Example #1
0
        public void RefreshFramesList()
        {
            Exception outException;
            bool      isOk = false;

            isOk = UIActions.PerformSlowOperation(
                "Operation: Refresh All Frames List",
                () =>
            {
                BrowserPageFrame rootFrame           = WebSpyBrowser.GetPageFramesTree();
                BrowserPageFrame[] currentPageFrames = rootFrame.ToList().ToArray();
                WebSpyBrowser.SwitchToDefaultContent();
                view.UpdatePageFramesList(currentPageFrames);
            },
                out outException,
                null,
                TimeSpan.FromMinutes(1)
                );

            if (!isOk)
            {
                MyLog.Error("Failed to refresh All Frames List");
                MyLog.Exception(outException);
                if (outException != null)
                {
                    throw outException;
                }
            }
        }
Example #2
0
        public void Get_Frames_Tree()
        {
            string[] expectedTitles = new string[]
            {
                "DefaultContent",
                "firstFrame",
                "secondFrame",
                "secondFrame.idIframeInsideSecondFrame",
                "thirdFrame",
                "thirdFrame.0"
            };


            Helper.RunDefaultBrowser();
            Helper.LoadTestFile("page_with_frames.html");


            BrowserPageFrame        rootFrame = WebSpyBrowser.GetPageFramesTree();
            List <BrowserPageFrame> allFrames = rootFrame.ToList();

            string[] actualTitles = allFrames.Select(i => i.ToString()).ToArray();

            actualTitles.Should().Equal(expectedTitles);

            WebSpyBrowser.CloseDriver();
        }
        public void StopDriver()
        {
            MyLog.Write("StopDriver - Entered");
            view.DisableDriverStartButton();

            view.DriverIsStopping();

            Exception threadException;

            UIActions.PerformSlowOperation(
                "Operation: Stop WebDriver instance",
                () =>
            {
                Presenters.WebSpyMainPresenter.StopVisualSearch();
                WebSpyBrowser.CloseDriver();
            },
                out threadException,
                null,
                TimeSpan.FromMinutes(10)
                );

            if (threadException != null)
            {
                MyLog.Exception(threadException);
            }

            view.EnableDriverStartButton();

            wasBrowserStarted = false;
            MyLog.Write("StopDriver - Exited");
        }
        internal void RunScript()
        {
            string scriptFromEditor = view.GetJavaScriptCodeFromEditor();

            Exception outException;
            bool      isOk   = false;
            object    result = null;

            isOk = UIActions.PerformSlowOperation(
                "Operation: RunScript() / Executing JavaScript Snippet",
                () =>
            {
                result = WebSpyBrowser.ExecuteJavaScript(scriptFromEditor);
            },
                out outException,
                null,
                TimeSpan.FromMinutes(1)
                );

            if (!isOk)
            {
                MyLog.Error("RunScript() Failed to execute JavaScript snippet");
                MyLog.Exception(outException);
                if (outException != null)
                {
                    throw outException;
                }
            }

            string consoleOut = DumpObject(result);

            view.AppendConsole(consoleOut);
        }
Example #5
0
        public void CloseDriver_should_close_the_opened_browser_instance()
        {
            Profile browserProfile = new Profile();

            browserProfile.ProfileConfig.activation.browserName = WebDriverOptions.browser_Firefox;

            WebDriverOptions options = new WebDriverOptions()
            {
                BrowserProfile = browserProfile,
                IsRemote       = false,
            };

            string specialTitle = "WebSpyBrowser.CloseDriver TEST TEST";

            string[] specialWindows = new string[] { };

            specialWindows = GetDesktopWindowsWithSpecialTitle(specialTitle);
            specialWindows.Length.Should().Be(0, "Expected no windows with title <{0}> at the beginning", specialTitle);

            WebSpyBrowser.Initialize(options);

            string changeTitleScript = string.Format("document.title = '{0}'", specialTitle);

            WebSpyBrowser.ExecuteJavaScript(changeTitleScript);

            specialWindows = GetDesktopWindowsWithSpecialTitle(specialTitle);
            specialWindows.Length.Should().Be(1, "Expected only 1 window with title <{0}> after new driver was created", specialTitle);

            WebSpyBrowser.CloseDriver();

            specialWindows = GetDesktopWindowsWithSpecialTitle(specialTitle);
            specialWindows.Length.Should().Be(0, "Expected no windows with title <{0}> after the driver was closed", specialTitle);
        }
