How to enable acceptInsecureCerts on Karate UI test - google-chrome

I'm trying to write a Karate UI test for my webpage which currently has a self signed certificate and hence blocked by the browser by default. According to the documentation, when acceptInsecureCerts parameter is enabled, this check should be bypassed. But I can't find the correct syntax to pass this parameter to the driver. This is my (simplified) feature file:
Feature: browser automation 1
Background:
* def session = { capabilities: { acceptInsecureCerts: true } }
* configure driver = { type: 'chrome', showDriverLog: true, showProcessLog: true, showBrowserLog: true, webDriverSession: '#(session)' }
Scenario: load demo page
Given driver 'https://127.0.0.1:8443/demo'
* waitUntil('document.readyState == "complete"')
* print 'page loaded'
* screenshot()
Then delay(2000).text('body')
When I run this, I get
13:31:25.237 [nioEventLoopGroup-2-1] DEBUG c.intuit.karate.driver.DriverOptions - << {"id":9,"result":{"result":{"type":"string","value":"Your connection is not private Attackers might be trying to steal your information from ...

Hold on, chrome is NOT webdriver based, so the webDriverSession will not apply. It would for chromedriver.
I did a quick search and the best I could find is this: ignore-certificate-errors + headless puppeteer+google cloud
So not sure if this works:
addOptions: ['--ignore-certificate-errors']
Please report what you find so that it helps others ! Another reference is this, but not sure how up to date it is: https://peter.sh/experiments/chromium-command-line-switches

Related

Chrome manifest V3 extensions and externally_connectable documentation

After preparing the migration of my chrome manifest V2 extension to manifest V3 and reading about the problems with persistent service workers I prepared myself for a battle with the unknown. My V2 background script uses a whole bunch of globally declared variables and I expected I need to refactor that.
But to my great surprise my extension background script seems to work out of the box without any trouble in manifest V3. My extension uses externally_connectable. The typical use case for my extension is that the user can navigate to my website 'bla.com' and from there it can send jobs to the extension background script.
My manifest says:
"externally_connectable": {
"matches": [
"*://localhost/*",
"https://*.bla.com/*"
]
}
My background script listens to external messages and connects:
chrome.runtime.onMessageExternal.addListener( (message, sender, sendResponse) => {
log('received external message', message);
});
chrome.runtime.onConnectExternal.addListener(function(port) {
messageExternalPort = port;
if (messageExternalPort && typeof messageExternalPort.onDisconnect === 'function') {
messageExternalPort.onDisconnect(function () {
messageExternalPort = null;
})
}
});
From bla.com I send messages to the extension as follows
chrome.runtime.sendMessage(EXTENSION_ID, { type: "collect" });
From bla.com I receive messages from the extension as follows
const setUpExtensionListener = () => {
// Connect to chrome extension
this.port = chrome.runtime.connect(EXTENSION_ID, { name: 'query' });
// Add listener
this.port.onMessage.addListener(handleExtensionMessage);
}
I tested all scenarios including the anticipation of the famous service worker unload after 5 minutes or 30 seconds inactivity, but it all seems to work. Good for me, but something is itchy. I cannot find any documentation that explains precisely under which circumstances the service worker is unloaded. I do not understand why things seem to work out of the box in my situation and why so many others experience problems. Can anybody explain or refer to proper documentation. Thanks in advance.

next-pwa runtimecaching does not produce strategies

I start using next-pwa and the basic setup worked like a charm. Now it want to play with the runtime caching option, which does not work for me:
My next.config.js includes the standard cache entries plus a custom one that should use the strategy StaleWhileRevalidate for each request going to /api/todoitem:
const withPWA = require("next-pwa");
const defaultRuntimeCaching = require("next-pwa/cache");
module.exports = withPWA({
reactStrictMode: true,
pwa: {
dest: "public",
disable: false, // disable PWA
register: true,
skipWaiting: true,
runtimeCaching: [
{
urlPattern: /\/api\/todoitem/,
method: "GET",
handler: "StaleWhileRevalidate",
options: {
cacheName: "todoApp-api",
expiration: {
maxEntries: 64,
maxAgeSeconds: 24 * 60 * 60, // 24 hours
},
},
},
...defaultRuntimeCaching,
],
},
});
Restart npm run dev fire up the browser -> fetch GET /api/todoitem -> and console.log tells me
workbox Network request for '/api/todoitem' returned a response with status '200'.
workbox Using NetworkOnly to respond to '/api/todoitem'
I tried a number of combinations of regexes, including defaultRuntimeCaching before or after my runtimeCache entry to no avail.
Any hints to get custom runtimeCache rules working would be greatly appreciated.
next.js 12.0.7
next-pwa 5.4.4
node.js v14.18.2
After some research I found:
In development mode, next-pwa creates a service worker that disables caching. It even tells me so on the console ;-):
[PWA] Build in development mode, cache and precache
are mostly disabled. This means offline support is
disabled, but you can continue developing other
functions in service worker.
When building the app via next build it creates a service worker that uses my custom rules and when starting the app next start the rules seem to work.
A bit hard to debug, so I tried to set mode: "production" on my developer machine but then for some reason the service worker gets rebuilt at every other request which brings the app to a grinding halt.

Cypress throwing SecurityError

I am currently running with Chrome 74 and trying to use Cypress to test a style-guide in my app. When I load up Cypress it throws this error:
SecurityError: Blocked a frame with origin "http://localhost:3000"
from accessing a cross-origin frame.
Please let me know if there is a solution to this!
I had tried to follow along with this:
https://github.com/cypress-io/cypress/issues/1951
But nothing has changed/worked for me. :(
My code is shown below: cypress/plugins/index.js
module.exports = (on, config) => {
on('before:browser:launch', (browser = {}, args) => {
// browser will look something like this
// {
// name: 'chrome',
// displayName: 'Chrome',
// version: '63.0.3239.108',
// path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
// majorVersion: '63'
// }
if (browser.name === 'chrome') {
args.push('--disable-site-isolation-trials');
return args
}
if (browser.name === 'electron') {
args['fullscreen'] = true
// whatever you return here becomes the new args
return args
}
})
}
in my cypress/support/index.js
This will load the site before every test I run to save myself from having to write cy.visit in every test.
beforeEach(() =>{
cy.visit('http://localhost:3000/style-guide')
})
I had the very same issue yesterday and the answer from #jsjoeio in the cypress issue #1951 you've referenced in your question actually helped me.
So basically only thing I've done was to modify my cypress.json and add following value:
{
"chromeWebSecurity": false
}
You can disable security to overcome this issue.
Go to cypress.json file.
Write { "chromeWebSecurity": false } and save.
Run the test again.
I had exactly the same problem, I advise you to do as DurkoMatko recommends. Documentation chromeWebSecurity
But I encountered another problem with a link pointing to localhost in an iframe.
If you want to use a link in an iframe I recommend this :
cy.get('iframe').then((iframe) => {
const body = iframe.contents().find('body');
cy.wrap(body).find('a').click();
});
I have also faced this issue. My application was using service workers. Disabling service workers while visiting a page solved the issue.
cy.visit('index.html', {
onBeforeLoad (win) {
delete win.navigator.__proto__.serviceWorker
}
})
Ref: https://glebbahmutov.com/blog/cypress-tips-and-tricks/#disable-serviceworker
So, at least for me, my further problem was an internal one with tokens, logins, etc. BUT!
the code I posted for how the index in the plugin folder is correct to bypass the chrome issue. That is how you want to fix it!
Goto your cypress.json file.
Set chrome web security as false
{
"chromeWebSecurity": false
}
To get around these restrictions, Cypress implements some strategies involving JavaScript code, the browser's internal APIs, and network proxying to play by the rules of same-origin policy.
Acess your project
In file 'cypress.json' insert
{
"chromeWebSecurity": false
}
Reference: Cypress Documentation

How do I get actual config in puppeteer?

I want to conditionally execute some code based on the headless config attribute in puppeteer (passed in the .launch function).
e.g. : when I use the .type function, if it is running with headless: true, I don't want any delay. Else, add some { delay: 200 }.
How can I retrieve the headless value from the config?
Edit (thanks to #AndreyLushnikov comment)
You can figure out if puppeteer runs (non-)headless at runtime by checking browser.process() spawnargs for --headless switch with which Chromium were (or not) launched:
const headless = browser.process().spawnargs.includes("--headless") ? true : false;
console.log("Headless? " + headless);
With the latest puppeteer version to date (1.7.0), this is how I retrieved the config :
const client = await page.target().createCDPSession();
const response = await client.send('Browser.getBrowserCommandLine');
page.headless = response.arguments.includes('--headless');
See this github issue for more information

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();");