I write automation tests in Selenium and use python and the chrome browser. I need to write a test that downloads a file (from a link ) and checks that the file has been downloaded. And if possible, the test checks the file type. How can I write this?
I managed to download the file using click(), but I don't know how to check if the file has been downloaded.
You can add download.default_directory
to the ChromeOptions
and instantiate the webdriver.Chrome
with the options object. All the downloads made with this instance will be stored in the download.default_directory
.
To make the test platform-agnostic you can use the tmp_path
fixture provided by pytest
, it will create a temporary directory for the downloaded files. But make sure you specify str(tmp_path)
as the download.default_directory
for the ChromeOptions
.
Consider the following example, you can run it with pytest test_download.py
:
# test_download.py
import os
import time
from dataclasses import dataclass
from pathlib import Path
import pytest
from selenium import webdriver
@dataclass
class Chrome:
driver: webdriver.Chrome
downloads: Path
@pytest.fixture(scope="function")
def chrome(tmp_path):
options = webdriver.ChromeOptions()
options.add_experimental_option(
"prefs",
{
"download.default_directory": str(tmp_path),
},
)
driver = webdriver.Chrome(options=options)
yield Chrome(driver=driver, downloads=tmp_path)
driver.quit()
def test_download_file(chrome: Chrome):
filename = "sample4.csv"
chrome.driver.get(f"https://filesamples.com/samples/document/csv/{filename}")
# Wait for the file to download, adjust if needed
time.sleep(1)
# Check if the file has been downloaded
assert filename in os.listdir(chrome.downloads)