Skip to content

Update test_waitinglist.py #597

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 2 commits into
base: development
Choose a base branch
from
Open

Conversation

td15
Copy link

@td15 td15 commented Mar 26, 2025

. Added a new class WaitingList that manages a queue of users using a priority queue to ensure FIFO order.

  • Methods: - add_user(user_id): Adds a user to the waiting list with a timestamp. - remove_user(): Removes and returns the next user from the waiting list. - peek_next_user(): Returns the next user without removing them from the list.
  1. Introduced a new test function test_waiting_list() to validate the functionality of the WaitingList class.
    • Tests include adding and removing users, checking the next user, and handling an empty queue case.
    • Validates that users are removed in the correct order based on their addition time.

The new functionality is integrated at the end of the existing test file, ensuring it does not interfere with the existing tests for the WaitingListEntry model.

Summary by Sourcery

Implement a thread-safe WaitingList class with priority queue-based user management for the waiting list functionality

New Features:

  • Introduce a WaitingList class that manages users in a queue with FIFO ordering using a thread-safe priority queue

Tests:

  • Add comprehensive test cases for the WaitingList class, covering user addition, removal, and edge cases like empty queue

. Added a new class `WaitingList` that manages a queue of users using a priority queue to ensure FIFO order.
   - Methods:
     - `add_user(user_id)`: Adds a user to the waiting list with a timestamp.
     - `remove_user()`: Removes and returns the next user from the waiting list.
     - `peek_next_user()`: Returns the next user without removing them from the list.
   
2. Introduced a new test function `test_waiting_list()` to validate the functionality of the `WaitingList` class.
   - Tests include adding and removing users, checking the next user, and handling an empty queue case.
   - Validates that users are removed in the correct order based on their addition time.

The new functionality is integrated at the end of the existing test file, ensuring it does not interfere with the existing tests for the `WaitingListEntry` model.
Copy link
Contributor

sourcery-ai bot commented Mar 26, 2025

Reviewer's Guide by Sourcery

This pull request introduces a WaitingList class that manages a queue of users using a priority queue to ensure FIFO order. It also includes a new test function test_waiting_list() to validate the functionality of the WaitingList class.

No diagrams generated as the changes look simple and do not need a visual representation.

File-Level Changes

Change Details Files
Implements a WaitingList class using a priority queue to manage users in FIFO order.
  • The WaitingList class uses a PriorityQueue to store users.
  • A counter is used to ensure FIFO order in case of same timestamps.
  • A lock is used to ensure thread safety.
  • add_user adds a user to the queue with a timestamp and counter.
  • remove_user removes and returns the next user from the queue.
  • peek_next_user returns the next user without removing them.
src/tests/api/test_waitinglist.py
Adds a test function to validate the WaitingList class.
  • The test_waiting_list function tests adding and removing users.
  • It checks the next user in the queue.
  • It handles the case of an empty queue.
  • It validates that users are removed in the correct order based on their addition time.
src/tests/api/test_waitinglist.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @td15 - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider creating a separate file for the WaitingList class instead of adding it to the test file.
  • Instead of running the test directly at the end of the file, integrate it with the existing test framework.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟡 Testing: 3 issues found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

assert wl.peek_next_user() == "User1", "Test Failed: User1 should be first"
assert wl.remove_user() == "User1", "Test Failed: User1 should be removed first"
assert wl.remove_user() == "User2", "Test Failed: User2 should be removed second"
assert wl.remove_user() == "User3", "Test Failed: User3 should be removed third"
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Consider adding more comprehensive tests for edge cases.

It would be beneficial to include tests for concurrent access to the waiting list to ensure thread safety. For example, simulate multiple users being added and removed from the list concurrently using multiple threads. This would help uncover potential race conditions or deadlocks.