Example #6
0
        internal Task TakeAndSaveScreenshot()
        {
            var task = new Task(() =>
            {
                EnsureScreenshotsDirectoryExists();

                MyLog.Write("Action: TakeAndSaveScreenshot()");
                try
                {
                    var pageUrl        = new Uri(WebSpyBrowser.GetDriver().Url);
                    var host           = pageUrl.Host;
                    string newFileName = DateTime.Now.ToString("yyyy-dd-M__HH-mm-ss") + "_" + host + ".png";
                    string newFilePath = Path.Combine(ScreenshotsLocation, newFileName);

                    Screenshot screenshot = WebSpyBrowser.TakeScreenshot();
                    screenshot.SaveAsFile(newFilePath, ImageFormat.Png);
                }
                catch (Exception ex)
                {
                    MyLog.Write("Action: TakeAndSaveScreenshot() FAILED");
                    MyLog.Exception(ex);
                    throw;
                }
            });

            task.Start();
            return(task);
        }
Example #7
0
        public static object JS(string script)
        {
            var driver = WebSpyBrowser.GetDriver();
            IJavaScriptExecutor jsExec = driver as IJavaScriptExecutor;

            return(jsExec.ExecuteScript(script));
        }
Example #8
0
        public void RefreshWindowsList()
        {
            Exception outException;
            bool      isOk = false;

            isOk = UIActions.PerformSlowOperation(
                "Operation: Refresh All Windows List",
                () =>
            {
                BrowserWindow[] currentWindows = WebSpyBrowser.GetBrowserWindows();
                string currentWindowHandle     = WebSpyBrowser.GetCurrentWindowHandle();
                view.UpdateBrowserWindowsList(currentWindows, currentWindowHandle);
            },
                out outException,
                null,
                TimeSpan.FromMinutes(1)
                );

            if (!isOk)
            {
                MyLog.Error("Failed to refresh All Windows List");
                if (outException != null)
                {
                    throw outException;
                }
            }
        }
Example #9
0
        public void Enumerate_Windows_Popup()
        {
            Helper.RunDefaultBrowser();
            Helper.LoadTestFile("page_opens_several_tabs.html");

            Helper.ClickId("openTab2");
            Helper.ClickId("openTab3");
            Helper.ClickId("openJavaScriptPopup");


            BrowserWindow[] actualWindows = WebSpyBrowser.GetBrowserWindows();

            string[] expectedWindowTitles = new string[]
            {
                "Page Tab1",
                "JavaScript Popup",
                "Page Tab3",
                "Page Tab2"
            };

            string[] actualTitles = actualWindows.Select(w => w.Title).ToArray();

            actualTitles.Should().Contain(expectedWindowTitles);

            WebSpyBrowser.CloseDriver();
        }
Example #10
0
        internal void HighLightElementFromNode(TreeNode treeNode)
        {
            string xpath = GetXPathFromTreeNode(treeNode);
            var    by    = WebSpyBrowser.ConvertLocatorSearchMethodToBy(LocatorSearchMethod.XPath, xpath);

            WebSpyBrowser.HighlightElement(by);
        }
