Playwright 端對端測試如何以硬碟佇列避免死鎖與記憶體不足
Predicting Injury Counts in Motor Vehicle Collisions
作者為 Playwright 端對端測試設計硬碟佇列,讓資源密集型請求逐一執行,避免多個 worker 同時呼叫伺服器造成死鎖和記憶體不足。作者建立了 @playwright/resource-intensive-queue 套件,並表示這個做法已解決他遇到的死鎖和記憶體不足問題。
What is Playwright?
Playwright is an end to end testing tool. End to end refers to the practice of testing an application frontend and backend. End to end mimics user behavior in an automated fashion. Imagine having a robot in your computer using the app you are working on to find mistakes in the logic of your code, frontend and backend. This is what Playwright does, it’s a fancy robot that allows Engineers to test the changes they are introducing.
Our most frequent tasks as Engineers is to create code and ‘merge’ it into the ‘main code’, the main code are the instructions the end users make the computers read when they use the app. Every time you go on threads.com you are making your computer + 1 or more computers run the ‘main code’. Our jobs as engineers is to write code; new features, bug fixes, code maintenance, etc… and this code we write gets merged into the ‘main code’ which we call ‘develop’, or ‘main’, or more old school ‘master’ — we stopped calling the main code master because of the history of slavery and such, the community has decided that naming the main code master can be considered hate speech.
Anyway, Playwright allows us to test the new code as if it was integrated in the main code so we know for sure the features that are tested by Playwright are compatible with the new code that is being introduced.
Flaky Tests
Usually, the Playwright test suite is divided into numerous amount of small tests; one test is for creating a new post, another test is for creating a new post with an image, another test is for creating a new post with a song, etc… One of the main challenges of end to end testing is that because of the unpredictable nature of computers, sometimes a test will pass and another times it won’t pass.
Flaky tests are very cumbersome and the way we write tests is one of the main ways we can avoid flakiness. However, with Playwright, sometimes it does not matter how well written your tests are, you are likely to face flaky tests due to other reasons as well.
Another reason tests can be flaky is if you have multiple workers executing the test suite at once. Usually to speed up test execution we may decide to increase the amount of workers, however, this means having multiple tests calling your server at the same time. This in turn can overload your test server, create something called deadlocks in the database, create out of memory errors when dealing with big amount of data in the SQL server for example, and even create unpredictable UI jumps due CPU throttling.
Resource Intensive Queue (RIQ)
https://github.com/carlosalmonte04/resource-intensive-queue
To avoid deadlocks and out of memory issues in our servers we can use a hard drive queue. This queue needs to be in the hard drive because each workers in the test environment have their own process, threads and memory space, worker 1 does not share memory space with worker 2, due to this we need a queue that is visible to both, worker 1 and worker 2.
The goal of this queue is to have resource intensive requests be queued, 4 multiple resource intensive requests are triggered, only one of the is executed, the other 3 wait to execute one there is no other resource intensive request being executed.
The code below is a simple example I put together with copilot.
class RIQueue {
constructor() {
this.queue = [];
this.running = false;
}
add(resourceIntensiveApiCall) {
this.queue.push(resourceIntensiveApiCall);
if (!this.running) {
this.process();
}
}
async process() {
this.running = true;
while (this.queue.length > 0) {
const task = this.queue.shift();
// Acquire file lock
while (true) {
try {
await fs.promises.writeFile(
"holder.json",
JSON.stringify({
running: true,
startedAt: new Date().toISOString()
}),
{ flag: "wx" } // fail if file already exists
);
break;
} catch (err) {
// Lock file exists or write failed.
// Keep trying until successful.
await new Promise(resolve => setTimeout(resolve, 100));
}
}
try {
await task();
} finally {
try {
await fs.promises.unlink("holder.json");
} catch (err) {
// Ignore cleanup errors
}
}
}
this.running = false;
}
}
Then, on Playwright you can make use of this queue like this:
await page.route("**/*", async (route) => {
const url = route.request().url();
if (!url.includes("/resource-intensive-api")) {
return route.continue();
}
await riQueue.add(async () => {
console.log("Starting:", url);
const response = await route.fetch();
const body = await response.text();
await route.fulfill({
status: response.status(),
headers: response.headers(),
body,
});
console.log("Finished:", url);
});
});
@carlosalmonte04/resource-intensive-queue
Install:
npm
npm i --save-dev @playwright/resource-intensive-queueu
yarn
yarn add -D @playwright/resource-intensive-queueu
This is a project I have created quickly with the help of Cursor. It exists so that in Playwright you can just use the code above by importing:
`import riQueue from '@playwright/resource-intensive-queue'
It’s important to have the distinction of memory based queue vs hard drive based queue, @playwright/resource-intensive-queue is a hard drive based queue.
Conclusion
This approach seems simple, it may raise concerns about not letting the other workers proceed due to having to wait for the queue to be cleared. However, in practice this has eliminated all deadlocks and out of memory issues I was facing.
Playwright recommended to implement this out of the test runner perimeter. However, I have a significant amount of containers and adding another proxy container in front of multiple services would require more changes. The changes I recommended above effectively remove the need for a proxy. Granted, need to install a new package into your frontend project. However, it is a very simple queue and adding an network traffic controller fixture is a fairly simple ask.
Reference:
https://github.com/carlosalmonte04/playwright-resource-intensive-queue
https://www.theserverside.com/feature/Why-GitHub-renamed-its-master-branch-to-main
來源:DEV Community · dev.to