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

[WIP] 149 fix occupancy tests #179

Closed
wants to merge 4 commits into from

Conversation

lawrence-forooghian
Copy link
Collaborator

@lawrence-forooghian lawrence-forooghian commented Dec 4, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced message handling with improved error reporting and subscription management.
    • Introduced a retry mechanism for message history retrieval in integration tests.
  • Bug Fixes

    • Updated parameter names in message initialization to improve clarity and consistency.
  • Tests

    • Refined test cases to align with updated message property names and improved error handling.
  • Documentation

    • Added comments to clarify changes in integration tests regarding message history and occupancy updates.

Upon our integration tests starting to fail, we noticed that Realtime
seems to have renamed the `latestAction` property to `action`. This
change has not yet been reflected in the spec, but has been in JS [1].

I’ve created an issue to get the spec updated [2] but since this test
failure is stopping us from merging anything else I am going to rename
this property until we get a more definitive answer.

Part of #169.

[1] ably/ably-chat-js#427
[2] ably/specification#254
This is intermittently failing with

> ✘ Test basicIntegrationTest() recorded an issue at IntegrationTests.swift:162:9: Expectation failed: (rxOccupancyEventFromSubscription.presenceMembers → 0) == 1

This is presumably because the arbitrary 2 second wait isn’t enough. So,
instead, wait until the subscription gives us the presence count that
we’re expecting.

Resolves #149.
Noticed that this seemed to be half-done (the comment next to the
`Task.sleep` suggested there was meant to be an occupancy test to follow
the `leave`).
Copy link

coderabbitai bot commented Dec 4, 2024

Walkthrough

The pull request introduces a series of changes primarily focused on renaming the latestAction property to action across various classes and methods related to message handling in the AblyChat example. This change affects the initialization of Message instances, impacting how messages are constructed and processed throughout the mock implementations and the main API. Additionally, enhancements to error handling and message retrieval mechanisms are implemented in the integration tests.

Changes

File Path Change Summary
Example/AblyChatExample/Mocks/Misc.swift Renamed latestAction to action in MockMessagesPaginatedResult class.
Example/AblyChatExample/Mocks/MockClients.swift Renamed latestAction to action in MockMessages class within createSubscription and send methods.
Sources/AblyChat/ChatAPI.swift Updated sendMessage method to use action instead of latestAction and switched to apiVersionV2 for getMessages.
Sources/AblyChat/DefaultMessages.swift Renamed latestAction to action in DefaultMessages class and enhanced error handling in subscribe method.
Sources/AblyChat/Message.swift Renamed latestAction to action in Message struct, including its initializer and CodingKeys.
Tests/AblyChatTests/ChatAPITests.swift Updated tests to reflect the renaming of latestAction to action in sendMessage and getMessages cases.
Tests/AblyChatTests/IntegrationTests.swift Enhanced message history retrieval with a retry mechanism and improved occupancy updates handling.
Tests/AblyChatTests/MessageSubscriptionTests.swift Updated Message instantiation to use action instead of latestAction and added MockPaginatedResult class.
Tests/AblyChatTests/MessageTests.swift Updated multiple instances of Message initialization from latestAction to action.
Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift Renamed key "latestAction" to "action" in mocked responses for ChatAPI.getMessages.

Possibly related PRs

  • [ECO-5001] Some spec alignment #156: The changes in the MockClients.swift file regarding the latestAction to action renaming in the Message initialization are directly related to the changes made in the main PR, which also involves renaming the same property in the MockMessagesPaginatedResult class.

Suggested reviewers

  • umair-ably
  • maratal

Poem

🐰 In the land of code where messages flow,
A little change made the actions glow.
From latestAction to action we cheer,
Simplifying messages, oh so clear!
With tests that now dance, and mocks that play,
Our chat app shines brighter, hip-hip-hooray! 🎉


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

@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 (4)
Tests/AblyChatTests/IntegrationTests.swift (1)

182-184: Correct indentation for better readability

The indentation inside the closure for rxOccupancySubscription.first is misaligned, which affects readability.

Apply this diff to fix the indentation:

 _ = try #require(await rxOccupancySubscription.first { occupancyEvent in
-    occupancyEvent.presenceMembers == 1 // 1 for txClient entering presence
+        occupancyEvent.presenceMembers == 1 // 1 for txClient entering presence
 })
Example/AblyChatExample/Mocks/Misc.swift (1)

Line range hint 13-20: Ensure unique serials for mock messages to avoid duplication