Example #11
0
        public void ProcessCommands()
        {
            var command = WebSpyBrowser.GetNextCommand();

            if (command is GetXPathFromElement)
            {
                var getXPathCommand = command as GetXPathFromElement;
                view.UpdateVisualSearchResult(getXPathCommand.XPathValue);
            }
            else if (command is AddElement)
            {
                var addElementCommand = command as AddElement;

                SimpleFrame      simpleFrame;
                BrowserPageFrame browserPageFrame = view.getCurrentlyChosenFrame();
                if (browserPageFrame != null)
                {
                    List <string> childs = new List <string>();
                    string        parentTitle;
                    if (browserPageFrame.ParentFrame != null)
                    {
                        parentTitle = browserPageFrame.ParentFrame.GetTitle();
                    }
                    else
                    {
                        parentTitle = "none";
                    }
                    if (browserPageFrame.ChildFrames != null)
                    {
                        foreach (BrowserPageFrame b in browserPageFrame.ChildFrames)
                        {
                            childs.Add(b.GetTitle());
                        }
                    }

                    simpleFrame = new SimpleFrame(browserPageFrame.Index, browserPageFrame.LocatorNameOrId, browserPageFrame.GetTitle(), parentTitle, childs);
                }
                else
                {
                    simpleFrame = new SimpleFrame(-1, "noFrameChosen", "noFrameChosen", "noFrameChosen", null);
                }

                bool emptyHtmlId = String.IsNullOrEmpty(addElementCommand.ElementId);
                var  element     = new WebElementDefinition()
                {
                    Name        = addElementCommand.ElementCodeName,
                    HtmlId      = addElementCommand.ElementId,
                    Xpath       = addElementCommand.ElementXPath,
                    HowToSearch = (emptyHtmlId) ? LocatorSearchMethod.XPath: LocatorSearchMethod.Id,
                    Locator     = (emptyHtmlId) ? addElementCommand.ElementXPath: addElementCommand.ElementId,
                    CssSelector = addElementCommand.ElementCssSelector,
                    frame       = simpleFrame,
                    Action      = addElementCommand.Action
                };
                bool addNew = true;
                Presenters.SelectorsEditPresenter.UpdateWebElementWithAdditionalProperties(element);
                Presenters.PageObjectDefinitionPresenter.UpdatePageDefinition(element, addNew);
            }
        }
Example #12
0
        public static void LoadTestFile(string pageRelativePath)
        {
            string fullPath = Path.Combine(AssemblyDirectory(), "TestResource", pageRelativePath);
            Uri    uri      = new Uri(fullPath);

            string uriPath = uri.AbsoluteUri;

            WebSpyBrowser.GetDriver().Url = uriPath;
        }
Example #13
0
        internal void ShowElementInTree(ResultElement element)
        {
            IWebElement webElement = element.WebElement;
            string      xPath      = WebSpyBrowser.GetElementXPath(webElement);

            var travelNodes = GetTreeTravelDataFromXPath(xPath);

            FindTreeNode(travelNodes);
        }
Example #14
0
        internal void HighLightWebElement(WebElementDefinition element)
        {
            if (!IsValidForm())
            {
                return;
            }

            var by = WebSpyBrowser.ConvertLocatorSearchMethodToBy(element.HowToSearch, element.Locator);

            WebSpyBrowser.HighlightElement(by);
        }
        public void WebElementExplorer_Test()
        {
            Helper.RunDefaultBrowser();
            Helper.LoadTestFile("page_with_frames.html");

            Helper.ToFrame(secondFrame);

            WebSpyBrowser.InjectVisualSearch();

            //Helper.ClickId();

            throw new NotImplementedException();
        }
Example #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            var screenshot = WebSpyBrowser.TakeScreenshot();

            //screenshot.AsByteArray

            imgBox.Zoom = 100;

            using (var ms = new MemoryStream(screenshot.AsByteArray))
            {
                imgBox.Image = Image.FromStream(ms);
            }
        }
