How to automate from protractor to set browser offline? - google-chrome

I have a scenario where it has to be tested when there is no connection. To automate this i thought making browser as offline and to test the scenario is feasible. Someone please help me how do we set browser offline during execution of a test from protractor? is there a way to access browser preferences from protractor ?

Since I don't see what language you are coding in I'm gonna assume it's Java
this func turns off the wifi:
protected void disConnectInternet() throws IOException {
Map map = new HashMap();
map.put("offline", true);
map.put("latency", 5);
map.put("download_throughput", 500);
map.put("upload_throughput", 1024);
CommandExecutor executor = ((ChromeDriver)driver).getCommandExecutor();
Response response = executor.execute(
new Command(((ChromeDriver)driver).getSessionId(), "setNetworkConditions", ImmutableMap.of("network_conditions", ImmutableMap.copyOf(map))));
}

Related

How to automate the maximize the window of an Electron application using Selenium

Currently I am performing End to end testing of an application developed using electron framework. I am able to open the application using selenium and also able to interact wit h the form controls etc. When I open the application it opens in a minimized mode and I want to maximize it by performing the keystrokes ALT + Space + X The following is my code,it executes with out any errors but does not maximize the window.
[TestMethod]
public void TestDispneseLogin()
{
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.BinaryLocation = #"C:\CorumDispense-win32-x64\CorumDispense.exe";
chromeOptions.AddArgument("start-maximized");
DesiredCapabilities capability = new DesiredCapabilities();
capability.SetCapability(CapabilityType.BrowserName, "Chrome");
capability.SetCapability("chromeOptions", chromeOptions);
IWebDriver driver = new ChromeDriver(chromeOptions);
Thread.Sleep(2000);
//maximize the window
Actions keyAction = new Actions(driver);
keyAction.SendKeys(Keys.Alt);
keyAction.SendKeys(Keys.Space);
keyAction.SendKeys(Convert.ToString('\u0078'));
keyAction.Build().Perform();
//input the text into the patient text box
driver.FindElement(By.Id("patient")).SendKeys("bharat");
}
I have also tried the option
keyAction.KeyDown(Keys.Alt).KeyDown(Keys.Space).SendKeys(Convert.ToString('\u0078')).Perform();
But it fails and gives me the following error
Test Name: TestDispneseLogin
Test FullName: LightHouseTestScenarios.TestScenarios.ElectronTest.TestDispneseLogin
Test Source: C:\Automation\SeleniumProjects\Lighthouse\LightHouseTestScenarios\TestScenarios\ElectronTest.cs : line 83
Test Outcome: Failed
Test Duration: 0:00:05.1098462
Result StackTrace:
at OpenQA.Selenium.Interactions.Internal.SingleKeyAction..ctor(IKeyboard keyboard, IMouse mouse, ILocatable actionTarget, String key)
at OpenQA.Selenium.Interactions.Actions.KeyDown(IWebElement element, String theKey)
at OpenQA.Selenium.Interactions.Actions.KeyDown(String theKey)
at LightHouseTestScenarios.TestScenarios.ElectronTest.TestDispneseLogin() in C:\Automation\SeleniumProjects\Lighthouse\LightHouseTestScenarios\TestScenarios\ElectronTest.cs:line 99
Result Message:
Test method LightHouseTestScenarios.TestScenarios.ElectronTest.TestDispneseLogin threw exception:
System.ArgumentException: key must be a modifier key (Keys.Shift, Keys.Control, or Keys.Alt)
Parameter name: key
I have also tried the below but with no success
keyAction.SendKeys(Keys.Alt + Keys.Space + Convert.ToString('\u0078')).Perform();
and also this option
driver.Manage().Window.Maximize();
Can some one help me solving this issue,thanks in advance.
cheers,
bharadwaj.
When you need using electron features, the easy way to do it is working with the executeScript method.
instead:
driver.Manage().Window.Maximize();
replace with:
driver.executeScript("require('electron').remote.BrowserWindow.getFocusedWindow().maximize();");
For python-selenium implementation, following worked for Electron:
self.session.execute_script('window.moveTo(0, 0);window.resizeTo(screen.width, screen.height);')
It does not exactly maximize the window but sets the window size equal to screen size. Might not work for all types of applications.
try this code.. Its working for me...
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("require('electron').remote.BrowserWindow.getFocusedWindow().maximize();");