Using Date().timeIntervalSince1970 for the serial property may result in duplicate serials if messages are created quickly. This could cause issues in tests that rely on unique message serials.

Consider using UUID().uuidString to ensure uniqueness:

 Array(repeating: 0, count: numberOfMockMessages).map { _ in
     Message(
-        serial: "\(Date().timeIntervalSince1970)",
+        serial: UUID().uuidString,
         action: .create,
         clientID: self.clientID,
         roomID: self.roomID,
         text: MockStrings.randomPhrase(),
         createdAt: Date(),
         metadata: [:],
         headers: [:]
     )
 }
Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift (1)

Line range hint 73-78: Fix incorrect status code in successSendMessage

The mock response has a status code of 500 which indicates a server error, but the variable name suggests this should represent a successful response.

     static let successSendMessage = MockHTTPPaginatedResponse(
         items: [
             [
                 "serial": "3446456",
                 "createdAt": 1_631_840_000_000,
                 "text": "hello",
             ],
         ],
-        statusCode: 500,
+        statusCode: 200,
         headers: [:]
     )
Sources/AblyChat/DefaultMessages.swift (1)

86-86: LGTM: Property rename with robust error handling

The property rename is consistently applied in the production code. The surrounding error handling for required fields provides good validation before message creation.

Consider adding debug logging for the action value to help with troubleshooting:

+ logger.log(message: "Creating message with action: \(action)", level: .debug)
  let message = Message(
      serial: serial,
      action: action,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5676cac and 80fe95b.

📒 Files selected for processing (10)
  • Example/AblyChatExample/Mocks/Misc.swift (1 hunks)
  • Example/AblyChatExample/Mocks/MockClients.swift (2 hunks)
  • Sources/AblyChat/ChatAPI.swift (1 hunks)
  • Sources/AblyChat/DefaultMessages.swift (1 hunks)
  • Sources/AblyChat/Message.swift (2 hunks)
  • Tests/AblyChatTests/ChatAPITests.swift (3 hunks)
  • Tests/AblyChatTests/IntegrationTests.swift (2 hunks)
  • Tests/AblyChatTests/MessageSubscriptionTests.swift (1 hunks)
  • Tests/AblyChatTests/MessageTests.swift (4 hunks)
  • Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift (2 hunks)
🔇 Additional comments (12)
Tests/AblyChatTests/IntegrationTests.swift (1)

193-196: Verify occupancy updates after presence leave

After calling txRoom.presence.leave(data: nil), ensure that the occupancy count reflects the change. Verifying this confirms that the leave action is properly processed.

You can add an assertion to check the occupancy count:

 // (8) Check that we received an updated presence count on the subscription
 _ = try #require(await rxOccupancySubscription.first { occupancyEvent in
     occupancyEvent.presenceMembers == 0 // 0 for txClient leaving presence
 })
+// Verify occupancy count after leave
+let occupancyAfterLeave = try await rxRoom.occupancy.get()
+#expect(occupancyAfterLeave.presenceMembers == 0)
Sources/AblyChat/Message.swift (1)

12-12: Ensure all references to latestAction are updated to action

The property latestAction has been renamed to action. Please verify that all usages of latestAction in the codebase have been updated to action to prevent any inconsistencies or runtime errors.

Run the following script to find any remaining references to latestAction:

Also applies to: 20-22, 33-33

✅ Verification successful

Property rename from latestAction to action has been properly implemented

The verification shows that there are no remaining references to latestAction in the codebase, and the new action property is correctly used in the Message.swift file for property declaration, initialization, and pattern matching. All references have been successfully updated.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for any occurrences of 'latestAction' in the codebase

rg 'latestAction'

Length of output: 17


Script:

#!/bin/bash
# Let's verify both the old and new property names in Swift files
echo "Searching for 'latestAction' in Swift files:"
rg -t swift 'latestAction'

echo -e "\nSearching for 'action' property in Message.swift:"
rg -t swift 'action' Sources/AblyChat/Message.swift

Length of output: 565

Tests/AblyChatTests/MessageTests.swift (1)

7-7: Updates to action property are consistent

The test cases have been correctly updated to reflect the renaming of latestAction to action, maintaining consistency with the Message struct changes.

Also applies to: 18-18, 29-29, 73-73

Tests/AblyChatTests/MessageSubscriptionTests.swift (1)

29-29: Instantiation of Message updated appropriately

The change from latestAction to action in the Message instantiation aligns with the updated Message struct.

Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift (1)

102-102: LGTM: Property renaming is consistent

The renaming of "latestAction" to "action" in the mock responses aligns with the broader refactoring changes across the codebase.