Suggested implementation:

    # Test: Adding and removing users
    wl.add_user("User1")
    wl.add_user("User2")
    wl.add_user("User3")

    assert wl.peek_next_user() == "User1", "Test Failed: User1 should be first"
    assert wl.remove_user() == "User1", "Test Failed: User1 should be removed first"
    assert wl.remove_user() == "User2", "Test Failed: User2 should be removed second"
    # Test: Concurrent access tests for WaitingList
    import threading

    def test_concurrent_access():
        concurrent_wl = WaitingList()
        num_users = 20

        # Function to add a user concurrently
        def add_user(i):
            concurrent_wl.add_user(f"User{i}")

        add_threads = []
        for i in range(num_users):
            t = threading.Thread(target=add_user, args=(i,))
            add_threads.append(t)
            t.start()

        for t in add_threads:
            t.join()

        # Function to remove a user concurrently
        removed_users = []
        def remove_user():
            user = concurrent_wl.remove_user()
            if user is not None:
                removed_users.append(user)

        remove_threads = []
        for _ in range(num_users):
            t = threading.Thread(target=remove_user)
            remove_threads.append(t)
            t.start()

        for t in remove_threads:
            t.join()

        # Verify that all users have been removed in FIFO order
        expected_users = [f"User{i}" for i in range(num_users)]
        assert removed_users == expected_users, "Test Failed: Concurrent removal did not maintain FIFO order"

    test_concurrent_access()

Ensure that your WaitingList.add_user method properly increments the counter and that it uses self.lock to synchronize access when adding or removing users.

Comment on lines +493 to +495
wl.add_user("User1")
wl.add_user("User2")
wl.add_user("User3")
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Use a more robust method for testing FIFO order.

Instead of relying solely on time.sleep(), consider using a monotonic clock like time.monotonic() to generate timestamps. This avoids potential issues with system clock adjustments during testing. Also, consider a test case where you add a large number of users (e.g., 1000) with very small time differences between additions to thoroughly validate the FIFO ordering.

Suggested implementation:

import time
# (Other existing imports)
    # Test: Users waiting for different durations using a large number of users and time.monotonic for precise timestamps
    # Continue the current test by adding a single user
    wl.add_user("UserA")
    assert wl.peek_next_user() == "UserA", "Test Failed: UserA should be next"

    # Now, add 1000 users using monotonic timestamps to simulate very small time differences
    for i in range(1000):
        # Capture monotonic time (if WaitingList internally relies on timestamps, this simulates a small delay)
        current_time = time.monotonic()
        # Add a user; position in queue is determined by the order of addition
        wl.add_user(f"LargeUser{i}")

    # Validate FIFO ordering for the 1000 users
    for i in range(1000):
        expected = f"LargeUser{i}"
        actual = wl.remove_user()
        assert actual == expected, f"Test Failed: Expected {expected} but got {actual}"

Ensure that WaitingList uses the appropriate timestamp source (e.g., time.monotonic()) if it requires precise timing comparisons. This test case assumes that the WaitingList implementation orders users by the time they were added. Adjust the code accordingly if the internal implementation differs.

Comment on lines 516 to 517
# Run tests
test_waiting_list()
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Integrate the test_waiting_list function with the test runner.

Directly calling test_waiting_list() at the end of the file bypasses the test runner. Rename the function to start with test_ (if it isn't already) and let the test runner discover and execute it. This ensures proper test discovery, reporting, and integration with CI/CD pipelines. Remove the direct call to test_waiting_list().

key update points:
Single Test File: Keeping all tests related to the WaitingList class in one file makes it easier to maintain and understand.
Comprehensive Testing: The tests now cover basic functionality, concurrent access, and handling a large number of users, ensuring that the WaitingList class behaves correctly under various conditions.
No Direct Calls: As noted in your original code, there are no direct calls to the test functions. This allows pytest to discover and run the tests automatically.
actual = wl.remove_user()
assert actual == expected, f"Test Failed: Expected {expected} but got {actual}"

# Note: No direct call to test_waiting_list() here; pytest will discover and run the tests.
Copy link
Author

Choose a reason for hiding this comment

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

Next Steps:
Create a Separate File for the WaitingList Class: If you haven't already, create a separate file for the WaitingList class to keep your code organized.
Run Your Tests: Use pytest to run your tests and ensure everything works as expected.
Review and Refactor: After running the tests, review the results and refactor any code as necessary based on the outcomes.

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.

1 participant