Example #17
0
        public static void RunDefaultBrowser()
        {
            var browserProfile = new Profile();

            browserProfile.ProfileConfig.activation.browserName = "Firefox";

            WebDriverOptions options = new WebDriverOptions()
            {
                BrowserProfile = browserProfile,
            };

            WebSpyBrowser.Initialize(options);
        }
Example #18
0
 internal void SwitchToFrame(BrowserPageFrame frame)
 {
     PauseWebElementExplorerProcessing();
     try
     {
         WebSpyBrowser.DestroyVisualSearch();
         WebSpyBrowser.GoToFrame(frame);
         MyLog.Write("FRAME: Switched to frame with Index= " + frame.Index + "; and Full Name:" + frame.ToString());
     }
     finally
     {
         ResumeWebElementExplorerProcessing();
     }
 }
Example #19
0
        internal async void RunScript(string code)
        {
            Presenters.WebSpyMainPresenter.DisplayLoadingIndicator(true);

            Task <string> t = new Task <string>(() =>
            {
                using (var engine = new JScriptEngine())
                {
                    engine.AddHostObject("driver", WebSpyBrowser.GetDriver());

                    ImportTypes(engine);

                    var uiPageObject = Presenters.PageObjectDefinitionPresenter.GetWebElementDefinitionFromTree();


                    foreach (var element in uiPageObject.Items)
                    {
                        IWebElement proxyElement = WebSpyBrowser.CreateWebElementProxy(element);
                        string name = element.Name;
                        engine.AddHostObject(name, proxyElement);
                    }

                    var result = engine.Evaluate(code) ?? "(none)";
                    return(result.ToString());
                }
            });


            string logLine = "done";

            try
            {
                t.Start();

                logLine = await t;
            }
            catch (Exception ex)
            {
                MyLog.Exception(ex);
                logLine = "ERROR: " + ex.Message;
                // TODO: FIX message --> Exception has been thrown by the target of invocation
                // \TODO: FIX message --> Exception has been thrown by the target of invocation
            }
            finally
            {
                view.AppendConsole(logLine + "\r\n");
                Presenters.WebSpyMainPresenter.DisplayLoadingIndicator(false);
            }
        }
        public bool TestRemoteHub(string url)
        {
            string result = "OK";
            bool   isOk   = true;

            try
            {
                WebSpyBrowser.TestRemoteHub(url);
            }
            catch (Exception e)
            {
                isOk   = false;
                result = "FAILED: " + e.Message;
            }
            view.SetTestResult(result, isOk);
            return(isOk);
        }
Example #21
0
 internal void SwitchToWindow(BrowserWindow window)
 {
     PauseWebElementExplorerProcessing();
     view.DisableSwitchToControls();
     try
     {
         WebSpyBrowser.GotoWindow(window);
         MyLog.Write("WINDOW: Switched to window/popup with WinID= "
                     + window.WindowHandle + "; and Title:" + window.Title);
         RefreshFramesList();
     }
     finally
     {
         ResumeWebElementExplorerProcessing();
         view.EnableSwitchToControls();
     }
 }
        public void StartDriver(WebDriverOptions browserOptions, bool shouldMaximizeBrowserWindow)
        {
            MyLog.Write("StartDriver - Entered");

            wasBrowserStarted = false;

            view.DisableDriverStartButton();

            Exception threadException;

            bool isSuccessful = UIActions.PerformSlowOperation(
                "Operation: Start new WebDriver instance",
                () =>
            {
                WebSpyBrowser.Initialize(browserOptions);
                wasBrowserStarted = true;

                if (shouldMaximizeBrowserWindow)
                {
                    WebSpyBrowser.Maximize();
                }
            },
                out threadException,
                null,
                TimeSpan.FromMinutes(10)
                );

            view.EnableDriverStartButton();

            if (isSuccessful)
            {
                SetDesiredCapabilities(browserOptions);
                view.DriverWasStarted();
            }
            else if (threadException != null)
            {
                throw threadException;
            }

            MyLog.Write("StartDriver - Exited");
        }
