Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always Upload Screenshot Artifacts for Nightly Tests #8171

Merged
merged 4 commits into from
Nov 6, 2024

Conversation

hotzenklotz
Copy link
Member

@hotzenklotz hotzenklotz commented Nov 6, 2024

Changes:

  • In order to better debug (failing) nightly screenshots tests, GitHub Actions should always upload screenshot artifacts.
  • Added some improvements to the BrowserStack integration:
    • added the test name to each BrowserStack session so we can more easily identify tests on their website
    • added logging of the BrowserStack session ID to our tests

Steps to test:

  • Run GA worklofw

(Please delete unneeded items, merge only when none are left open)

Summary by CodeRabbit

  • New Features

    • Enhanced BrowserStack integration with the ability to retrieve and log the session ID during tests.
    • Test titles are now assigned to BrowserStack sessions for better tracking.
  • Bug Fixes

    • Ensured that screenshot uploads occur regardless of test success or failure.
  • Documentation

    • Improved console logging for better visibility of the Chrome version and BrowserStack session ID during testing.

@hotzenklotz hotzenklotz self-assigned this Nov 6, 2024
Copy link
Contributor

coderabbitai bot commented Nov 6, 2024

Walkthrough

The changes in this pull request involve updates to two GitHub workflow files and a TypeScript file related to Puppeteer testing. In the workflow files, a conditional statement if: always() was added to the "Upload screenshots as artifact" step, ensuring that screenshots are uploaded regardless of the success or failure of preceding steps. In the TypeScript file, a new function for retrieving the BrowserStack session ID was introduced, and modifications were made to enhance session management and logging during Puppeteer tests.

Changes

File Path Change Summary
.github/workflows/nightly.yml Updated action version to actions/upload-artifact@v4 and added if: always() to "Upload screenshots as artifact" step to ensure execution regardless of previous step outcomes.
.github/workflows/wkorg-nightly.yaml Updated action version to actions/upload-artifact@v4 and added if: always() to "Upload screenshots as artifact" step within nightly-screenshot-tests job to ensure screenshots are uploaded even if tests fail.
frontend/javascripts/test/puppeteer/dataset_rendering_helpers.ts Introduced getBrowserstackSessionId function for retrieving session ID from BrowserStack. Updated setupBeforeEachAndAfterEach to include name in caps and modified browser instance handling. Minor logging enhancements added.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GitHub Actions
    participant Puppeteer
    participant BrowserStack

    User->>GitHub Actions: Trigger nightly workflow
    GitHub Actions->>Puppeteer: Start tests
    alt Tests succeed
        Puppeteer->>GitHub Actions: Upload screenshots
    else Tests fail
        Puppeteer->>GitHub Actions: Upload screenshots
    end
    GitHub Actions->>User: Notify completion
Loading

🐰 "In the workflows, a change so bright,
Screenshots now upload, day or night.
With BrowserStack, we fetch the ID,
Our tests run smoothly, oh yes indeed!
So hop along, let's celebrate,
With joyful bounces, it's truly great!" 🥕


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@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: 1

🧹 Outside diff range and nitpick comments (3)
.github/workflows/nightly.yml (1)

Line range hint 1-62: Consider additional workflow robustness improvements.

While the current changes improve debugging capabilities, here are some suggestions to make the workflow even more robust:

  1. Consider adding error handling for the deployment removal/installation curl commands
  2. The fixed sleep times (180s) could be replaced with active polling or health checks
  3. The screenshot test timeout (3000s) could benefit from being a workflow input parameter

Example improvement for the deployment health check:

      - name: Wait for deployment
        run: |
-         sleep 180
+         max_attempts=30
+         attempt=1
+         while [ $attempt -le $max_attempts ]; do
+           if curl -s -f https://master.webknossos.xyz/health > /dev/null; then
+             echo "Deployment is healthy"
+             exit 0
+           fi
+           echo "Waiting for deployment to be healthy (attempt $attempt/$max_attempts)..."
+           sleep 10
+           attempt=$((attempt + 1))
+         done
+         echo "Deployment health check failed after $max_attempts attempts"
+         exit 1
.github/workflows/wkorg-nightly.yaml (1)

Line range hint 37-41: Consider adding a retention period for artifacts.

Since these are nightly tests generating screenshots regularly, it would be good to manage storage by setting a retention period for the artifacts.

 - name: Upload screenshots as artifact
   uses: actions/upload-artifact@v3
   if: always()
   with:
     name: screenshots
     path: frontend/javascripts/test/screenshots-wkorg
+    retention-days: 14  # Adjust the number based on your debugging needs
frontend/javascripts/test/puppeteer/dataset_rendering_helpers.ts (1)

381-389: Consider improving log readability.

The logging implementation is good, but the format could be more consistent. Consider removing the extra newlines and using a more structured format.

-    console.log(`\nRunning chrome version ${await t.context.browser.version()}\n`);
-    console.log(`\nBrowserStack Session Id ${await getBrowserstackSessionId(browser)}\n`);
+    console.log(`Running Chrome version: ${await t.context.browser.version()}`);
+    console.log(`BrowserStack Session ID: ${await getBrowserstackSessionId(browser)}`);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5988865 and 149b8ba.

📒 Files selected for processing (3)
  • .github/workflows/nightly.yml (1 hunks)
  • .github/workflows/wkorg-nightly.yaml (1 hunks)
  • frontend/javascripts/test/puppeteer/dataset_rendering_helpers.ts (2 hunks)
🔇 Additional comments (4)
.github/workflows/nightly.yml (2)

