Example #1
0
        //private void GlobalClickEventHandler(object sender, MouseButtonEventArgs input)
        //{
        //    if(input.RoutedEvent.Name != "MouseDown")
        //    {
        //        return;
        //    }

        //    var element = input.Device.Target;
        //    var uielement = element as UIElement;
        //    if(uielement != null)
        //    {
        //        var id = MonitorService.GetId(uielement);
        //        Point pt = input.GetPosition(this);

        //        if (!string.IsNullOrWhiteSpace(id))
        //            Console.WriteLine($"{DateTime.Now} User clicked element {id} on position {pt}");
        //    }
          
        //}


        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            AutomationElement textBox = AutomationUtilities.FindElementsByName(
            AutomationElement.RootElement,
            txtbox.Name)[0];
            setText(textBox, "papini");
        }
Example #2
0
        /// <summary>
        /// Creates videos directory if not exist and stores the videos in the folder
        /// </summary>
        /// <returns></returns>
        public string CreateVideoDirectory()
        {
            string date = DateTime.Now.ToString("MM-dd-yy");
            string path = new AutomationUtilities().GetProjectLocation();

            path = Path.Combine(path, "Videos");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            foreach (string dir in Directory.GetDirectories(path))
            {
                if (!dir.Contains(date))
                {
                    Directory.Delete(dir, true);
                }
            }
            path = Path.Combine(path, "Videos_On_" + date);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                log.Info("===>Directory created:=>" + path);
            }
            return(path);
        }
Example #3
0
    public void VerifyInput()
    {
        //
        // Start the application we are testing
        //
        string sampleAppPath      = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), "SampleApp.exe");
        OutOfProcessSettings oops = new OutOfProcessSettings(new ProcessStartInfo(sampleAppPath), null, null);
        AutomatedApplication a    = AutomatedApplication.Start(oops);

        try
        {
            a.WaitForMainWindow(TimeSpan.FromSeconds(10));

            //
            // Discover various elements in the UI
            //
            AutomationElement inputTextBox  = AutomationUtilities.FindElementsById(a.MainWindow, "inputTextBox")[0];
            AutomationElement outputTextBox = AutomationUtilities.FindElementsById(a.MainWindow, "outputTextBox")[0];
            AutomationElement appendButton  = AutomationUtilities.FindElementsById(a.MainWindow, "appendButton")[0];

            //
            // Click on the input text box and simulate typing
            //
            string inputText    = "TestTest";
            string expectedText = inputText + "\n";

            WindowPattern winPattern = a.MainWindow.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern;
            Helpers.MoveToAndClick(inputTextBox);
            winPattern.WaitForInputIdle(1000);
            Microsoft.Test.Keyboard.Type(inputText);
            winPattern.WaitForInputIdle(1000);

            //
            // Now click the button
            //
            Helpers.MoveToAndClick(appendButton);
            winPattern.WaitForInputIdle(1000);

            //
            // Now, get the text of the outputTextBox and compare it against what's expected
            // Fail the test if expected != actual
            //
            TextPattern textPattern = outputTextBox.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
            string      actualText  = textPattern.DocumentRange.GetText(-1);

            //
            // Report the test result
            //
            Assert.AreEqual(expectedText, actualText);
        }

        finally
        {
            //
            // Close the tested application
            //
            a.Close();
        }
    }
Example #4
0
 public BaseClass()
 {
     new Waits().setWaits();
     baseLog = LogManager.GetLogger("BaseClass");
     baseLog.Info("Initializing waits..");
     balloon        = new BalloonPopuUp();
     _autoutilities = new AutomationUtilities();
 }
Example #5
0
        /// <summary>
        /// Parameterized Constructor with the SheetName
        /// </summary>
        /// <params>Sheetname as String</params>
        /// <return>none</returns>

        public ExcelManager(string sheetName)
        {
            _autoutilities   = new AutomationUtilities();
            excelPath        = _autoutilities.GetKeyValue("INPUTDATAPATH", "ExcelDataPath");
            ExcelApp         = new Application();
            ExcelApp.Visible = true;
            MyBook           = ExcelApp.Workbooks.Open(excelPath);
            MySheet          = (Worksheet)MyBook.Worksheets.get_Item(sheetName); // Explicit cast is not required here
        }
    public void VerifyWindowAppearance()
    {
        //
        // Start the application we are testing
        //
        string sampleAppPath   = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), "SampleApp.exe");
        AutomatedApplication a = new OutOfProcessApplication(new OutOfProcessApplicationSettings
        {
            ProcessStartInfo = new ProcessStartInfo(sampleAppPath),
            ApplicationImplementationFactory = new UIAutomationOutOfProcessApplicationFactory()
        });

        a.Start();

        try
        {
            a.WaitForMainWindow(TimeSpan.FromSeconds(10));
            Thread.Sleep(1000);  // Ensure that the Vista/Win7 window creation animation is complete

            var mainWindow = a.MainWindow as AutomationElement;


            //
            // Discover the checkbox in the UI, then click it
            //
            AutomationElement styleBox = AutomationUtilities.FindElementsById(mainWindow, "styleBox")[0];
            Helpers.MoveToAndClick(styleBox);

            //
            // Capture the window image and compare to the master image by generating a
            // diff image and processing the diff image with a tolerance map verifier
            //
            Snapshot toleranceMap = Snapshot.FromFile("ToleranceMap.png");
            Snapshot master       = Snapshot.FromFile("Master.png");
            Snapshot actual       = Snapshot.FromWindow((IntPtr)mainWindow.Current.NativeWindowHandle, WindowSnapshotMode.ExcludeWindowBorder);
            Snapshot difference   = actual.CompareTo(master);

            master.ToFile(@"Master-expected.png", ImageFormat.Png);
            actual.ToFile(@"Master-actual.png", ImageFormat.Png);
            difference.ToFile(@"Master-difference.png", ImageFormat.Png);

            //
            // Report the test result
            //
            SnapshotVerifier verifier = new SnapshotToleranceMapVerifier(toleranceMap);
            Assert.AreEqual(VerificationResult.Pass, verifier.Verify(difference));
        }
        finally
        {
            //
            // Close the tested application
            //
            a.Close();
        }
    }
Example #7
0
        /// <summary>
        /// Creates properties file for all the suites
        /// </summary>
        public static string CreatePropertiesFile()
        {
            string path = new AutomationUtilities().GetProjectLocation();

            path = Path.Combine(path, "Resources");
            path = Path.Combine(path, "Reporter.properties");
            FileInfo f = new FileInfo(path);

            if (!f.Exists)
            {
                f.Create();
            }
            return(path);
        }
Example #8
0
    public void VerifyWindowAppearance()
    {
        //
        // Start the application we are testing
        //
        string sampleAppPath      = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), "SampleApp.exe");
        OutOfProcessSettings oops = new OutOfProcessSettings(new ProcessStartInfo(sampleAppPath), null, null);
        AutomatedApplication a    = AutomatedApplication.Start(oops);

        try
        {
            a.WaitForMainWindow(TimeSpan.FromSeconds(10));

            //
            // Discover the checkbox in the UI, then click it
            //
            AutomationElement styleBox = AutomationUtilities.FindElementsById(a.MainWindow, "styleBox")[0];
            Helpers.MoveToAndClick(styleBox);
            Thread.Sleep(1000);  // Ensure that the Vista/Win7 window creation animation is complete

            //
            // Capture the window image and compare to the master image by generating a
            // diff image and processing the diff image with a tolerance color verifier
            //
            Snapshot master     = Snapshot.FromFile(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Master0.png"));
            Snapshot actual     = Snapshot.FromWindow((IntPtr)a.MainWindow.Current.NativeWindowHandle, WindowSnapshotMode.ExcludeWindowBorder);
            Snapshot difference = actual.CompareTo(master);
            master.ToFile(@"Master0-expected.png", ImageFormat.Png);
            actual.ToFile(@"Master0-actual.png", ImageFormat.Png);
            difference.ToFile(@"Master0-difference.png", ImageFormat.Png);

            //
            // Report the test result
            //
            SnapshotVerifier verifier = new SnapshotColorVerifier(Color.Black, new ColorDifference(255, 18, 18, 18));
            Assert.AreEqual(VerificationResult.Pass, verifier.Verify(difference));
        }

        finally
        {
            //
            // Close the tested application
            //
            a.Close();
        }
    }
Example #9
0
        private void DrawEdgeTestApi(string fromId, string toId)
        {
            RunInBackground(
                delegate {
                var fromElement = AutomationUtilities.FindElementsById(GetGraphControlAutomationElement(), fromId);
                var toElement   = AutomationUtilities.FindElementsById(GetGraphControlAutomationElement(), toId);
                // Normally we would use GetClickablePoint here. However, the AutomationPeer takes the value returned and
                // then looks whether there really is either the element or a descendant at that point. And that goes
                // wrong as soon as there is an edge overlapping a node. The AutomationPeer sees the edge and determines
                // that the clickable point is invalid and throws an exception.
                // To work around that we use the same default logic AutomationPeers have for determining a clickable
                // point: Just take the center of the bounding box. It should work most of the time, and in this case we
                // don't particularly care whether an edge overlays the *target* node, for example. The edge doesn't react
                // in that case anyway. And even if it overlays the source node there's still a good chance that our
                // initial drag point will work.
                var fromBounds = fromElement[0].Current.BoundingRectangle;
                var toBounds   = toElement[0].Current.BoundingRectangle;
                var fromPoint  = new Point((int)(fromBounds.X + fromBounds.Width / 2),
                                           (int)(fromBounds.Y + fromBounds.Height / 2));
                var toPoint = new Point((int)(toBounds.X + toBounds.Width / 2),
                                        (int)(toBounds.Y + toBounds.Height / 2));

                Mouse.MoveTo(fromPoint);
                Thread.Sleep(50);
                Mouse.Down(MouseButton.Left);
                Thread.Sleep(50);
                // If we're trying to create a self-loop we have to drag outside the node first, otherwise it's just a
                // click that selects the node.
                if (fromPoint == toPoint)
                {
                    Mouse.MoveTo(new Point((int)fromBounds.X - 10, (int)fromBounds.Y - 10));
                    Thread.Sleep(50);
                    // Note: The following mini-move is necessary due to how yFiles does state transitions while finding a
                    // suitable target for drawing the edge. It just generates one additional MouseEvent on the node.
                    // This is also only necessary when drawing self-loops, so in many real-world cases it can be left out.
                    Mouse.MoveTo(new Point(fromPoint.X + 1, fromPoint.Y + 1));
                    Thread.Sleep(50);
                }
                Mouse.MoveTo(toPoint);
                Thread.Sleep(50);
                Mouse.Up(MouseButton.Left);
            },
                delegate { });
        }
Example #10
0
        public override IMessages Run()
        {
            Messages messages = new Messages();

            try
            {
                if (!string.IsNullOrEmpty(this.Script))
                {
                    return(AutomationUtilities.OpenUrl(this.Url, this.Script));
                }
                else
                {
                    Process.Start(this.Url);
                }
            }
            catch (Exception e)
            {
                messages.AddException(e);
            }

            return(messages);
        }
Example #11
0
        public void VerifyInput()
        {
            AutomationElement rootElement;
            Process           appProcess = AutomationHelpers.StartProcess(new ProcessStartInfo("SampleApp.exe"), out rootElement);

            AutomationElement inputTextBox  = AutomationUtilities.FindElementsById(rootElement, "inputTextBox")[0];
            AutomationElement outputTextBox = AutomationUtilities.FindElementsById(rootElement, "outputTextBox")[0];
            AutomationElement button        = AutomationUtilities.FindElementsById(rootElement, "appendButton")[0];

            string inputText    = "TestTest";
            string expectedText = inputText + "\n";

            WindowPattern winPattern = (WindowPattern)rootElement.GetCurrentPattern(WindowPatternIdentifiers.Pattern);

            AutomationHelpers.MoveToAndClick(inputTextBox);
            winPattern.WaitForInputIdle(1000);
            Microsoft.Test.Keyboard.Type(inputText);
            winPattern.WaitForInputIdle(1000);
            AutomationHelpers.MoveToAndClick(button);
            winPattern.WaitForInputIdle(1000);

            object o;

            outputTextBox.TryGetCurrentPattern(TextPatternIdentifiers.Pattern, out o);
            TextPattern pattern    = (TextPattern)o;
            string      actualText = pattern.DocumentRange.GetText(-1);

            try
            {
                Assert.AreEqual(expectedText, actualText, "The text did not match. Expected: {0}  Actual: {1}", expectedText, actualText);
            }
            finally
            {
                AutomationHelpers.CloseWindow(rootElement);
                appProcess.WaitForExit();
            }
        }
Example #12
0
        public void VerifyWindowAppearance()
        {
            ApplicationDriver driver = new ApplicationDriver(typeof(SampleApp.App));

            driver.WaitForIdleUi();
            AutomationElement window        = AutomationUtilities.FindElementsById(AutomationElement.RootElement, "sampleAppWindow")[0];
            AutomationElement styleBox      = AutomationUtilities.FindElementsById(window, "styleBox")[0];
            AutomationElement captureRegion = AutomationUtilities.FindElementsById(window, "captureContainer")[0];

            AutomationHelpers.MoveToAndClick(styleBox);
            driver.WaitForIdleUi();

            try
            {
                // Capture the actual pixels from the bounds of the screen rectangle
                Snapshot actual = Snapshot.FromRectangle(AutomationHelpers.GetElementSize(captureRegion));
                LogFile(actual, "Actual.png");

                // Load the reference/master data from a previously saved file
                Snapshot master = Snapshot.FromFile(Path.Combine(TestContext.TestDeploymentDir, "Master0.png"));
                LogFile(master, "Master.png");

                // Log the outcome of the test, only on failure to save disk space.
                // For test stability in scenarios of varying window styles, consider:
                //  -cropping the capture region to eliminate the border rectangle
                //  -Testing on a well controlled test environment
                if (CompareImages(actual, master) == VerificationResult.Fail)
                {
                    Assert.Fail("Initial State test failed. Actual should look like Master image. Refer to logged images under:" + TestContext.TestLogsDir);
                }
            }
            finally
            {
                AutomationHelpers.CloseWindow(window);
                driver.Join();
            }
        }
Example #13
0
        /// <summary>
        /// Method for initializing RemoteDriver and Invoke Remote driver based on browser type specified in config file ie  If the browser type is null it will take as ff and other than chrome,ff/firefox or null ,  it will provide an error message of invalid browser type
        /// </summary>
        /// <params>None</params>
        /// <return>WebDriver Reference</returns>

        public IWebDriver InitialiseRemoteDriver(string sBrowserType)
        {
            _autoutilities = new AutomationUtilities();
            //  string sBrowserType = _autoutilities.GetKeyValue("BROWSER", "Browser").ToLower();
            string _ip = _autoutilities.GetKeyValue("REMOTE", "IP");

            switch (sBrowserType)
            {
            case "ie":
            case "iexplore":
                SetRemoteDriver("internet explorer", _ip);
                break;

            case "ff":
            case "firefox":
                SetRemoteDriver("firefox", _ip);
                break;

            case "chrome":
                SetRemoteDriver("chrome", _ip);
                break;

            case "safari":
                SetRemoteDriver("safari", _ip);
                break;

            case "":
                SetRemoteDriver("firefox", _ip);
                break;

            default:
                Assert.Fail(" Browser name mentioned in config file is Invalid");
                break;
            }
            return(GetRemoteDriver());
        }
Example #14
0
        public void FaultAppendText()
        {
            //This is a work-around, Xunit moves the reference dll's at run time so we need to call register
            //from the test, instead of TestApiCore.
            string processorArch = DetectProccessorArchitecture();

            ComRegistrar.Register(@".\FaultInjectionEngine\" + processorArch + @"\FaultInjectionEngine.dll");

            string sampleAppPath = "SampleApp.exe";

            //Create the FaultRule and FaultSession
            FaultRule rule = new FaultRule(
                "SampleApp.Window1.Append(string, string)",
                BuiltInConditions.TriggerOnEveryCall,
                BuiltInFaults.ReturnValueFault(""));

            FaultSession session = new FaultSession(rule);

            //Start the app
            ProcessStartInfo        psi     = session.GetProcessStartInfo(sampleAppPath);
            OutOfProcessApplication testApp = new OutOfProcessApplication(
                new OutOfProcessApplicationSettings
            {
                ProcessStartInfo = psi,
                ApplicationImplementationFactory = new UIAutomationOutOfProcessApplicationFactory()
            });

            testApp.Start();


            try
            {
                testApp.WaitForMainWindow(TimeSpan.FromSeconds(15));

                // Discover various elements in the UI
                AutomationElement mainWindowElement = (AutomationElement)testApp.MainWindow;
                AutomationElement inputTextBox      = AutomationUtilities.FindElementsById(mainWindowElement, "inputTextBox")[0];
                AutomationElement outputTextBox     = AutomationUtilities.FindElementsById(mainWindowElement, "outputTextBox")[0];
                AutomationElement appendButton      = AutomationUtilities.FindElementsById(mainWindowElement, "appendButton")[0];

                // Click on the input text box and simulate typing
                string inputText    = "TestTest";
                string expectedText = ""; //expected text should be nothing since we intercept the Append method

                WindowPattern winPattern = mainWindowElement.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern;
                Helpers.MoveToAndClick(inputTextBox);
                winPattern.WaitForInputIdle(inputWaitTime);
                Microsoft.Test.Input.Keyboard.Type(inputText);
                winPattern.WaitForInputIdle(inputWaitTime);

                // Now click the button
                Helpers.MoveToAndClick(appendButton);
                winPattern.WaitForInputIdle(inputWaitTime);

                // Now, get the text of the outputTextBox and compare it against what's expected
                // Fail the test if expected != actual
                TextPattern textPattern = outputTextBox.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
                string      actualText  = textPattern.DocumentRange.GetText(-1);

                // Report the test result
                Assert.Equal <string>(expectedText, actualText);
            }
            finally
            {
                // Close the tested application
                testApp.Close();
            }
        }
Example #15
0
        /// <summary>
        ///Method for setting the Remote Driver for GRID as well as Sauce Labs
        /// </summary>
        /// <params>browsertype as String and IP as String</params>
        /// <return>none</returns>
        public void SetRemoteDriver(string sBrowserType, string ip)
        {
            _autoutilities = new AutomationUtilities();
            string executionMode = _autoutilities.GetKeyValue("MODEOFEXECUTION", "ExecutionMode").ToLower();

            try
            {
                /// compare the execution mode and IP that are specified in config file is Grid then execute the test in Grid else execute in saucelabs
                if (executionMode.Equals("remote") && _autoutilities.GetKeyValue("REMOTE", "IP").Contains("4444"))
                {
                    DesiredCapabilities capabilities = new DesiredCapabilities();
                    capabilities.SetCapability(CapabilityType.BrowserName, sBrowserType);
                    capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
                    this.Driver = new RemoteWebDriver(new Uri("http://" + ip + "/wd/hub"), capabilities, TimeSpan.FromSeconds(300));
                    this.Driver.Manage().Cookies.DeleteAllCookies();
                }
                //Running on Browser Stack ....
                else if (executionMode.Equals("remote") && _autoutilities.GetKeyValue("REMOTE", "IP").Contains("browserstack"))
                {
                    DesiredCapabilities capability = new DesiredCapabilities();
                    capability.SetCapability("os", "OS X");
                    capability.SetCapability("os_version", "Mojave");
                    capability.SetCapability("browser", "Safari");
                    capability.SetCapability("browser_version", "12.0");
                    capability.SetCapability("resolution", "1920x1080");
                    capability.SetCapability("project", "Mac_Safari12");
                    capability.SetCapability("build", "Build_Test");
                    capability.SetCapability("browserstack.user", "silpavajja2");
                    capability.SetCapability("browserstack.key", "3BqtD3z8zqJn4ZEqyZy7");

                    this.Driver = new RemoteWebDriver(new Uri("http://" + ip + "/wd/hub"), capability, TimeSpan.FromSeconds(300));
                }
                // execute the test using saucelabs
                else if (executionMode.Equals("remote") && _autoutilities.GetKeyValue("REMOTE", "IP").Contains("saucelabs"))
                {
                    string SAUCE_LABS_ACCOUNT_NAME = _autoutilities.GetKeyValue("REMOTE", "SAUCE_LABS_ACCOUNT_NAME");
                    string SAUCE_LABS_ACCOUNT_KEY  = _autoutilities.GetKeyValue("REMOTE", "SAUCE_LABS_ACCOUNT_KEY");
                    // string browserName = _autoutilities.GetKeyValue("BROWSER", "Browser").ToLower();
                    string version  = "34";
                    string platform = "Windows 7";
                    DesiredCapabilities desiredCapabilites = new DesiredCapabilities(sBrowserType, version, Platform.CurrentPlatform); // set the desired browser
                    desiredCapabilites.SetCapability("platform", platform);                                                            // operating system to use
                    desiredCapabilites.SetCapability("username", SAUCE_LABS_ACCOUNT_NAME);                                             // supply sauce labs username
                    desiredCapabilites.SetCapability("accessKey", SAUCE_LABS_ACCOUNT_KEY);                                             // supply sauce labs account key
                    //      desiredCapabilites.SetCapability("name", TestContext.CurrentContext.Test.Name); // give the test a name
                    this.Driver = new RemoteWebDriver(new Uri("http://" + ip + "/wd/hub"), desiredCapabilites, TimeSpan.FromSeconds(300));
                    this.Driver.Manage().Cookies.DeleteAllCookies();
                }

                MaximizeBrowser();
            }
            catch (WebException e)
            {
                log.Error("Error while Initializing the Remote Webdriver " + e.Message);
                Assert.Fail("Error while Initializing the Remote Webdriver " + e.Message.Replace('{', '[').Replace('}', ']'));
            }
            catch (Exception e)
            {
                log.Error("Error while Initializing the Remote Webdriver " + e.Message);
                Assert.Fail("Error while Initializing the Remote Webdriver " + e.Message.Replace('{', '[').Replace('}', ']'));
            }
        }