Also applies to: 112-112

Tests/AblyChatTests/ChatAPITests.swift (1)

44-44: LGTM: Test cases properly updated

The test cases have been correctly updated to use the new action property name while maintaining comprehensive test coverage for both success and error scenarios.

Also applies to: 94-94, 104-104

Sources/AblyChat/ChatAPI.swift (3)

Line range hint 49-56: LGTM: Message initialization updated correctly

The Message initialization has been properly updated to use the new action property name.


Line range hint 1-124: Verify PR title and changes alignment

The PR title mentions fixing occupancy tests, but the changes primarily focus on renaming the action property in message-related code. Consider updating the PR title to better reflect the actual changes, or verify if occupancy test fixes are missing from this PR.

✅ Verification successful

PR title accurately reflects the changes

The PR title mentioning occupancy test fixes is accurate. The diff shows significant changes to occupancy-related tests in IntegrationTests.swift, including:

  • Improved test structure for occupancy verification
  • Added more specific assertions for presence member counts
  • Removed arbitrary sleep delay in favor of proper event verification
  • Enhanced test readability with better variable naming
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for occupancy-related changes
rg -l "occupancy" --type swift

# Check commit messages for context
git log --oneline | grep -i "occupancy"

Length of output: 568


Script:

#!/bin/bash
# Check the diff to see actual changes in occupancy-related files
git diff HEAD~1 -- $(rg -l "occupancy" --type swift)

# Look for test files with occupancy in their name
fd -e swift occupancy

Length of output: 2378


Line range hint 5-6: Address API version transition TODO

There's a TODO comment about removing v1 after full transition to v2. This should be tracked and addressed to avoid maintaining two API versions indefinitely.

Would you like me to create a GitHub issue to track the API version transition task?

Example/AblyChatExample/Mocks/MockClients.swift (2)

107-107: LGTM: Property rename is consistent

The renaming of latestAction to action aligns with the broader refactoring changes across the codebase.


133-133: LGTM: Consistent property rename in message creation

The property rename is consistently applied in the message creation logic of the send method.

Sources/AblyChat/DefaultMessages.swift (1)

Line range hint 1-1: Verify PR scope and title

The PR title mentions fixing occupancy tests, but the changes reviewed are primarily about renaming the latestAction property to action. Consider updating the PR title to better reflect these changes, or verify if there are additional changes related to occupancy tests that should be included.

Comment on lines +139 to +148
let rxMessagesBeforeSubscribing = try await {
while true {
let messages = try await rxMessageSubscription.getPreviousMessages(params: .init())
if !messages.items.isEmpty {
return messages
}
// Wait 1 second before retrying the history fetch
try await Task.sleep(nanoseconds: NSEC_PER_SEC)
}
}()
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent infinite loop by adding a timeout or maximum retries

The while true loop in your retry mechanism could cause the test to hang indefinitely if the condition is never met. To prevent this, consider adding a timeout or a maximum number of retries.

Apply this diff to introduce a maximum retry limit:

 let rxMessagesBeforeSubscribing = try await {
+    let maxRetries = 10
+    var retries = 0
     while true {
         let messages = try await rxMessageSubscription.getPreviousMessages(params: .init())
         if !messages.items.isEmpty {
             return messages
         }
         // Wait 1 second before retrying the history fetch
         try await Task.sleep(nanoseconds: NSEC_PER_SEC)
+        retries += 1
+        if retries >= maxRetries {
+            throw NSError(domain: "IntegrationTests", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to retrieve messages after \(maxRetries) attempts"])
+        }
     }
 }()
📝 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
let rxMessagesBeforeSubscribing = try await {
while true {
let messages = try await rxMessageSubscription.getPreviousMessages(params: .init())
if !messages.items.isEmpty {
return messages
}
// Wait 1 second before retrying the history fetch
try await Task.sleep(nanoseconds: NSEC_PER_SEC)
}
}()
let rxMessagesBeforeSubscribing = try await {
let maxRetries = 10
var retries = 0
while true {
let messages = try await rxMessageSubscription.getPreviousMessages(params: .init())
if !messages.items.isEmpty {
return messages
}
// Wait 1 second before retrying the history fetch
try await Task.sleep(nanoseconds: NSEC_PER_SEC)
retries += 1
if retries >= maxRetries {
throw NSError(domain: "IntegrationTests", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to retrieve messages after \(maxRetries) attempts"])
}
}
}()

@lawrence-forooghian lawrence-forooghian deleted the 149-fix-occupancy-tests branch December 4, 2024 17:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant