Playwright: Saving session storage - playwright

I'm very new to Playwright. I'm trying to follow this https://playwright.dev/docs/auth#reuse-signed-in-state so I can login and then save the session for further tests.
My steps work fine in a test but once I've moved them to global-setup.ts I get a timeout:
import { chromium, FullConfig } from '#playwright/test'
async function globalSetup(config: FullConfig) {
const browser = await chromium.launch()
const page = await browser.newPage()
await page.goto('MYDOMAIN/login');
await page.locator("a[testid='googleSignIn']").click()
await page.locator("input[type='email']").fill('MYEMAIL')
await page.locator(
"button[class='VfPpkd-LgbsSe VfPpkd-LgbsSe-OWXEXe-k8QpJ VfPpkd-LgbsSe-OWXEXe-dgl2Hf nCP5yc AjY5Oe DuMIQc LQeN7 qIypjc TrZEUc lw1w4b']",
).click()
await page.locator("input[type='password']").fill('MYPASSWORD')
await page.locator(
"button[class='VfPpkd-LgbsSe VfPpkd-LgbsSe-OWXEXe-k8QpJ VfPpkd-LgbsSe-OWXEXe-dgl2Hf nCP5yc AjY5Oe DuMIQc LQeN7 qIypjc TrZEUc lw1w4b']",
).click()
// Save signed-in state to 'storageState.json'.
await page.context().storageState({ path: 'storageState.json' })
await browser.close()
}
export default globalSetup
The above steps log me in fine in a test but now I've set my config file to use the saved session storage:
storageState: 'storageState.json',
When I run a test I don't see a browser appear it just waits a minute and then says:
locator.click: Timeout 30000ms exceeded.
=========================== logs =========================== waiting for selector "button[class='VfPpkd-LgbsSe VfPpkd-LgbsSe-OWXEXe-k8QpJ
VfPpkd-LgbsSe-OWXEXe-dgl2Hf nCP5yc AjY5Oe DuMIQc LQeN7 qIypjc TrZEUc
lw1w4b']"
at ../../global-setup.ts:15
13 | await page.locator( 14 | "button[class='VfPpkd-LgbsSe
VfPpkd-LgbsSe-OWXEXe-k8QpJ VfPpkd-LgbsSe-OWXEXe-dgl2Hf nCP5yc AjY5Oe
DuMIQc LQeN7 qIypjc TrZEUc lw1w4b']",
15 | ).click()
| ^
The time out is the step just before I enter my password.
I'm running the tests with this command:
yarn playwright test login-page-tests --headed
Am I doing something wrong?

I wouldn't count on these google login class names. Did you try running something like:
await page.locator('text="Next"').click()

Related

Playwright hook / callback / try-catch to handle the overall test timeout

When the timeout specified as below in playwright.config.ts expires, Playwright simply blows away the browser. How can I catch this timeout expiry in my Playwright test script, and handle it gracefully? I would like to log the timeout and exit the test gracefully.
Thanks,
Sanjoy
// playwright.config.ts
import type { PlaywrightTestConfig } from '#playwright/test';
const config: PlaywrightTestConfig = {
timeout: 60000, // Timeout is shared between all tests.
I would like a hook / callback that can log the timeout and close the browser gracefully.

Trying to select an email field using playwright

Using playwright I am trying to do a simple login operation on a website
The steps are simple :
click on a Login button
Try to enter an email (Playwrights fails here)
I can see that the selector is getting to the correct field but fails to enter the username into the input (and times out instead)
async def login(url, username, password):
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
page = await browser.new_page()
await page.goto(url)
print(await page.title())
# Click login
await page.click('xpath=/html/body/nav[2]/div/ul/li[4]/a')
await page.pause()
# Wait for email popup
# await page.type('[placeholder="Enter your email address and hit enter"]', username)
await page.type('//input[#type="email" and not(#disabled)]', username, delay = 10) # fails here
await page.click('xpath=/html/body/app-main/app-widget/screen-layout/main/current-screen/div/screen-login/p[2]/button')
asyncio.run(login(url, username, password))
The error that I get is a timeout :
return await self.inner_send(method, params, False)
File "/Users/work/Documents/Code/venv/lib/python3.9/site-packages/playwright/_impl/_connection.py", line 63, in inner_send
result = next(iter(done)).result()
playwright._impl._api_types.TimeoutError: Timeout 30000ms exceeded.
=========================== logs ===========================
waiting for selector "//input[#type="email" and not(#disabled)]"
============================================================
This essentially means playwright was waiting for this element and no luck finding it, so it explodes after the default 30 seconds
I tried using
different xpaths
CSS selectors
Text selectors
I also tried using selenium and strangely the behavior is the same.
The website in question: https://epaper.thehindu.com/
That particular element on the website that I am trying to type into
<input _ngcontent-ttw-c171="" fieldloginemail="" type="email" placeholder="Enter your email address and hit enter" id="email" class="sub margin-0 empty" autocorrect="off" autocapitalize="off">
The question is : why playwright cannot find this input? (Playwright Inspector can clearly see it in broad daylight)
That whole element is iFrame. Get that iFrame first then type.
https://playwright.dev/docs/release-notes#frame-locators
As #senaid already pointed out, the element you want to access is inside an iframe. So you can use the iframe locator as given in the link provided by senaid and then use it to login.
loc = await page.frameLocator('#piano-id-u4ajR').locator('#email');
await loc.type("username");
Check for if any iFrame is there. If iframe is not there then you can try this.
const element = page.locator("//input[#type="email" and not(#disabled)]").first();
await element.focus();
await element.click();
await page.locator("//input[#type="email" and not(#disabled)]").first().fill(textTobeEntered)

arweave-sol option is not working well when uploading images for mainnet-beta on solana

I'm going to upload images to arweave-sol storage for mainnet-beta on solana, but am encountering on errors everytimes.
I have now 1.2 sol and know it's enough to upload images.
The errors are following.
wallet public key: xxxxxxxxxxxxxxxxxxxxx
Beginning the upload for 2 (img+json) pairs
started at: 1644902774661
initializing candy machine
initialized config for a candy machine with publickey: xxxxxxxxxxxxxxxxxxxxx
Uploading Size 2 { mediaExt: '.png', index: '0' }
Saved bundle upload result to cache.
Computed Bundle range, including 2 file pair(s) totaling 0.014MB.
Uploading bundle via bundlr... in multiple transactions
0.000002188 SOL to upload
Failed bundlr upload, automatically retrying transaction in 10s (attempt: 1) Error: Not enough funds to send data
at NodeUploader.dataItemUploader (/home/user/solana-mint/metaplex/js/packages/cli/node_modules/#bundlr-network/client/build/common/upload.js:43:23)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async uploadTransaction (/home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:520:13)
at async processBundle (/home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:535:11)
at async uploadV2 (/home/user/solana-mint/metaplex/js/packages/cli/src/commands/upload.ts:202:11)
at async Command.<anonymous> (/home/user/solana-mint/metaplex/js/packages/cli/src/candy-machine-v2-cli.ts:190:7)
Failed bundlr upload, automatically retrying transaction in 10s (attempt: 2) Error: Not enough funds to send data
at NodeUploader.dataItemUploader (/home/user/solana-mint/metaplex/js/packages/cli/node_modules/#bundlr-network/client/build/common/upload.js:43:23)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async uploadTransaction (/home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:520:13)
at async /home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:531:15
at async uploadTransaction (/home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:520:13)
at async processBundle (/home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:535:11)
at async uploadV2 (/home/user/solana-mint/metaplex/js/packages/cli/src/commands/upload.ts:202:11)
at async Command.<anonymous> (/home/user/solana-mint/metaplex/js/packages/cli/src/candy-machine-v2-cli.ts:190:7)
upload was not successful, please re-run. Error: Not enough funds to send data
at NodeUploader.dataItemUploader (/home/user/solana-mint/metaplex/js/packages/cli/node_modules/#bundlr-network/client/build/common/upload.js:43:23)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async uploadTransaction (/home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:520:13)
at async /home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:531:15
at async uploadTransaction (/home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:520:13)
at async /home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:531:15
at async uploadTransaction (/home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:520:13)
at async processBundle (/home/user/solana-mint/metaplex/js/packages/cli/src/helpers/upload/arweave-bundle.ts:535:11)
at async uploadV2 (/home/user/solana-mint/metaplex/js/packages/cli/src/commands/upload.ts:202:11)
at async Command.<anonymous> (/home/user/solana-mint/metaplex/js/packages/cli/src/candy-machine-v2-cli.ts:190:7)
how can I fix these errors?
Looks like you don't have fund on your wallet
" Error: Not enough funds to send data"
send sol to the address of your default file wallet
(make sure solana cli is installed then "solana address" will give you the address of your default wallet. the path of the default wallet is displayed when you type "solana config get")

What to change to prevent double request from service worker?

Please do not mark as duplicate. This is not an exact duplicate of the other similar questions here on SO. It's more specific and fully reproducible.
Clone this repo.
yarn && yarn dev
Go to localhost:3000 and make sure under (F12)->Applications->Service workers, the service worker is installed.
Go to Network tab and refresh a few times(F5)
Observe how the network requests are doubled.
Example of what I see:
Or if you want to do it manually follow the instructions below:
yarn create-next-app app_name
cd app_name && yarn
in public folder, create file called service-worker.js and paste the following code:
addEventListener("install", (event) => {
self.skipWaiting();
console.log("Service worker installed!");
});
self.addEventListener("fetch", (event) => {
event.respondWith(
(async function () {
const promiseChain = fetch(event.request.clone()); // clone makes no difference
event.waitUntil(promiseChain); // makes no difference
return promiseChain;
})()
);
});
open pages/index.js and just below import Head from "next/head"; paste the following code:
if (typeof window !== "undefined" && "serviceWorker" in navigator) {
window.addEventListener("load", function () {
// there probably needs to be some check if sw is already registered
navigator.serviceWorker
.register("/service-worker.js", { scope: "/" })
.then(function (registration) {
console.log("SW registered: ", registration);
})
.catch(function (registrationError) {
console.log("SW registration failed: ", registrationError);
});
});
}
yarn dev
go to localhost:3000 and make sure the service worker has been loaded under (F12)Applications/Service Workers
Go to the Network tab and refresh the page a few times. See how the service worker sends two requests for each one
What do I need to change in the service-worker.js code so that there are no double requests?
This is how Chrome DevTools shows requests and is expected.
There is a request for a resource from the client JavaScript to the Service Worker and a request from the Service Worker to the server. This will always happen unless the service worker has the response cached and does not need to check the server for an update.
Does not seems the right way to initialize service worker in Next.js.You may need to look into next-pwa plugin to do it right.Here is the tutorial PWA with Next.js
If anyone is looking for an answer to the original question 'What to change to prevent double request from service worker?', specifically for network requests.
I've found a way to prevent it. Use the following in the serviceworker.js. (This also works for api calls etc.)
self.addEventListener('fetch', async function(event) {
await new Promise(function(res){setTimeout(function(){res("fetch request allowed")}, 9999)})
return false
});

Taking a screenshot of a page running WebGL using puppeteer

I'm trying to take a screenshot of a page that is running webGL based Cesium. If I just take the screenshot, the page will be loaded, but the webGL wont be finished loading.
If I use the built in networkidle0 or networkidle2, the screenshot is never taken. Here is my code.
And here is the website I'm trying to take a picture of: https://www.arelplane.com/#arelenglish
const puppeteer = require('puppeteer');
module.exports = {
takeScreenshot: (userId) => {
(async () => {
const browser = await puppeteer.launch({
headless: false,
args: [
'--headless',
'--hide-scrollbars'
]
});
const page = await browser.newPage();
await page.goto('https://www.arelplane.com/#arelenglish', {"waitUntil" : "networkidle0"});
await page.screenshot({path: 'example.png'});
await browser.close();
})();
return "Successful API call!";
}
}
Your code is saying headless: false, along with an argument called --headless which means headless: true. Puppeteer will get confused.
Jokes aside, here is what I saw on the network tab.
The network tab says it loads at least 66 requests with at least or more than 1.5s for each resource (idk why it loaded slower on my default chrome).
Same from a page load test (click to see the report), which basically says it loads 170+ requests for around 40+ seconds.
The default timeout is 30 seconds, but it loads data for 90+ seconds.
Here is the argument to deal with navigation timeout.
await page.goto('https://www.arelplane.com/#arelenglish', {"waitUntil" : "networkidle0", "timeout": 0}); // timeout: 0 will disable navigation timeout
Either disable the timeout or increase it to say 120 seconds or something around that range. Here is my code,
puppeteer.launch({headless: false}).then(async browser => {
const page = await browser.newPage();
await page.goto('https://www.arelplane.com/#arelenglish', {"waitUntil" : "networkidle0", "timeout": 0});
await page.screenshot({path: "test.png"});
await browser.close();
});
and here is the result,

Resources