Skip to content

[CUS-12130] updated add-on to store filename/path/extension#381

Open
ManojTestsigma wants to merge 1 commit intodevfrom
CUS-12130
Open

[CUS-12130] updated add-on to store filename/path/extension#381
ManojTestsigma wants to merge 1 commit intodevfrom
CUS-12130

Conversation

@ManojTestsigma
Copy link
Copy Markdown
Contributor

@ManojTestsigma ManojTestsigma commented Apr 17, 2026

please review this addon and publish as PUBLIC

Addon name : get_latest_downloaded_file_path
Addon accont: https://jarvis.testsigma.com/ui/tenants/3072/addons
Jira: https://testsigma.atlassian.net/browse/CUS-12130

fix

added 2 NLP's

  1. to get the actual file name/path/extension
  2. to verify the file content using mime type.

Summary by CodeRabbit

  • New Features

    • Retrieve the most recently downloaded file's full path, filename, or extension directly from the browser to incorporate in your automated tests and workflows.
    • Verify the file type of the most recently downloaded file by validating its MIME type against an expected file type value.
  • Chores

    • Updated version to 1.0.3.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 17, 2026

📝 Walkthrough

Walkthrough

Version 1.0.3 release adds two new web actions for browser-downloaded files: GetLatestDownloadedFileName retrieves the latest downloaded file's path or metadata from Chrome/Edge downloads, and VerifyIfTheLatestFileType validates the downloaded file's MIME type against an expected type.

Changes

Cohort / File(s) Summary
Version Update
get_latest_downloaded_file_path/pom.xml
Maven project version bumped from 1.0.2 to 1.0.3.
Download File Name Action
get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/GetLatestDownloadedFileName.java
New web action that retrieves the most recently downloaded file from browser downloads. Supports multiple output modes: local file path (via file copy), base filename, full filename with extension, or file extension. Handles temporary tab creation for download tracking and ensures cleanup by closing temporary tabs.
Download File Type Validator
get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/VerifyIfTheLatestFileType.java
New web action that validates the MIME type of the latest downloaded file against an expected type. Maps file extensions to MIME types for pdf, png, jpg/jpeg, csv, zip, xlsx, docx, and txt. Probes file MIME type using Files.probeContentType and compares against normalized expected value.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Action
    participant Browser as Browser Downloads
    participant FileOp as File System
    participant Runtime as Runtime Variable
    participant Util as Utilities

    Test->>Browser: Identify latest downloaded file
    alt Return file path
        Test->>Util: Copy file from downloads
        Util->>FileOp: Create local temp copy
        FileOp-->>Test: Local file path
        Test->>Runtime: Store file-path
    else Return file metadata
        Test->>Browser: Open temp blank tab
        Test->>Browser: Wait for download completion
        Browser-->>Test: Download confirmed
        Test->>FileOp: Parse filename from path
        FileOp-->>Test: Extract name/extension
        Test->>Runtime: Store file-name or file-extension
        Test->>Browser: Close temp tab
    end
Loading
sequenceDiagram
    participant Test as Test Action
    participant Browser as Browser Downloads
    participant FileOp as File System
    participant Util as Utilities

    Test->>Test: Normalize expected file type
    Test->>Test: Map extension to MIME type
    Test->>Util: Create utilities instance
    Test->>Util: Copy latest downloaded file
    Util->>FileOp: Write to temp location
    FileOp-->>Test: Temp file created
    Test->>FileOp: Probe file MIME type
    FileOp-->>Test: Detected MIME type
    alt MIME matches expected
        Test-->>Test: Set success message
    else MIME mismatch
        Test-->>Test: Set error message
    end
    Test->>FileOp: Delete temp file
    Test->>Browser: Switch to original window
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested reviewers

  • Ganesh-Testsigma
  • vigneshtestsigma

Poem

🐰 A rabbit hops through downloads so neat,
Fetching files with path and beat!
MIME types checked, filenames found,
Your downloaded files are safe and sound! 🎉

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: two new web actions added to handle filename/path/extension storage and file type verification.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch CUS-12130

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/VerifyIfTheLatestFileType.java (1)