Example #23
0
        public void UpdateWebElementWithAdditionalProperties(WebElementDefinition element)
        {
            var by         = WebSpyBrowser.ConvertLocatorSearchMethodToBy(element.HowToSearch, element.Locator);
            var attributes = new Dictionary <string, string>();

            try
            {
                attributes = WebSpyBrowser.ReadElementAttributes(by);
            }
            catch (Exception e)
            {
                string errorMsg = string.Format(
                    "UpdateWebElementWithAdditionalProperties:\n" +
                    "Failed to find element: How={0};   Locator={1}\n" +
                    "With exception:\n {2}"
                    , element.HowToSearch.ToString()
                    , element.Locator.ToString()
                    , e.Message

                    );
                MyLog.Error(errorMsg);
            }


            if (attributes.Count == 0)
            {
                return;
            }

            element.HtmlTag = attributes["TagName"];
            attributes.Remove("TagName");

            WebElementHtmlAttributes elementAttrs = new WebElementHtmlAttributes();

            foreach (var attrKey in attributes.Keys)
            {
                elementAttrs.Add(attrKey, attributes[attrKey]);
            }

            element.AllHtmlTagProperties = elementAttrs;
        }
Example #24
0
        internal void UpdateTestHtmlDocumentView()
        {
            Presenters.WebSpyMainPresenter.PauseWebElementExplorerProcessing();

            HAP.HtmlDocument doc  = WebSpyBrowser.GetPageSource();
            HAP.HtmlNode     root = doc.DocumentNode.ChildNodes.FindFirst(@"html");

            string rootNodeName = RemoveNamespace(root.Name);
            var    treeRootNode = new TreeNode(rootNodeName);

            treeRootNode.Name = rootNodeName.ToLower();
            treeRootNode.Tag  = new HtmlTreeNodeData()
            {
                nodeXPath        = "/html",
                OriginalHtmlNode = root,
            };
            ParseHtmlNodes(treeRootNode, root.ChildNodes, "/html");

            view.AddTestHtmlNodes(treeRootNode);

            Presenters.WebSpyMainPresenter.ResumeWebElementExplorerProcessing();
        }
Example #25
0
        private void imgBox_Click(object sender, EventArgs args)
        {
            if (!ModifierKeys.HasFlag(Keys.Control))
            {
                return;
            }

            MouseEventArgs mouse = args as MouseEventArgs;



            int absoluteX = mouse.X; // + ;
            int absoluteY = mouse.Y; // + ;


            absoluteX = (Convert.ToInt32(absoluteX / imgBox.ZoomFactor) + Convert.ToInt32(imgBox.HorizontalScroll.Value / imgBox.ZoomFactor));
            absoluteY = Convert.ToInt32(absoluteY / imgBox.ZoomFactor) + Convert.ToInt32(imgBox.VerticalScroll.Value / imgBox.ZoomFactor);


            string script =
                @"(function showRectangle(x, y) {
                var rectangle = document.createElement('div');
                rectangle.style.border = '3px solid red';
                rectangle.style.position = 'absolute';
                
                rectangle.style.left = x + 'px';
                rectangle.style.top  = y + 'px';

                rectangle.style.width  = '100px';
                rectangle.style.height = '20px';

                document.body.appendChild(rectangle);
                setTimeout(function cbRemoveRectangle() {
                    doNastyStuff();
                }, 2000);
            })(arguments[0], arguments[1]);";

            WebSpyBrowser.ExecuteJavaScript(script, absoluteX, absoluteY);
        }
Example #26
0
        public void VisualSearch_UpdateSearchResult()
        {
            try
            {
                MyLog.Write("VisualSearch_UpdateSearchResult: Started");
                while (webElementExplorerStarted == true)
                {
                    if (!webElementExplorerThreadPaused)
                    {
                        try
                        {
                            if (!WebSpyBrowser.IsVisualSearchScriptInjected())
                            {
                                MyLog.Write("VisualSearch_UpdateSearchResult: Found the Visual search is not injected. Injecting");
                                WebSpyBrowser.InjectVisualSearch();
                            }

                            if (!webElementExplorerThreadPaused)
                            {
                                ProcessCommands();
                            }
                        }
                        catch (Exception e)
                        {
                            StopVisualSearch();
                            MyLog.Error("Visual search stopped:");
                            MyLog.Exception(e);
                        }
                    }
                    Thread.Sleep(VisualSearchQueryDelayMs);
                }
            }
            finally
            {
                StopVisualSearch();
                MyLog.Write("VisualSearch_UpdateSearchResult: Finished");
            }
        }
Example #27
0
        public void Initialize_should_be_able_to_start_new_browser()
        {
            Profile browserProfile = new Profile();

            browserProfile.ProfileConfig.activation.browserName = WebDriverOptions.browser_HtmlUnitWithJavaScript;

            WebDriverOptions options = new WebDriverOptions()
            {
                BrowserProfile = browserProfile,
                IsRemote       = true,
                RemoteUrl      = "http://localhost:4444/wd/hub/",
            };

            bool isSeleniumServerAvailable = true;

            try
            {
                WebSpyBrowser.TestRemoteHub(options.RemoteUrl);
            }
            catch (Exception e)
            {
                isSeleniumServerAvailable = false;
                Console.WriteLine("FAILED: " + e.Message);
            }

            if (!isSeleniumServerAvailable)
            {
                WebSpyBrowser.RunStandaloneServer("start_selenium_server.bat");
            }

            WebSpyBrowser.Initialize(options);

            var rempteDriver = (RemoteWebDriver)WebSpyBrowser.GetDriver();

            rempteDriver.Capabilities.BrowserName.Should().Be("htmlunit");

            WebSpyBrowser.CloseDriver();
        }
Example #28
0
        internal void StartVisualSearch()
        {
            WebSpyBrowser.InjectVisualSearch();
            if (visualSearchWorker != null)
            {
                visualSearchWorker.Abort();
                visualSearchWorker = null;
            }

            webElementExplorerStarted = true;

            visualSearchWorker = new Thread(VisualSearch_UpdateSearchResult);
            visualSearchWorker.IsBackground = true;
            visualSearchWorker.Start();

            while (!visualSearchWorker.IsAlive)
            {
                Application.DoEvents();
                System.Threading.Thread.Sleep(1);
            }

            view.VisuaSearchStarted();
        }
        internal void LoadCapabilities()
        {
            var remoteDriver = (RemoteWebDriver)WebSpyBrowser.GetDriver();

            foreach (var prop in _desiredCapabilitiesdata.GetType().GetProperties())
            {
                string capabilityName = prop.Name.Replace("__", ".");

                if (!remoteDriver.Capabilities.HasCapability(capabilityName))
                {
                    continue;
                }

                object driverValue = remoteDriver.Capabilities.GetCapability(capabilityName);
                if (driverValue == null)
                {
                    continue;
                }

                if (prop.PropertyType == typeof(bool?))
                {
                    bool?boolValue = GetValueOrNull <bool>(driverValue.ToString());
                    prop.SetValue(_desiredCapabilitiesdata, boolValue, null);
                }
                else if (prop.PropertyType == typeof(int?))
                {
                    int?intValue = GetValueOrNull <int>(driverValue.ToString());
                    prop.SetValue(_desiredCapabilitiesdata, intValue, null);
                }
                else
                {
                    prop.SetValue(_desiredCapabilitiesdata, driverValue.ToString(), null);
                }
            }
            InitDesiredCapabilities();
        }
Example #30
0
 internal void DisplayHtmlPageSource()
 {
     string htmlSource = WebSpyBrowser.GetHtml();
     view.FillHtmlCodeBox(htmlSource);
 }