Showing posts with label Playwright File Handling. Show all posts
Showing posts with label Playwright File Handling. Show all posts

File Download in Playwright




In Playwright, file download refers to the process of handling situations where a web application triggers the downloading of files, such as PDFs, CSVs, images, or reports. Normally, when you click a download button or a link that initiates a file download, the browser prompts to save the file. 

In automated testing, Playwright provides a structured way to handle and verify these downloads without manual intervention.

In Playwright Java, downloading a file involves listening for the Download event and then saving the file locally using the download.saveAs() method.


Here’s the theory behind file download in Playwright:


Download Event:

When an action in the browser (like clicking a button or link) triggers a download, Playwright emits a special download event. This allows the test script to detect that a download has started and then capture details about it.

Download Object:

Playwright represents the file download as a Download object. This object contains metadata such as the file’s suggested name, its URL, and a reference to the temporary storage location where the file is initially kept during the download process.

Temporary Storage:

By default, downloaded files are saved to a temporary location. They are not stored permanently until the script explicitly saves them. This ensures tests don’t clutter the file system unless the user specifically chooses to persist the files.

File Path Control:

Playwright allows you to programmatically decide where to save the file. You can move it from the temporary location to a permanent folder on your machine, giving you flexibility in managing test artifacts.

Assertions on Downloads:

Since the Download object provides information like the filename, path, and size, you can add assertions in your tests to confirm that the correct file was downloaded. This helps verify that the application is generating the expected content.


Why Important in Testing:

Handling downloads is critical in end-to-end testing because many applications allow users to export reports, invoices, or other data. Automating this ensures that not only is the UI interaction correct, but also the file itself is generated and downloadable as expected.












How It Works:

  • Trigger the download action on the page (example: clicking a button or link).
  • Wait for the Download event using page.waitForDownload().
  • Save the file locally using the download.saveAs() method.

<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.44.0</version> <!-- or latest -->
</dependency>


Java Code Example to Download File using Playwright


import com.microsoft.playwright.*;

import java.nio.file.Paths;

public class FileDownloadExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
             BrowserContext context = browser.newContext(
	                    new Browser.NewContextOptions().setAcceptDownloads(true)
	                );

            Page page = context.newPage();

            // Navigate to the page that has download link/button
            page.navigate("https://demo.automationtesting.in/FileDownload.html");

            // Click the first download link in the sample Word documents table
            Locator downloadLink = page.locator("a.btn:has-text('Download')");

            // Wait for the download to start and get the Download object
            Download download = page.waitForDownload(() -> {
                downloadLink.click(); // Trigger download
            });

            // Save the downloaded file to local path
            String downloadPath = "samplefile.pdf";
            download.saveAs(Paths.get(downloadPath));

            System.out.println("File downloaded to: " + downloadPath);

            browser.close();
        }
    }
}


Code explanation:

(a) While creating BrowserContext object, we have to do setAcceptDownloads(true)
(b)  Navigate to the page that has download link/button
(c) Click the first download link in the sample Word documents table
(d) Wait for the download to start and get the Download object
(e) Save the downloaded file to local path


Important Points:

  • waitForDownload() ensures Playwright listens for the download triggered by the action inside the callback.

  • You must call download.saveAs(Paths.get(...)) to save the file locally.

  • The file is stored in a temporary directory by default until saved manually.


Suggested Posts:

1. BrowserContext in Playwright
2. File Upload in Playwright
3. Comma Selectors in Playwright
4. Handle Dynamic Webtable in Playwright
5. Page Object Model in Playwright

File Upload in Playwright




In Playwright, file upload refers to the process of automating the action of selecting and submitting files through an HTML file input element (<input type="file">). Normally, in a web application, when a user wants to upload a file, they click the "Choose File" button, and the system’s file picker dialog opens. However, automation tools like Playwright cannot interact with the operating system’s file picker directly because it is outside the browser’s scope.

Instead, Playwright handles file uploads by directly setting the file path(s) to the <input type="file"> element in the DOM. This way, the need to interact with the native dialog is bypassed.

In Playwright Java, uploading a file is done using the setInputFiles() method. This method is used with an <input type="file"> element to simulate file uploads, just like a user would select a file using a file chooser dialog.


Key Points in Theory:

  • File Input Element: The automation must target an element of type file. Uploading only works with this type of input field since browsers restrict file access for security reasons.
  • Bypassing File Picker Dialog: Playwright avoids interacting with the native dialog window. Instead, it programmatically attaches the specified file to the input element.
  • Single or Multiple Files: If the file input supports multiple files (multiple attribute), Playwright can upload more than one file at once.
  • Security Model: Browsers prevent arbitrary file uploads by requiring automation tools to specify exact file paths on the machine. Playwright complies with this security model and only uploads what is explicitly provided.
  • Clearing Files: Just like a user can remove an already chosen file, Playwright can also clear the selected files from the input if needed.
  • Form Submission: After setting the file on the input, the automation can proceed with form submission or trigger any JavaScript events tied to file selection.



Steps to Upload a File in Playwright (Java)

  • Locate the file input element on the page using a suitable locator.
  • Use setInputFiles(Path file) or setInputFiles(FilePayload file) to simulate uploading the file.
  • Optionally, click the submit button if needed.

URL: https://the-internet.herokuapp.com/upload














Example Scenario

Let's assume we have an HTML element like:

<input type="file" id="uploadFile">


Java Code Example

import com.microsoft.playwright.*;
import java.nio.file.Paths;

public class FileUploadExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            Page page = browser.newPage();

            // Go to a page with file upload field
            page.navigate("https://the-internet.herokuapp.com/upload");

            // Locate the input element and upload file
            page.locator("input#file-upload").setInputFiles(Paths.get("example.txt"));

            // Click the Upload button
            page.locator("input#file-submit").click();

            // Optional: verify upload success message
            String uploadedMessage = page.locator("h3").textContent();
            System.out.println("Upload Result: " + uploadedMessage);
        }
    }
}


Explanation of above code:

(a) page.navigate() will navigate to the webpage
(b) locate to the web element and set the input file to be uploaded
(c) Click on the upload button
(d) file become uploaded and print the uploaded message on console









Maven Dependency 

<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.43.0</version> <!-- Use latest version -->
</dependency>