Showcasing how to do tests for `elm/file` with selenium

Following with that topic:

@Deimos I managed to do it. The solution is a bit hacky, but works, headless or not.

  1. Hack to make selenium tests works in headless selenium driver. · GitHub
    This gist has the code that keeps a reference to the last 20 created input elements.

  2. in selenium, inject that javascript before the form is created:


    with open("./scripts/hack-file-upload.js", "r") as f:
        patch_for_elm_file = f.read()

    driver.execute_script(patch_for_elm_file)
    time.sleep(1) # Not sure this is needed, but is late.

  1. In seleinum, trigger the file dialog of the elm app.

  2. Afterwards call set_file_image_elm_hack

# Awaiter is a custom class, just use regular wait.

def set_file_image_elm_hack(driver: WebDriver, offset: int, path: str):
    id = str(random.randint(111111111, 999999999))
    driver.execute_script("document.addFileInputToDom(arguments[0], arguments[1])", offset, id)

    file_input = WebDriverWait(driver, 30).until(ec.presence_of_element_located((By.XPATH, "//*[@test-id='" + id + "']")))
    file_input.send_keys(path)

    driver.execute_script("document.removeFileInputFromDom(arguments[0])", id)
    if not HEADLESS:
        time.sleep(1)
        subprocess.call(["./scripts/close_file_dialog.sh"])
  1. This bash script closes the file dialog:
#!/usr/bin/env bash

# The window name is not the same in firefox. we should handle that if we need it.
win_name="Open File"

# Find window PID
for pid in $(xdotool search --name "$win_name"); do
  error=$(xdotool windowactivate $pid 2>&1)
  if [[ "$error" == "" ]]; then
    WIN=$pid
    break
  fi
done

if [[ "$WIN" == "" ]]; then
  echo "Failed to find file dialog window."
  exit 1
fi

# Switch to the window
xdotool windowactivate $WIN

# Press "Open" button
xdotool key --window $WIN alt+c

Wow, thanks! I was going to resort to ports and stuff. I’ll definitely have to test your way, thanks!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.