Appium - running browser tests without clearing browser data

I'm testing a web application on Chrome, Android (real device, not emulator) using Appium. Whenever I launch a test, all browser data (bookmarks, history etc.) is deleted. Is there any way to stop this from happening?
I tried setting the noReset capability to true, but that didn't help.
Thank you in advance for any help
public static Uri testServerAddress = new Uri("http://127.0.01:4723/wd/hub"); // Appium is running locally
public static TimeSpan INIT_TIMEOUT_SEC = TimeSpan.FromSeconds(180);
public void SetUpTest()
{
if (driver == null)
{
DesiredCapabilities testCapabilities = new DesiredCapabilities();
testCapabilities.SetCapability("browserName", "Chrome");
testCapabilities.SetCapability("platformName", "Android");
testCapabilities.SetCapability("deviceName", "S(Galaxy S5)");
testCapabilities.SetCapability("noReset", true);
AppUrl = "http://www.google.com/"; //for example
driver = new RemoteWebDriver(testServerAddress, testCapabilities, INIT_TIMEOUT_SEC);
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, globalTimeoutInSec));
driver.Navigate().GoToUrl(AppUrl);
}
}
Chromedriver always starts totally fresh, nothing is keeping.
There is option to re-use the existent one (using desired capability androidUseRunningApp) but unfortunately Appium any way will kill it.
Please see more details in this post

Windows Phone app not receiving push notification from Parse.com

I have followed this tutorial on setting up Parse push notification in a Windows Phone app. This is my code:
public App() {
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Language display initialization
InitializeLanguage();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached) {
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
// Initialize the Parse client with your Application ID and .NET Key found on
// your Parse dashboard
ParseClient.Initialize("grpTmrClet8K35yeXg2HQKK8wl59VeC9ijH0I0dn", "os8EfSFq9maPBtDJ91Mq0xnWme8fLANhttTPAqKu");
// After calling ParseClient.Initialize():
this.Startup += async (sender, args) =>
{
// This optional line tracks statistics around app opens, including push effectiveness:
ParseAnalytics.TrackAppOpens(RootFrame);
// By convention, the empty string is considered a "Broadcast" channel
// Note that we had to add "async" to the definition to use the await keyword
await ParsePush.SubscribeAsync("testchannel");
};
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private async void Application_Launching(object sender, LaunchingEventArgs e) {
await ParseAnalytics.TrackAppOpenedAsync();
}
When I send a push notification from the Parse dashboard it doesn't get received. I have tried running both on the emulator (Windows Phone 8.0) and device (8.1), with app in foreground, background and closed with the same negative result.
When I use a channel like "testchannel" above and use the segment options, the channel name appears in the dropdown list of options indicating that the app is at least connecting Parse, but it just wont receive the notifications.
Hope someone can help me identify what I am missing. Thanks in advance.
If you are developing a Windows Phone 8.1 app, make sure you've enabled toast notification in the manifest file.
I don't quite understand everything about Parse just yet, but this is what works for me.
In App.xaml.cs:
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
ParseClient.Initialize("wSjuNTbtjVLRaedXvOoaf9S5cTbkuQohTulNZ2vS", "nWZMhXRet9Wotlgikb9aUdKf5GFtRiMvduw7w68z");
}
We subscribe and enable analytics OnLaunched:
protected async override void OnLaunched(LaunchActivatedEventArgs e)
//Generated codes go here
await ParsePush.SubscribeAsync("testchannel");
await ParseAnalytics.TrackAppOpenedAsync();
That would simply do the trick. You should modify the code according to your needs. Hope this helps.

How to disable print option for PDF in iframe

I'm showing a PDF in an <iframe> as follows:
<iframe src="/itextPdfServlet" height="600px" width="700px"></iframe>
I would like to disable the print option for this. How can I achieve this?
my servlet
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fullPath = (String) request.getSession().getAttribute("fullPath");
response.setContentType("application/pdf");
ServletOutputStream out = null;
try{
File file = new File( fullPath );
FileInputStream fileIn = new FileInputStream( file );
out = response.getOutputStream();
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfReader reader = new PdfReader(fileIn);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("fullPath"));
stamper.setEncryption("reader_password".getBytes(), "permission_password".getBytes(),
~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING ), PdfWriter.STANDARD_ENCRYPTION_128);
stamper.close();
PdfImportedPage page = writer.getImportedPage(reader, 1);
document.newPage();
cb.addTemplate(page, 0, 0);
document.add(new Paragraph("my timestamp"));
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
document.close();
}catch(Exception e){
}
}
Treating visitors or customers like enemies might not be in your best interest. You can disable printing in the options of a PDF file when generating the file:
PdfReader reader = new PdfReader("testpdf.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("my-pdf-file.pdf"));
stamper.setEncryption("reader_password".getBytes(), "permission_password".getBytes(), ~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING ), PdfWriter.STANDARD_ENCRYPTION_128);
stamper.close();
But I know at least one PDF viewer which doesn't care about these options. I know a lot of tools that can make screenshots, so even if your PDF makes me angry, I just print the screenshot. There are screen automation tools that will even page through the file for me, make a screenshot for every page and a little script will compile a new PDF from that.
You can also try to disable printing with JavaScript in the web browser. That would then force me to install a tool like Tampermonkey or similar that kicks your script out of my browser.
Usually, a much better approach is to put watermarks in the PDF file which say who downloaded / bought the file and then harass them, if the PDF file leaks out. That way, you're not annoying everyone.
That said, consider how much your PDFs are worth and how much suing someone would cost (money and negative feedback wise). Most of the time, investing your money in great service will earn you much more money than you can lose by people printing PDFs (they would also have to do something with those prints before it could have any impact on your revenue, rights, ...)
I have never worked with iText, but I assume this might help you a little:
iText Java disable print pdf

Getting WP8 web requests to be synchronous

I am trying to port some code from a Windows form application to WP8, and have run into some issues regarding asynchronous calls.
The basic idea is to do some UAG authentication. In the Windows form code, I do a GET on the portal homepage and wait for the cookies. I then pass these cookies into a POST request to the validation URL the UAG server. It all works fine in the form, since all the steps are sequential and synchronous.
Now, when I started porting this to WP8, first thing I noticed was that GetResponse() wasn't available, instead I had to use BeginGetResponse(), which is asynchronous and calls a callback function. This is no good for me, since I need to ensure this step finishes before I do the POST
My Windows form code looks like this (taken from http://usingnat.net/sharepoint/2011/2/23/how-to-programmatically-authenticate-to-uag-protected-sharep.html):
private void Connect()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Url);
request.CookieContainer = new CookieContainer();
request.UserAgent = this.UserAgent;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
//Get the UAG generated cookies from the response
this.Cookies = response.Cookies;
}
}
private void ValidateCredentials()
{
//Some code to construct the headers goes here...
HttpWebRequest postRequest = (HttpWebRequest)WebRequest.Create(this.ValidationUrl);
postRequest.ContentType = "application/x-www-form-urlencoded";
postRequest.CookieContainer = new CookieContainer();
foreach (Cookie cookie in this.Cookies)
{
postRequest.CookieContainer.Add(cookie);
}
postRequest.Method = "POST";
postRequest.AllowAutoRedirect = true;
using (Stream newStream = postRequest.GetRequestStream())
{
newStream.Write(data, 0, data.Length);
}
using (HttpWebResponse response = (HttpWebResponse)postRequest.GetResponse())
{
this.Cookies = response.Cookies;
}
public CookieCollection Authenticate()
{
this.Connect();
this.ValidateCredentials();
return this.Cookies;
}
The thing is this code relies on synchronous operation (first call Connect(), then ValidateCredentials() ), and it seems WP8 does not support that for Web requests. I could combine the two functions into one, but that won't solve my problem fully since later on this needs to be expanded to access resources behind the UAG, so it would need a modular design.
Is there a way to "force" synchronization?
Thanks
You can still continue your steps in the call back function using the asynchronous model. Or you can use the new HttpClient which can be used with the await keyword so you can program your stuff in a synchronous way.
You can get HttpClient through nuget
install-package Microsoft.Net.Http