61-63: Ignored File.delete() result and no cleanup on probe failure path.

localFile.delete() return value is ignored — if deletion fails (e.g. file locked), the temp file silently lingers. Also, since copyFileFromDownloads writes a temp file, consider using Files.delete(path) to surface the failure in the log, or register the temp file for deletion on JVM exit (File.deleteOnExit()) as a safety net.

🧹 Suggested tweak
-            String actualFileType;
-            try {
-                actualFileType = Files.probeContentType(localFile.toPath());
-            } finally {
-                localFile.delete();
-            }
+            localFile.deleteOnExit();
+            String actualFileType;
+            try {
+                actualFileType = Files.probeContentType(localFile.toPath());
+            } finally {
+                if (!localFile.delete()) {
+                    logger.info("Could not delete temp file: " + localFile.getAbsolutePath());
+                }
+            }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/VerifyIfTheLatestFileType.java`
around lines 61 - 63, The finally block currently calls localFile.delete() and
ignores the boolean result, so failed deletes silently leave temp files; update
the cleanup in the copyFileFromDownloads flow to attempt a surfaced delete (use
Files.delete(Path) and catch/log IOException) and also register the temp file as
a safety net with localFile.deleteOnExit() when it is created; ensure you
reference and update the cleanup around localFile (and the finally block) to log
failures with processLogger or similar and avoid swallowing the delete result.
get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/GetLatestDownloadedFileName.java (1)

66-78: file-extension returns empty string for dotfiles and extensionless files.

dotIndex > 0 plus the dotIndex + 1 substring can silently return an empty extension (e.g. archive. or .bashrc). That's fine for truly extensionless files, but for trailing-dot names it's also empty. Consider whether callers should instead get a clearer failure (or at least log a warning) when no extension can be derived, so downstream assertions don't pass on an empty value.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/GetLatestDownloadedFileName.java`
around lines 66 - 78, The current logic in GetLatestDownloadedFileName uses
dotIndex > 0 and substring(dotIndex + 1) which returns an empty string for names
like "archive." or dotfiles like ".bashrc"; change the "file-extension" branch
so it only returns an extension when dotIndex > 0 AND dotIndex <
originalFileName.length() - 1, otherwise set storedValue to null (or another
sentinel) and emit a warning/logging message so downstream assertions don't
silently accept an empty extension; update the branch that assigns storedValue
for contentType "file-extension" to use this stricter check (referencing
variables contentType, storedValue, originalFileName, dotIndex) and add a
warning via the existing logger or a new one if none exists.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/GetLatestDownloadedFileName.java`:
- Around line 23-26: Update the stale `@Action` description on the
GetLatestDownloadedFileName class so it enumerates all supported content values:
"file-name", "file-name-with-extension", and "file-extension" in addition to
retrieving the latest downloaded file path; edit the description string in the
`@Action` annotation (the annotation with actionText = "Get latest downloaded
content and store in runtime variable variable-name") to explicitly mention
these supported content values and their meanings so the annotation accurately
reflects current behavior.
- Around line 56-87: The blank tab creation and switch
(JavascriptExecutor.executeScript, driver.getWindowHandles,
driver.switchTo().window) occur before the try/finally that closes the tab, so
if any of those calls throw the temp tab can leak; move the tab-open and switch
logic inside the existing try block (or expand the try to start before
executeScript) in GetLatestDownloadedFileName so that the finally always runs
and always executes driver.close() and
driver.switchTo().window(originalWindowHandle); ensure you still capture
originalWindowHandle before opening the new tab and keep
utilities.isFileDownloaded(), utilities.getDownloadedFileLocalPath(), and the
contentType switch unchanged.

In
`@get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/VerifyIfTheLatestFileType.java`:
- Around line 45-46: The current MIME check in VerifyIfTheLatestFileType (the
switch cases setting expectedMimeType for "xlsx" and "docx") relies on
Files.probeContentType which is platform-dependent and will cause flaky
failures; update the logic to treat expected mime types as a set of allowed
values per extension (e.g., for "xlsx" allow
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet and
application/zip, for "docx" allow
application/vnd.openxmlformats-officedocument.wordprocessingml.document and
application/zip, and for "csv" allow text/csv and text/plain), and change the
validation path in the method that calls Files.probeContentType to: 1) first try
a content-based detector such as Apache Tika (org.apache.tika:tika-core) if
available, 2) if not available or detector returns null/ambiguous, fall back to
matching the file extension against the allowed set, and 3) consider
probeContentType returning null or generic types (like application/zip or
text/plain) as valid when they appear in the allowed set; update the switch that
defines expectedMimeType to produce collections (allowedMimeTypes) and modify
the comparison code to check containment instead of strict equality.

---

Nitpick comments:
In
`@get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/GetLatestDownloadedFileName.java`:
- Around line 66-78: The current logic in GetLatestDownloadedFileName uses
dotIndex > 0 and substring(dotIndex + 1) which returns an empty string for names
like "archive." or dotfiles like ".bashrc"; change the "file-extension" branch
so it only returns an extension when dotIndex > 0 AND dotIndex <
originalFileName.length() - 1, otherwise set storedValue to null (or another
sentinel) and emit a warning/logging message so downstream assertions don't
silently accept an empty extension; update the branch that assigns storedValue
for contentType "file-extension" to use this stricter check (referencing
variables contentType, storedValue, originalFileName, dotIndex) and add a
warning via the existing logger or a new one if none exists.

In
`@get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/VerifyIfTheLatestFileType.java`:
- Around line 61-63: The finally block currently calls localFile.delete() and
ignores the boolean result, so failed deletes silently leave temp files; update
the cleanup in the copyFileFromDownloads flow to attempt a surfaced delete (use
Files.delete(Path) and catch/log IOException) and also register the temp file as
a safety net with localFile.deleteOnExit() when it is created; ensure you
reference and update the cleanup around localFile (and the finally block) to log
failures with processLogger or similar and avoid swallowing the delete result.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5d254082-c9c3-49f3-84b4-578f158df22e

📥 Commits

Reviewing files that changed from the base of the PR and between 54a1d53 and b57a63b.

📒 Files selected for processing (3)
  • get_latest_downloaded_file_path/pom.xml
  • get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/GetLatestDownloadedFileName.java
  • get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/VerifyIfTheLatestFileType.java

Comment on lines +56 to +87
((JavascriptExecutor) driver).executeScript("window.open('about:blank','_blank');");
List<String> tabs = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(tabs.size() - 1));
try {
if (!utilities.isFileDownloaded()) {
throw new RuntimeException("File is still downloading.");
}
String originalPath = utilities.getDownloadedFileLocalPath();
logger.info("Original downloaded file path: " + originalPath);

int lastSep = Math.max(originalPath.lastIndexOf('/'), originalPath.lastIndexOf('\\'));
String originalFileName = lastSep >= 0 ? originalPath.substring(lastSep + 1) : originalPath;
int dotIndex = originalFileName.lastIndexOf('.');

switch (contentType) {
case "file-name":
storedValue = dotIndex > 0 ? originalFileName.substring(0, dotIndex) : originalFileName;
break;
case "file-name-with-extension":
storedValue = originalFileName;
break;
case "file-extension":
storedValue = dotIndex > 0 ? originalFileName.substring(dotIndex + 1) : "";
break;
default:
storedValue = originalFileName;
break;
}
} finally {
driver.close();
driver.switchTo().window(originalWindowHandle);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Possible temporary-tab leak on early failure.

The new blank tab is opened on line 56 and the switch happens on line 58, but the try/finally that restores the original window handle and closes the tab only starts at line 59. If executeScript, getWindowHandles, or switchTo().window(...) throws, the temp tab is left open and the driver may be pointed at it, which cascades into the outer catch where no cleanup runs.

Consider moving the tab creation/switch inside the try block (or wrap the whole else-branch in a try/finally that restores originalWindowHandle and closes any extra tabs).

🛠️ Suggested structure
-                ((JavascriptExecutor) driver).executeScript("window.open('about:blank','_blank');");
-                List<String> tabs = new ArrayList<>(driver.getWindowHandles());
-                driver.switchTo().window(tabs.get(tabs.size() - 1));
-                try {
+                try {
+                    ((JavascriptExecutor) driver).executeScript("window.open('about:blank','_blank');");
+                    List<String> tabs = new ArrayList<>(driver.getWindowHandles());
+                    driver.switchTo().window(tabs.get(tabs.size() - 1));
                     if (!utilities.isFileDownloaded()) {
                         throw new RuntimeException("File is still downloading.");
                     }
                     ...
                 } finally {
-                    driver.close();
-                    driver.switchTo().window(originalWindowHandle);
+                    if (!driver.getWindowHandle().equals(originalWindowHandle)) {
+                        driver.close();
+                    }
+                    driver.switchTo().window(originalWindowHandle);
                 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
((JavascriptExecutor) driver).executeScript("window.open('about:blank','_blank');");
List<String> tabs = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(tabs.size() - 1));
try {
if (!utilities.isFileDownloaded()) {
throw new RuntimeException("File is still downloading.");
}
String originalPath = utilities.getDownloadedFileLocalPath();
logger.info("Original downloaded file path: " + originalPath);
int lastSep = Math.max(originalPath.lastIndexOf('/'), originalPath.lastIndexOf('\\'));
String originalFileName = lastSep >= 0 ? originalPath.substring(lastSep + 1) : originalPath;
int dotIndex = originalFileName.lastIndexOf('.');
switch (contentType) {
case "file-name":
storedValue = dotIndex > 0 ? originalFileName.substring(0, dotIndex) : originalFileName;
break;
case "file-name-with-extension":
storedValue = originalFileName;
break;
case "file-extension":
storedValue = dotIndex > 0 ? originalFileName.substring(dotIndex + 1) : "";
break;
default:
storedValue = originalFileName;
break;
}
} finally {
driver.close();
driver.switchTo().window(originalWindowHandle);
}
try {
((JavascriptExecutor) driver).executeScript("window.open('about:blank','_blank');");
List<String> tabs = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(tabs.size() - 1));
if (!utilities.isFileDownloaded()) {
throw new RuntimeException("File is still downloading.");
}
String originalPath = utilities.getDownloadedFileLocalPath();
logger.info("Original downloaded file path: " + originalPath);
int lastSep = Math.max(originalPath.lastIndexOf('/'), originalPath.lastIndexOf('\\'));
String originalFileName = lastSep >= 0 ? originalPath.substring(lastSep + 1) : originalPath;
int dotIndex = originalFileName.lastIndexOf('.');
switch (contentType) {
case "file-name":
storedValue = dotIndex > 0 ? originalFileName.substring(0, dotIndex) : originalFileName;
break;
case "file-name-with-extension":
storedValue = originalFileName;
break;
case "file-extension":
storedValue = dotIndex > 0 ? originalFileName.substring(dotIndex + 1) : "";
break;
default:
storedValue = originalFileName;
break;
}
} finally {
if (!driver.getWindowHandle().equals(originalWindowHandle)) {
driver.close();
}
driver.switchTo().window(originalWindowHandle);
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@get_latest_downloaded_file_path/src/main/java/com/testsigma/addons/web/GetLatestDownloadedFileName.java`
around lines 56 - 87, The blank tab creation and switch
(JavascriptExecutor.executeScript, driver.getWindowHandles,
driver.switchTo().window) occur before the try/finally that closes the tab, so
if any of those calls throw the temp tab can leak; move the tab-open and switch
logic inside the existing try block (or expand the try to start before
executeScript) in GetLatestDownloadedFileName so that the finally always runs
and always executes driver.close() and
driver.switchTo().window(originalWindowHandle); ensure you still capture
originalWindowHandle before opening the new tab and keep
utilities.isFileDownloaded(), utilities.getDownloadedFileLocalPath(), and the
contentType switch unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants