Skip to content

test: add testing for isVotingWithinLastThreeMonths function #1837

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

Open
wants to merge 6 commits into
base: master
Choose a base branch
from

Conversation

Nandgopal-R
Copy link
Contributor

@Nandgopal-R Nandgopal-R commented Mar 31, 2025

Desciption

  • This PR brings in basic testing for automation and fixes a bug in the vote tracking logic.

Tests Introduced

  • Added Jest-based test cases to improve automation reliability for the isVotingWithinLastThreeMonths.
  • Covered various edge cases, including boundary conditions, invalid inputs, and real-world scenarios.

Fixes

  • Fixed the isVotingWithinLastThreeMonths to correctly handle future dates given in lastVoteDate.

How to test

  • Run npm test to execute all test cases.
  • Verify that all edge cases pass and invalid scenarios are correctly rejected.

This PR is related to issue #1786

Summary by CodeRabbit

  • New Features

    • Introduced a vote tracking workflow for TSC members, including automated parsing of voting results and generation of a markdown voting overview.
    • Added a utility to check if members have participated in votes within the last three months.
  • Documentation

    • Added a "Development" section to the README with instructions for testing and contributing automation scripts.
  • Tests

    • Added comprehensive test coverage for vote tracking edge cases using Jest.
  • Chores

    • Added a package.json to support running tests with Jest.

@Nandgopal-R Nandgopal-R changed the title test: Add testing for isVotingWithinLastThreeMonths function test: add testing for isVotingWithinLastThreeMonths function Mar 31, 2025
Copy link
Member

@derberg derberg left a comment

Choose a reason for hiding this comment

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

  • sorry, please rename testing to test to follow standard naming - I don't know why I suggested testing initially 😄
  • you forgot to add docs (first bullet point in requirements)
  • provide jsdoc for isVotingWithinLastThreeMonths and put there an example of voteInfo argument
  • I think that instead of vote_tracker_utils.js we should rather add there a new folder, as we already have some, like maintainers
    - .github
        - scripts
           - vote_tracker
               - index.js (previously `vote_tracker.js`)
               - utils.js 
    

wdyt?

@Nandgopal-R
Copy link
Contributor Author

I thought of this:

.github  
└── scripts  
    ├── vote_tracker  
    │   ├── index.js  # Main vote tracking logic  
    ├── vote_utils  
    │   ├── utils.js  # Utility functions for vote tracking  

This way, the core logic and utilities are separate. What do you think?

@Nandgopal-R Nandgopal-R requested a review from derberg April 4, 2025 17:33
@derberg
Copy link
Member

derberg commented Apr 7, 2025

but it ain't a big project, so does it make sense to introduce such folder structure? especially that scripts is more thatn vote tracking

@Nandgopal-R
Copy link
Contributor Author

but it ain't a big project, so does it make sense to introduce such folder structure? especially that scripts is more thatn vote tracking

Yeah, fair point. I'll follow the other one and keep it simple. And by the way, I have added the jsdoc and the Development segment to the readme in the previous PR

@derberg
Copy link
Member

derberg commented Apr 14, 2025

ping me whenever ready for another review round

@derberg
Copy link
Member

derberg commented Apr 29, 2025

@Nandgopal-R any news from your side?

Copy link

coderabbitai bot commented Apr 30, 2025

Walkthrough

This update refactors the vote tracking script for TSC member voting on GitHub by moving the main logic from a single file to a new modular structure. The core vote tracking workflow is now in .github/scripts/vote_tracker/index.js, and a new utility function isVotingWithinLastThreeMonths is introduced in .github/scripts/vote_tracker/utils.js. Comprehensive tests for this utility are added in test/vote_tracker.test.js. The update also introduces a package.json for managing dependencies and running tests with Jest, and adds testing instructions to the README.

Changes

File(s) Change Summary
.github/scripts/vote_tracker.js Deleted the original monolithic vote tracking script.
.github/scripts/vote_tracker/index.js Added new modular vote tracking workflow, encapsulating the main logic as an exported async function.
.github/scripts/vote_tracker/utils.js Added utility function isVotingWithinLastThreeMonths with JSDoc and export.
test/vote_tracker.test.js Added Jest test suite covering edge cases for the new utility function.
package.json Added Node.js project metadata, Jest as a dev dependency, and a test script.
README.md Added a "Development" section with instructions for running and writing tests for automation scripts.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GitHub Actions
    participant VoteTracker (index.js)
    participant Utils (utils.js)
    participant Filesystem

    User->>GitHub Actions: Trigger workflow (via comment or bot URL)
    GitHub Actions->>VoteTracker: Invoke exported async function
    VoteTracker->>GitHub Actions: Fetch comment/issue data
    VoteTracker->>Filesystem: Read MAINTAINERS.yaml and voteTrackingFile.json
    VoteTracker->>Utils: Call isVotingWithinLastThreeMonths
    Utils-->>VoteTracker: Return recent voting status
    VoteTracker->>Filesystem: Update voteTrackingFile.json
    VoteTracker->>Filesystem: Write TSC_VOTING_OVERVIEW.md
    VoteTracker-->>GitHub Actions: Finish workflow
Loading

Possibly related issues

  • basic testing for automation #1786: The changes modularize the vote tracking script, extract the utility function, and add comprehensive tests, directly addressing the objectives described in this issue.

Poem

In the warren of code, we’ve tidied the den,
Split scripts into modules, again and again.
With tests now in place, and utils that gleam,
The vote tracker’s workflow is crisp and supreme!
🐇✨
So hop on, dear devs, and give Jest a try—
Our scripts are now tested, as months flutter by!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8875af9 and 8541509.

📒 Files selected for processing (1)
  • test/vote_tracker.test.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/vote_tracker.test.js
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@Nandgopal-R
Copy link
Contributor Author

@derberg I have made the changes

Copy link

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

🧹 Nitpick comments (4)
.github/scripts/vote_tracker/utils.js (1)

45-60: Good implementation with proper edge case handling.

The function correctly:

  • Handles cases where a member has no voting history
  • Rejects future dates as invalid
  • Calculates the difference in days accurately

One minor suggestion would be to extract the "90 days" as a named constant at the top of the file for better maintainability.

+ // Number of days considered as "within 3 months"
+ const DAYS_IN_THREE_MONTHS = 90;

function isVotingWithinLastThreeMonths(voteInfo) {
  // ...existing code...
  
  const diffInDays = (currentDate - lastVoteDate) / (1000 * 60 * 60 * 24);
- return diffInDays <= 90; // 90 days = 3 months
+ return diffInDays <= DAYS_IN_THREE_MONTHS;
}
package.json (1)

1-8: Basic package.json setup for testing.

The package.json file correctly sets up Jest for testing but is missing standard metadata fields. Consider adding name, version, description, and other relevant fields to make the package.json more complete and informative.

{
+ "name": "asyncapi-community",
+ "version": "1.0.0",
+ "description": "AsyncAPI Community repository",
+ "private": true,
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "jest": "^29.0.0"
  }
}
.github/scripts/vote_tracker/index.js (2)

63-72: Avoid double lookup of the same vote row

userVote and userInfo are computed with identical find calls. This duplicates work and complicates reasoning. Re-use the first lookup result:

-const userVote = latestVotes.find(...);
+const userVote = latestVotes.find(
+  (vote) => vote.user.toLowerCase() === voteInfo.name.toLowerCase()
+);

/* …later… */
-const userInfo = latestVotes.find(
-  (vote) => vote.user.toLowerCase() === voteInfo.name.toLowerCase()
-);
-
-const voteChoice = userInfo ? userInfo.vote : "Not participated";
+const voteChoice = userVote ? userVote.vote : "Not participated";

259-261: Prefer Object.hasOwn over hasOwnProperty

Using hasOwnProperty directly on potentially user-supplied objects can be hijacked.
Object.hasOwn() is the modern, prototype-safe alternative.

- return requiredKeys.every((key) => member.hasOwnProperty(key));
+ return requiredKeys.every((key) => Object.hasOwn(member, key));
🧰 Tools
🪛 Biome (1.9.4)

[error] 260-260: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 216148a and 8875af9.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • .github/scripts/vote_tracker.js (0 hunks)
  • .github/scripts/vote_tracker/index.js (1 hunks)
  • .github/scripts/vote_tracker/utils.js (1 hunks)
  • README.md (1 hunks)
  • package.json (1 hunks)
  • test/vote_tracker.test.js (1 hunks)
💤 Files with no reviewable changes (1)
  • .github/scripts/vote_tracker.js
🧰 Additional context used
🪛 Biome (1.9.4)
.github/scripts/vote_tracker/index.js

[error] 74-74: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 260-260: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)

🔇 Additional comments (5)
.github/scripts/vote_tracker/utils.js (1)

1-43: Well-documented function with thorough JSDoc comments!

The JSDoc comments are comprehensive, providing clear descriptions of parameters, return values, and good usage examples. This will help other developers understand how to use this function correctly.

README.md (1)

134-161: Clear development documentation added.

The new Development section provides clear and helpful instructions for running and creating tests. This will help contributors understand how to properly test their changes, which is essential for maintaining code quality.

test/vote_tracker.test.js (1)

3-91: Well-structured tests covering important edge cases.

The test suite is comprehensive and covers several important edge cases:

  • Users who haven't voted recently (>90 days)
  • Users who have never voted
  • Invalid future dates
  • New users who just voted
  • Inactive members

This thorough testing will help ensure the utility function works correctly in all scenarios.

.github/scripts/vote_tracker/index.js (2)

154-158: Property name mismatch breaks column tooltip

The titles map defines hasVotedInLast3Months, but objects use isVotedInLast3Months.
As a result the generated markdown shows the raw key instead of the descriptive tooltip.

- hasVotedInLast3Months: "Flag indicating if TSC member voted in last 3 months …",
+ isVotedInLast3Months: "Flag indicating if TSC member voted in last 3 months …",

Ensure all writes/readers use the same property name (prefer hasVotedInLast3Months for readability, or rename everywhere).
After renaming, remember to adjust tests that may assert on this field.


94-103: ⚠️ Potential issue

isVotingWithinLastThreeMonths is evaluated before the record is populated

lastParticipatedVoteTime is added after isVotingWithinLastThreeMonths(voteInfo) is called, so the utility receives stale/empty data and will always return false.
Populate the field first, then call the helper.

- voteInfo.isVotedInLast3Months = isVotingWithinLastThreeMonths(voteInfo);
- voteInfo.lastParticipatedVoteTime = currentTime;
+voteInfo.lastParticipatedVoteTime = currentTime;
+voteInfo.isVotedInLast3Months = isVotingWithinLastThreeMonths(voteInfo);

Likely an incorrect or invalid review comment.

Comment on lines +74 to +76
if (userVote && userVote.timestamp) {
currentTime = userVote.timestamp.toString().split(" ")[0];
}
Copy link

@coderabbitai coderabbitai bot Apr 30, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Guard against undefined timestamps with optional-chaining

userVote?.timestamp is safer than directly accessing userVote.timestamp, because userVote is undefined when a TSC member did not cast a binding vote.
Without the guard, the script will throw TypeError: Cannot read properties of undefined (reading 'timestamp'), terminating the workflow prematurely.

- if (userVote && userVote.timestamp) {
-   currentTime = userVote.timestamp.toString().split(" ")[0];
- }
+if (userVote?.timestamp) {
+  currentTime = userVote.timestamp.split(" ")[0];
+}
📝 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
if (userVote && userVote.timestamp) {
currentTime = userVote.timestamp.toString().split(" ")[0];
}
if (userVote?.timestamp) {
currentTime = userVote.timestamp.split(" ")[0];
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 74-74: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Copy link
Member

Choose a reason for hiding this comment

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

good suggestion, please apply

Copy link

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Apply the suggested code change
sed -i '/if (userVote && userVote.timestamp) {/,+2c\      if (userVote?.timestamp) {\n        currentTime = userVote.timestamp.split(" ")[0];\n      }' .github/scripts/vote_tracker/index.js

# Verify the change was applied correctly
grep -A 2 "if (userVote?.timestamp)" .github/scripts/vote_tracker/index.js

Length of output: 365


@derberg I've applied the suggested change. The code now uses optional chaining for safer access to the timestamp property and removes the unnecessary .toString() call:

if (userVote?.timestamp) {
  currentTime = userVote.timestamp.split(" ")[0];
}

The change has been committed successfully.


🧬 Code Graph Analysis Results

Relevant snippet from .github/scripts/vote_tracker/index.js (entire file, lines 1-237)

The entire file .github/scripts/vote_tracker/index.js is relevant as it contains the main logic for tracking votes, parsing vote comments, updating vote tracking files, and generating markdown summaries. Key points include:

  • Imports: js-yaml, fs.promises, path, and a utility function isVotingWithinLastThreeMonths.
  • Main exported async function accepting { github, context, botCommentURL }.
  • Logic to extract vote comment details either from a bot comment URL or from the GitHub Actions context.
  • Parsing vote-closed comments to extract voting rows.
  • Reading MAINTAINERS.yaml to get maintainer information.
  • Updating vote tracking file (voteTrackingFile.json) with TSC members and their voting details.
  • Processing votes to update counts for agree, disagree, abstain, and non-participation.
  • Writing updated vote details back to JSON and generating a markdown table (TSC_VOTING_OVERVIEW.md).
  • Helper functions:
    • jsonToMarkdownTable(data): Converts JSON vote data to a markdown table with tooltips and links.
    • parseVoteClosedComment(): Extracts vote rows from the comment message.
    • updateVoteTrackingFile(): Updates the vote tracking file with new TSC members and initializes their vote data.
    • fetchCommentInformation(): Fetches comment and issue details from GitHub API when triggered manually.
  • Extensive error handling and logging throughout.

Possibly relevant snippets from other files

  • .github/workflows/create-event-helpers/calendar/index.js line 135:

    const currentTime = new Date(Date.now()).toISOString();

    This snippet shows a way to get the current ISO timestamp, which is similar to how timestamps are handled in the vote tracker script.

  • .github/scripts/maintainers/gh_calls.js line 116:

    const data = await getCodeownersFile(github, owner, repo.name, core);

    This snippet indicates a call to fetch CODEOWNERS file data, which might relate to maintainer information, but is not directly connected to vote tracking.


No other snippets appear directly relevant to understanding or modifying .github/scripts/vote_tracker/index.js.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@Nandgopal-R
Copy link
Contributor Author

@derberg can you please review this

### Adding New Tests
If you are contributing new automation scripts, ensure they are covered by tests. To add a new test:

1. Create or update the relevant test file in the `testing/` directory.
Copy link
Member

Choose a reason for hiding this comment

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

always remember to update docs 😛

abstainCount: 2,
notParticipatingCount: 0
},
false
Copy link
Member

Choose a reason for hiding this comment

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

this test is giving true instead of expecting false

Copy link
Member

Choose a reason for hiding this comment

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

it;s because you're checking agains the current date, which yeah, now is may, not before april

you need to somehow mock current date and set it as older, before april

Copy link
Member

@derberg derberg left a comment

Choose a reason for hiding this comment

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

few minor comments left, but the overal it is a great quality PR and will help a lot long term

just to clarify, the code in index.js was not changed comparing to the original except for taking one function outside?

@derberg
Copy link
Member

derberg commented May 14, 2025

@Nandgopal-R hey man, did you have a chance to look into my review?

@Nandgopal-R
Copy link
Contributor Author

Yes, I did. I'm almost finished—just tidying up the README, after which I'll commit.

@Nandgopal-R
Copy link
Contributor Author

just to clarify, the code in index.js was not changed comparing to the original except for taking one function outside?

@derberg Yes, that's correct. The only modification to index.js was extracting one function.

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.

3 participants