59-59: LGTM! Good improvement for debugging capabilities.

Adding if: always() ensures that screenshot artifacts are uploaded even when tests fail, which is crucial for debugging failing nightly tests. This change aligns perfectly with the PR objective.


Line range hint 46-57: Verify BrowserStack environment variables usage.

The workflow uses BrowserStack credentials, and the PR objectives mention improvements to BrowserStack integration. Let's verify how these credentials are used in the test code.

✅ Verification successful

Let me check the content of the file that uses BrowserStack to understand how the credentials are utilized.


BrowserStack credentials are properly configured and validated

The credentials are correctly used in the test setup:

  • Environment variables are properly validated through checkBrowserstackCredentials()
  • Credentials are securely passed to BrowserStack's CDP endpoint
  • Variables are used as expected in the BrowserStack capabilities configuration
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how BrowserStack credentials are used in the test code
# Expected: Find usage of BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY in test files

# Search for BrowserStack configuration in test files
echo "Searching for BrowserStack configuration..."
rg -l "BROWSERSTACK" --type ts frontend/javascripts/test/

Length of output: 219


Script:

#!/bin/bash
# Check the content of the file that uses BrowserStack
rg -A 5 -B 5 "BROWSERSTACK" frontend/javascripts/test/puppeteer/dataset_rendering_helpers.ts

Length of output: 964

.github/workflows/wkorg-nightly.yaml (1)

37-37: LGTM! Good improvement for debugging failed tests.

Adding if: always() ensures that screenshot artifacts are uploaded even when tests fail, which is crucial for debugging nightly test failures. This change aligns perfectly with the PR objective.

frontend/javascripts/test/puppeteer/dataset_rendering_helpers.ts (1)

377-381: LGTM: Test name added to BrowserStack session.

The addition of name: t.title to the BrowserStack capabilities will help identify test sessions on the BrowserStack dashboard.

Comment on lines +403 to +412
async function getBrowserstackSessionId(browser: Browser) {
const page = await browser.newPage();
const response = (await page.evaluate(
(_) => {},
`browserstack_executor: ${JSON.stringify({ action: "getSessionDetails" })}`,
)) as unknown as string;

const sessionDetails = await JSON.parse(response);
return sessionDetails.hashed_id;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve robustness of BrowserStack session ID retrieval.

The function has several areas for improvement:

  1. Memory leak: The created page is never closed
  2. Missing error handling for JSON parsing
  3. Unnecessary empty callback in page.evaluate
  4. Type safety could be improved

Consider this improved implementation:

 async function getBrowserstackSessionId(browser: Browser) {
   const page = await browser.newPage();
-  const response = (await page.evaluate(
-    (_) => {},
-    `browserstack_executor: ${JSON.stringify({ action: "getSessionDetails" })}`,
-  )) as unknown as string;
+  try {
+    const response = await page.evaluate(
+      `browserstack_executor: ${JSON.stringify({ action: "getSessionDetails" })}`
+    ) as string;
+    
+    const sessionDetails = JSON.parse(response) as { hashed_id: string };
+    return sessionDetails.hashed_id;
+  } catch (error) {
+    console.error('Failed to retrieve BrowserStack session ID:', error);
+    throw error;
+  } finally {
+    await page.close();
+  }
-  const sessionDetails = await JSON.parse(response);
-  return sessionDetails.hashed_id;
 }
📝 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
async function getBrowserstackSessionId(browser: Browser) {
const page = await browser.newPage();
const response = (await page.evaluate(
(_) => {},
`browserstack_executor: ${JSON.stringify({ action: "getSessionDetails" })}`,
)) as unknown as string;
const sessionDetails = await JSON.parse(response);
return sessionDetails.hashed_id;
}
async function getBrowserstackSessionId(browser: Browser) {
const page = await browser.newPage();
try {
const response = await page.evaluate(
`browserstack_executor: ${JSON.stringify({ action: "getSessionDetails" })}`
) as string;
const sessionDetails = JSON.parse(response) as { hashed_id: string };
return sessionDetails.hashed_id;
} catch (error) {
console.error('Failed to retrieve BrowserStack session ID:', error);
throw error;
} finally {
await page.close();
}
}

@@ -55,7 +55,8 @@ jobs:
BROWSERSTACK_ACCESS_KEY : ${{ secrets.BROWSERSTACK_ACCESS_KEY }}

- name: Upload screenshots as artifact
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
Copy link
Member Author

Choose a reason for hiding this comment

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

Updated to v4 since v3 is EOL at the end of the year.

Screenshot 2024-11-06 at 10 49 58

const page = await browser.newPage();
const response = (await page.evaluate(
(_) => {},
`browserstack_executor: ${JSON.stringify({ action: "getSessionDetails" })}`,
Copy link
Member Author

Choose a reason for hiding this comment

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

@hotzenklotz
Copy link
Member Author

hotzenklotz commented Nov 6, 2024

Seems to work. See this action run which includes BrowserStack Ids and the BrowserStack UI showing names for each invocation: https://github.com/scalableminds/webknossos/actions/runs/11701122812/job/32586545549

Screenshot 2024-11-06 at 11 05 57

Copy link
Member

@daniel-wer daniel-wer left a comment

Choose a reason for hiding this comment

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

LGTM, Thank you for fixing this!

@hotzenklotz hotzenklotz merged commit 8f8a1d2 into master Nov 6, 2024
3 checks passed
@hotzenklotz hotzenklotz deleted the nightly-always branch November 6, 2024 16:08
@coderabbitai coderabbitai bot mentioned this pull request Dec 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants