Browser opens many times while Geb testing - selenium-webdriver

I wrote the following test for my simple Spring Boot Web application:
#SpringApplicationConfiguration(classes=[PDK])
#WebIntegrationTest
#DirtiesContext
class GebMainpageSpec extends GebSpec {
#Autowired
WebApplicationContext context;
def setup() {
System.setProperty("webdriver.chrome.driver", "chromedriver/win32/chromedriver.exe");
browser.driver = new ChromeDriver();
browser.baseUrl = "http://localhost:8080/";
}
def 'Static page present and works, check without pages'() {
when:
go ""
then:
assert title == "MyApp"
}
def 'Static page present and works, check WITH pages'() {
when:
to Mainpage
then:
LoginWithFormUsername.value() == "root"
}
}
These tests are apparently work, i.e. they pass or fail depending on page data.
The problem is that it opens TWO instances of Chrome browser to operate (by number of tests).
How to prevent that? May be reuse browser? Or may be close it after each test?
UPDATE
If I add something like below
def cleanupSpec() {
browser.driver.quit()
}
then all my tests startin to run twice, moreover, each second run they try with HtmlUnit (i.e. with "in memory" web browser, not Chrome).

You shouldn't instantiate the driver yourself when using GebSpec because it already handles the lifecycle of a driver instance through a browser instance it lazy initializes in it's getBrowser() method.
See the sections of The Book of Geb about how Geb interacts with WebDriver instances and about configuring the driver to be used via the config script to learn more.

Related

How to test single registration page using selenium web driver and provide test report to development team?

I know basic selenium web driver and also written code using Page Object Model in TestNG frame work for one small application registration and login page.
Bu i don't know, how can provide test report to development team and what are the check points for automation testing please help me.
Example:
Assume my application have two pages like Registration and signin page
My code:
public class Sample {
Authentication_Locators authenticate;
WebDriver d = null;
#BeforeTest
public void beforeTest() throws Exception {
d = InitDriver.wbDriver("chrome", testData.getProperty("testUrl"));
authenticate = PageFactory.initElements(d,
Authentication_Locators.class);
}
#Test (priority = 0)
public void signIn() throws Exception {
Thread.sleep(1000);
authenticate.userName.sendKeys("user1");
authenticate.password.sendKeys("password1");
authenticate.signin.Click();
}
}
TesgNG creates HTML report of the execution which is located in the current working directory under results folder with name emailable_report. Also for more accurate reports you can also use Soft and hard asserts.
Hope this helps.

App Certification fails because of PreLaunch Test

When I run the App Certification on my Template 10 based app, I get the following error:
Error Found: The app prelaunch validation detected the following errors:◦The app failed prelaunch test - 49581RisingSoundMedia.ElectionCentral_1.1.7.0_x64__xrbjpqg44kdgm.
•Impact if not fixed: The app will take a longer time to launch, even when prelaunch is enabled.
•How to fix: In the OnLaunched method implementation of the app, ensure you handle the LaunchActivatedEventArgs.PreLaunch option to be prelaunch event aware.
Obviously I can't override the OnLaunched even with Template 10 because the Bootstrap class seals it.
I tried overriding the OnPreLaunchAsync and setting continueStartup = false; but it did not fix the problem.
Any ideas?
This seems to be a known issue with Windows App Cert Kit: https://developer.microsoft.com/en-us/windows/develop/app-certification-kit
"The App Prelaunch Validation test will fail ig you run on a version of Windows-10 released before version 1607(Windows Anniversary Edition). Note that this test is not run as part of the final certification for Windows Store submissions"
Resolution: To ensure the results to this test pass, test with Windows-10 SDK Version (14393) running on Windows-10 Anniversary Edition.
Turns out that I was able to publish to the store, and it passed certification even though it failed the local Windows App Cert Kit locally.
Yes i had this problem, first have you updated to the lastest version of Template 10 (1.1.4): https://www.nuget.org/packages/template10
Next what I had to do was move all of my code that was in OnInitializeAsync and OnStartAsync that was in app.xaml.cs into the App().
You need to keep OnInitializeAsync and OnStartAsync as lean as possible, you should keep only the essential Template10 code in them and add your specific code in App().
public override Task OnInitializeAsync(IActivatedEventArgs args)
{
// content may already be shell when resuming
if ((Window.Current.Content as ModalDialog) == null)
{
// setup hamburger shell
var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
Window.Current.Content = new ModalDialog
{
DisableBackButtonWhenModal = true,
Content = new Shell(nav),
ModalContent = new Views.Busy(),
};
}
return Task.CompletedTask;
}
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
NavigationService.Navigate(typeof(MainView));
return Task.CompletedTask;
}
In App() I added all my my initialization methods for my app so my App() looks liek this:
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
WindowsCollectors.Metadata |
WindowsCollectors.UnhandledException |
WindowsCollectors.PageView |
WindowsCollectors.Session
);
this.InitializeComponent();
var element = new ViewModelLocator();
//Template10.Services.LoggingService.LoggingService.Enabled = true;
//Template 10 stuff
// DOCS: https://github.com/Windows-XAML/Template10/wiki/Docs-%7C-Cache
CacheMaxDuration = TimeSpan.FromDays(1);
// DOCS: https://github.com/Windows-XAML/Template10/wiki/Docs-%7C-BackButton
ShowShellBackButton = SettingsService.Instance.UseShellBackButton;
// DOCS: https://github.com/Windows-XAML/Template10/wiki/Docs-%7C-SplashScreen
SplashFactory = (e) => new Views.Splash(e);
//My code here
ApiRoot.Instance.Init();
InitDeviceTypeAndResource();
InitApiLanguage();
InitAppLanguage();
InitABCRatings();
//For updating Tiles
RegisterBackgroundTask();
}
I hope that this helps you out!

Same functionality as HTTPClient in Codename one

I was wondering how I can achieve something like an HTTPClient.
I tried WebBrowser class but it seems that the execution continues even though the URL specified has not yet loaded.
public void testWebBrowser(){
final WebBrowser b = new WebBrowser(){
#Override
public void onLoad(String url) {
BrowserComponent c = (BrowserComponent)this.getInternal();
JavascriptContext ctx = new JavascriptContext(c);
// I want this Javascript context here
}
};
// just a test URL
b.setURL("http://youtube.com");
// Suppose to get the Javascript context here though it executes without waiting for the whole page to load
}
How can I get the JS Context from within a WebBrowser context? Like a synchronous execution
WebBrowser browser = new WebBrowser();
browser.setURL("someURL");
// wait execution till the whole page in "someURL" loads till it executes the next line
BrowserComponent c = (BrowserComponent)browser.getInternal();
JavascriptContext ctx = new JavascriptContext(c);
If I understand correctly you are trying to create a scraping solution?
That's probably not the ideal approach since this will actually create a web browser which you then need to automate with JavaScript. I would suggest you create a webservice that encapsulates the HttpClient functionality and drive it with ConnectionRequest. This way when the web site changes you can just fix your server in a way seamless to your installed base.

cookies validation using selenium

I am new to selenium. Actually I am working on some cookie validation project, which requires me to manually check the cookies present before and after clicking on some consent link in multiple browsers (Firefox, ie, chrome, safari).
Previously in the phase 1 project I ran a qtp script to treat the firefox as a window object and capture screenshots, but that is quite troublesome if the resolution changes or any minor look-n-feel changes. Also it is quite difficult to manage and it works on firefox only and I needed to write the same script again for chrome and safari. Apart from this since QTP is licensed product and currently we are using seat license so I can't run it on multiple machines to speed up execution.
So I thought moving to Selenium. As of now my requirement is:
1. open the page - take the screenshot once page loaded.
2. check the cookies using firebug or any other way - take the screenshot
3. click the link to close the consent - take screenshot once consent closed.
4. refresh the page and again check the cookies using firebug - take screenshot
So I done some research on selenium and found that I can validate the cookies using verifyCookie but still I need screenshot of firebug window for cookies. So I got stuck here.
please help me out here..
I found some possible way to do this on Firefox but now I was looking forward for something similar for Chrome if that possible. Thanks
Selenium cannot interact with firefox extensions, or the browser in the way you want it to.
What you can do is collect a list of cookies on the page by doing:
driver.manage().getCookies()
This will give you a list of all cookies that are visible to Selenium. Please note that this is the same as the cookies that are visible in the JavaScript console (Not all cookies are visible via JavaScript, for example cookies set with the HTTPOnly attribute) using:
document.cookie
I would suggest you use getCookies() to programatically validate the cookies.
In selenium IDE if you want to take screenshot of the page use captureEntirePageScreenshot command
captureEntirePageScreenshot | D:\\test.png |
D:\\test.png - path of file where you want to save the file
Got some solution
public class Selenium1st {
/**
* #param args
*/
public static void main(String[] args) throws IOException, AWTException{
// TODO Auto-generated method stub
System.setProperty("webdriver.firefox.bin","C:\\Program Files (x86)\\Mozilla Firefox\\Firefox.exe");
FirefoxProfile firefoxProfile = new FirefoxProfile();
String domain = "extensions.firebug.";
firefoxProfile.setPreference("app.update.enabled", false);
firefoxProfile.addExtension(new File("E:\\softs\\selenium-2.29.0\\firebug\\firebug-1.11.2-fx.xpi"));
firefoxProfile.setPreference(domain + "currentVersion", "1.11.2");
firefoxProfile.setPreference("extensions.firebug.cookies.enableSites", true);
firefoxProfile.setPreference("extensions.firebug.allPagesActivation", "on");
firefoxProfile.setPreference(domain + "framePosition", "bottom");
firefoxProfile.setPreference(domain + "defaultPanelName", "cookies");
WebDriver driver = new FirefoxDriver(firefoxProfile);
driver.get("http://www.google.com/webhp?complete=1&hl=en");
WebElement query = driver.findElement(By.name("q"));
query.sendKeys("Cheese");
query.sendKeys("\n");
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(new Dimension(1024, 768)));
File path = new File("E:\\abc");//Path to your file
if(path.getName().indexOf(".jpg") == -1){
path = new File(path.getPath() + ".jpg");
}
ImageIO.write(img, "jpg", path);
}
}
might be useful.

Will Prism OnDemand module loading work in an OOB scenerio?

Should the loading of OnDemand Prism modules work in an OOB scenerio? If so, I cannot seem to make it work. Everything is currently working in browser without any problems. Specifically I:
register my modules in code:
protected override IModuleCatalog GetModuleCatalog() {
var catalog = new ModuleCatalog();
Uri source;
if( Application.Current.IsRunningOutOfBrowser ) {
source = IsolatedStorageSettings.ApplicationSettings[SOURCEURI] as Uri;
}
else {
var src = Application.Current.Host.Source.ToString();
src = src.Substring( 0, src.LastIndexOf( '/' ) + 1 );
source = new Uri( src );
IsolatedStorageSettings.ApplicationSettings[SOURCEURI] = source;
IsolatedStorageSettings.ApplicationSettings.Save();
}
if( source != null ) {
var mod2 = new ModuleInfo { InitializationMode = InitializationMode.OnDemand,
ModuleName = ModuleNames.mod2,
ModuleType = "mod2.Module, mod2.Directory, '1.0.0.0', Culture=neutral, PublicKeyToken=null" ),
Ref = ( new Uri( source, "mod2.xap" )).AbsoluteUri };
catalog.AddModule( mod2 );
}
// per Jeremy Likeness - did not help.
Application.Current.RootVisual = new Grid();
return ( catalog );
}
later request for the module to be loaded is made:
mModuleManager.LoadModule( ModuleNames.mod2 );
and wait for a response to an event published during the initialization of that loaded module.
The module appears to never be loaded, and when the application is running under the debugger there will be a message box that states that the web server returned a 'not found' error. I can take the requesting url for the module and enter it into Firefox and download the module with no problem.
I have not been able to find any reference to this actually being workable, but it seems as though it should. The most I have found on the subject is a blog entry by Jeremy Likeness, which covers loading modules in MEF, but applying his knowledge here did not help.
The server is localhost (I have heard it mentioned that this might cause problems). The server has a clientaccesspolicy.xml file - although I don't expect that is needed.
I am using the client stack and register it during app construction:
WebRequest.RegisterPrefix( Current.Host.Source.GetComponents( UriComponents.SchemeAndServer, UriFormat.UriEscaped ), WebRequestCreator.ClientHttp );
Followup questions:
Can all of the xaps be installed to the client desktop in some manner - or only the main application xap? specify them in appmanifest.xml somehow??
Is it worth it make this work if only the application.xap is installed and the rest of the xaps must be downloaded anyway?
Once I worked on a similar scenario. The trick is having the modules stored in isolated storage and use a module loader that reads from isolated storage when working offline.
This is because otherwise, you can't get download the modules that are in a different .xap file than the Shell.
Thanks,
Damian
It is possible to hook custom module loaders into Prism if you're willing to tweak the Prism source and build it yourself. I was actually able to get this to work pretty easily - in our app, I look on disk first for the module, and if it's not found, I fall back to loading it from the server via a third-party commercial HTTP stack that supports client certificates.
To do this, download the Prism source code, and locate the Microsoft.Practices.Composite.Modularity.XapModuleTypeLoader class. This class uses another Prism class, Microsoft.Practices.Composite.Modularity.FileDownloader, to download the .xap content; but it instantiates it directly, giving you no chance to inject your own or whatever.
So - in XapModuleTypeLoader, I added a static property to set the type of the downloader:
public static Type DownloaderType { get; set; }
Then I modified the CreateDownloader() method to use the type specified above in preference to the default one:
protected virtual IFileDownloader CreateDownloader() {
if (_downloader == null) {
if (DownloaderType == null) {
_downloader = new FileDownloader();
} else {
_downloader = (IFileDownloader)Activator.CreateInstance(DownloaderType);
}
}
return _downloader;
}
When my app starts up, I set the property to my own downloader type:
XapModuleTypeLoader.DownloaderType = typeof(LocalFileDownloader);
Voila - now Prism calls your code to load its modules.
I can send you my LocalFileDownloader class as well as the class it falls back to to load the .xap from the web if you're interested... I suspect though that if you look at Prism's FileDownloader class you'll see that it's simple enough.
With regard to your other questions, the clientaccesspolicy.xml file is probably not needed if the URL the app is installed under is the same one you're talking to, or if you're in elevated trust.
The .xaps can definitely be pre-installed on the client, but it's a bit of work. What we did was write a launcher app that is a standalone .NET 2.0 desktop app. It downloads the main .xap plus certain modules* (checking for updates and downloading only as needed), then uninstalls/reinstalls the app if necessary, then launches the app. The last two are done via sllauncher.exe, which is installed as part of Silverlight. Here's a good intro to that: http://timheuer.com/blog/archive/2010/03/25/using-sllauncher-for-silent-install-silverlight-application.aspx.
Assuming you're running under elevated trust, it should also be possible to pre-fetch the module .xaps from within the SL client, but before they're actually requested due to user action. You'd just need to put them in a folder under My Documents somewhere, and then use the custom module loading approach described above to pull them from there.
*In our case, our main .xap is 2/3 of the application. The rest of our .xaps are small, so we download them on-the-fly, with the exception of some .xaps we created as containers for third-party components. We don't expect to update those very often, so we pre-install them.

Resources