Skip to content

chore: update Postman client example in python folder.#1498

Merged
asyncapi-bot merged 19 commits into
asyncapi:masterfrom
Light13008:update-python-postmanClient-example.js
Apr 17, 2025
Merged

chore: update Postman client example in python folder.#1498
asyncapi-bot merged 19 commits into
asyncapi:masterfrom
Light13008:update-python-postmanClient-example.js

Conversation

@Light13008

@Light13008 Light13008 commented Apr 15, 2025

Copy link
Copy Markdown
Contributor

Description
-Only updated for python.
-client-postman and client-hoppscotch were added with respective README.md and 'example.py'
-To work on echo we first need to adapt to the new file structure.
Fixes #1373

Related issue(s)

Fixes #1373 for Python files

Summary by CodeRabbit

  • Documentation

    • Updated the Python WebSocket client template README with revised instructions for testing an alternative client.
    • Corrected import paths and clarified usage examples in the Python example script.
  • Tests

    • Improved test isolation for Python WebSocket client generation by separating output directories per client type and standardizing output filenames.
  • Style

    • Minor formatting adjustment in a JavaScript test file (removal of trailing newline).

@changeset-bot

changeset-bot Bot commented Apr 15, 2025

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 47ad74b

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Apr 15, 2025

Copy link
Copy Markdown

Walkthrough

This pull request modifies the Python WebSocket client template and its associated test and documentation files. The test suite is updated to generate and store outputs for both the Postman and Hoppscotch client types in separate directories, using consistent filenames. The README instructions are revised to reflect the new import paths and usage for the Postman client. The example Python script is updated to use the new import path and to explicitly invoke the main function. Additionally, a minor formatting change is made in a JavaScript integration test file.

Changes

File(s) Change Summary
packages/templates/clients/websocket/python/test/integration.test.js Refactored to generate and test Postman and Hoppscotch client outputs in separate directories with unified filenames.
packages/templates/clients/websocket/python/README.md Updated usage instructions to reflect new import path and client instantiation for Postman client.
packages/templates/clients/websocket/python/example.py Changed import path for Postman client and added explicit call to main().
packages/templates/clients/websocket/javascript/test/integration.test.js Removed trailing newline at end of file.

Sequence Diagram(s)

sequenceDiagram
    participant TestRunner
    participant Generator
    participant FileSystem

    TestRunner->>Generator: Generate Postman client (writes to /client_postman)
    Generator->>FileSystem: Write client.py, requirements.txt to /client_postman
    TestRunner->>Generator: Generate Hoppscotch client (writes to /client_hoppscotch)
    Generator->>FileSystem: Write client.py, requirements.txt to /client_hoppscotch
    TestRunner->>FileSystem: Read generated files for both clients
    TestRunner->>TestRunner: Compare outputs to snapshots
Loading

Assessment against linked issues

Objective Addressed Explanation
Generate both postman-echo and hoppscotch-echo outputs in separate folders in snapshot tests (#1373)
Update snapshot tests to check for README.md for both asyncapi documents (#1373) No evidence of README.md generation or snapshot checks for README.md in the test changes.

Possibly related PRs

Suggested labels

ready-to-merge

Suggested reviewers

  • derberg
  • Florence-Njeri
  • magicmatatjahu
  • jonaslagoni

Poem

In the warren where code bunnies hop,
We split our tests—no need to stop!
Clients Postman and Hoppscotch, side by side,
In folders neat, their outputs reside.
With imports fixed and main called true,
This rabbit’s work is nearly through!
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

🪧 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 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.

@Light13008 Light13008 changed the title Update python postman client example.js chore: update Postman client example in python folder. Apr 15, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 (5)
packages/templates/clients/websocket/javascript/README.md (1)

9-9: Fix grammar and punctuation in the documentation.

The instruction line has several minor grammar and punctuation issues that should be fixed for better readability.

- > By default this is testing against Postman echo service. You can modify `packages/templates/clients/websocket/javascript/example.js` and change first line to `const WSClient = require('./test/temp/snapshotTestResult/postman-client/client-postman.js');` again. You will see example still works but now it is using a different API. This is possible since both AsyncAPI documents define the same name of operation for sending messages: `sendEchoMessage` so each client generated has the same API.
+ > By default, this is testing against Postman echo service. You can modify `packages/templates/clients/websocket/javascript/example.js` and change the first line to `const WSClient = require('./test/temp/snapshotTestResult/postman-client/client-postman.js');` again. You will see the example still works but now it is using a different API. This is possible since both AsyncAPI documents define the same name of operation for sending messages: `sendEchoMessage`, so each client generated has the same API.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~9-~9: Did you mean: “By default,”?
Context: ...rated by the test: node example.js > By default this is testing against Postman echo se...

(BY_DEFAULT_COMMA)


[uncategorized] ~9-~9: You might be missing the article “the” here.
Context: ...ocket/javascript/example.jsand change first line toconst WSClient = require('./te...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)


[uncategorized] ~9-~9: Possible missing article found.
Context: ...ient-postman.js');` again. You will see example still works but now it is using a diffe...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~9-~9: Use a comma before ‘but’ if it connects two independent clauses (unless they are closely connected and short).
Context: ... again. You will see example still works but now it is using a different API. This i...

(COMMA_COMPOUND_SENTENCE)

packages/templates/clients/websocket/javascript/example.js (1)

10-10: Trailing whitespace detected.

There is a trailing whitespace at the end of line 10 that should be removed.

-} 
+}
packages/templates/clients/websocket/python/README.md (1)

11-11: Fix grammar issues and a typo in the documentation.

There are several grammar issues and a typo ("agains" instead of "against") in this instruction line.

- > By default this is testing against Postman echo service. You can modify `packages/templates/clients/websocket/python/example.py` and change first line to `from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient` and line 16 `client = PostmanEchoWebSocketClient()` and run `python example.py` again. You will see example still works but agains different API. This is possible as both AsyncAPI documents have the same name of operation for sending messages: `sendEchoMessage` so each client generated has the same API.
+ > By default, this is testing against Postman echo service. You can modify `packages/templates/clients/websocket/python/example.py` and change the first line to `from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient` and line 16 to `client = PostmanEchoWebSocketClient()` and run `python example.py` again. You will see the example still works but against a different API. This is possible as both AsyncAPI documents have the same name of operation for sending messages: `sendEchoMessage`, so each client generated has the same API.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~11-~11: Did you mean: “By default,”?
Context: ...ted by the test: python example.py > By default this is testing against Postman echo se...

(BY_DEFAULT_COMMA)


[uncategorized] ~11-~11: You might be missing the article “the” here.
Context: ...python example.py again. You will see example still works but agains different API. T...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

packages/templates/clients/websocket/javascript/test/integration.test.js (2)

22-22: Clean up unnecessary whitespace

There's an empty line at line 32 that could be removed for consistency.

    await generator.generateFromFile(asyncapi_v3_path_postman);

-    
    const client = await readFile(path.join(testResultPathPostman, testOutputFile), 'utf8');

Also applies to: 32-33


57-57: Clean up unnecessary whitespace

There's an empty line at line 66 that could be removed for consistency.

    await generator.generateFromFile(asyncapi_v3_path_hoppscotch);

-    
    const clientOutputFile = path.join(testResultPathClient, defaultOutputFile);

Also applies to: 66-67

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d7a73c5 and eaf4537.

📒 Files selected for processing (7)
  • apps/generator/lib/generator.js (1 hunks)
  • packages/templates/clients/websocket/javascript/README.md (1 hunks)
  • packages/templates/clients/websocket/javascript/example.js (2 hunks)
  • packages/templates/clients/websocket/javascript/test/integration.test.js (6 hunks)
  • packages/templates/clients/websocket/python/README.md (1 hunks)
  • packages/templates/clients/websocket/python/test/example.py (3 hunks)
  • packages/templates/clients/websocket/python/test/integration.test.js (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/templates/clients/websocket/python/test/integration.test.js (1)
packages/templates/clients/websocket/javascript/test/integration.test.js (6)
  • testResultPathPostman (11-11)
  • path (5-5)
  • testResultPath (10-10)
  • testResultPathHoppscotch (12-12)
  • template (14-14)
  • Generator (7-7)
🪛 LanguageTool
packages/templates/clients/websocket/javascript/README.md

[uncategorized] ~9-~9: Did you mean: “By default,”?
Context: ...rated by the test: node example.js > By default this is testing against Postman echo se...

(BY_DEFAULT_COMMA)


[uncategorized] ~9-~9: You might be missing the article “the” here.
Context: ...ocket/javascript/example.jsand change first line toconst WSClient = require('./te...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)


[uncategorized] ~9-~9: Possible missing article found.
Context: ...ient-postman.js');` again. You will see example still works but now it is using a diffe...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~9-~9: Use a comma before ‘but’ if it connects two independent clauses (unless they are closely connected and short).
Context: ... again. You will see example still works but now it is using a different API. This i...

(COMMA_COMPOUND_SENTENCE)

packages/templates/clients/websocket/python/README.md

[uncategorized] ~11-~11: Did you mean: “By default,”?
Context: ...ted by the test: python example.py > By default this is testing against Postman echo se...

(BY_DEFAULT_COMMA)


[uncategorized] ~11-~11: You might be missing the article “the” here.
Context: ...python example.py again. You will see example still works but agains different API. T...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

🪛 Ruff (0.8.2)
packages/templates/clients/websocket/python/test/example.py

1-1: temp.snapshotTestResult.client_postman.client.PostmanEchoWebSocketClientClient imported but unused

Remove unused import: temp.snapshotTestResult.client_postman.client.PostmanEchoWebSocketClientClient

(F401)


16-16: Undefined name PostmanEchoWebSocketClient

(F821)

🔇 Additional comments (9)
apps/generator/lib/generator.js (1)

12-13: Good defensive programming approach.

The change adds a safeguard against requireg.resolve('npm') potentially returning undefined or null, which prevents runtime errors that would occur when calling .replace() on an undefined value.

packages/templates/clients/websocket/javascript/example.js (1)

1-1: Path update to align with new directory structure.

The import path for the WSClient module has been updated to reflect the new directory structure where client outputs are isolated by client type, improving organization.

packages/templates/clients/websocket/javascript/test/integration.test.js (3)

11-13: LGTM - Directory structure reorganization

Good job separating the test output directories by client type. This organization makes the test outputs clearer and prevents potential file conflicts.


40-40: LGTM - Updated generator path for Hoppscotch

The generator now correctly writes to the dedicated Hoppscotch directory.

Also applies to: 50-50


77-77: LGTM - Consistent test setup

The error test correctly uses the same directory structure as the success tests.

packages/templates/clients/websocket/python/test/example.py (1)

35-36: LGTM - Added proper Python entry point guard

Adding the if __name__ == "__main__": guard is a good Python practice that prevents the code from running when imported as a module.

packages/templates/clients/websocket/python/test/integration.test.js (3)

11-12: LGTM - Separate output directories for different clients

Good job separating the test output directories by client type. Note that the directory naming convention differs slightly from the JavaScript template (client_postman vs postman-client), but it's consistent within this Python template.


19-21: LGTM - Consistent file naming and path updates

Good standardization of output file names and correct path updates for reading the generated files. This makes the test more maintainable.

Also applies to: 32-33


40-42: LGTM - Parallel implementation for Hoppscotch client

The implementation for the Hoppscotch client mirrors the Postman client approach, which ensures consistency across different client types.

Also applies to: 53-54

6. Start example script that uses a client library generated by the test: `python example.py`

> By default this is testing against Postman echo service. You can modify `packages/templates/clients/websocket/python/example.py` and change first line to `from temp.snapshotTestResult.client_hoppscotch import HoppscotchEchoWebSocketClient` and line 16 `client = HoppscotchEchoWebSocketClient()` and run `python example.py` again. You will see example still works but agains different API. This is possible as both AsyncAPI documents have the same name of operation for sending messages: `sendEchoMessage` so each client generated has the same API. No newline at end of file
> By default this is testing against Postman echo service. You can modify `packages/templates/clients/websocket/python/example.py` and change first line to `from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient` and line 16 `client = PostmanEchoWebSocketClient()` and run `python example.py` again. You will see example still works but agains different API. This is possible as both AsyncAPI documents have the same name of operation for sending messages: `sendEchoMessage` so each client generated has the same API. No newline at end of file

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

Fix inconsistent class name in import statement.

There's an inconsistency in the class name - PostmanEchoWebSocketClientClient in the import statement, but PostmanEchoWebSocketClient when instantiating. The import statement appears to have an extra "Client" at the end.

- from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient
+ from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClient
📝 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
> By default this is testing against Postman echo service. You can modify `packages/templates/clients/websocket/python/example.py` and change first line to `from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient` and line 16 `client = PostmanEchoWebSocketClient()` and run `python example.py` again. You will see example still works but agains different API. This is possible as both AsyncAPI documents have the same name of operation for sending messages: `sendEchoMessage` so each client generated has the same API.
> By default this is testing against Postman echo service. You can modify `packages/templates/clients/websocket/python/example.py` and change first line to `from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClient` and line 16 `client = PostmanEchoWebSocketClient()` and run `python example.py` again. You will see example still works but agans different API. This is possible as both AsyncAPI documents have the same name of operation for sending messages: `sendEchoMessage` so each client generated has the same API.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~11-~11: Did you mean: “By default,”?
Context: ...ted by the test: python example.py > By default this is testing against Postman echo se...

(BY_DEFAULT_COMMA)


[uncategorized] ~11-~11: You might be missing the article “the” here.
Context: ...python example.py again. You will see example still works but agains different API. T...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

@@ -1,4 +1,4 @@
from temp.snapshotTestResult.client_postman import PostmanEchoWebSocketClientClient
from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient

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

Fix import/instantiation mismatch

There's a mismatch between the imported class and the instantiated class. The import statement imports PostmanEchoWebSocketClientClient but the code tries to instantiate PostmanEchoWebSocketClient.

-from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient
+from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClient

def custom_message_handler(message):
    print(f"\033[94mCustom processing of received message\033[0m: {message}")

def custom_error_handler(error):
    print(f"Custom error handling: {error}")

def outgoing_message_processor(message):
    # Modify message before sending (e.g., add a timestamp)
    print(f"\033[92mCustom processing of outgoing message\033[0m: {message}")
    return {"Processed outgoing message": message, "timestamp": "2025-03-13T12:00:00Z"}

def main():
    client = PostmanEchoWebSocketClient()

Also applies to: 16-16

🧰 Tools
🪛 Ruff (0.8.2)

1-1: temp.snapshotTestResult.client_postman.client.PostmanEchoWebSocketClientClient imported but unused

Remove unused import: temp.snapshotTestResult.client_postman.client.PostmanEchoWebSocketClientClient

(F401)

@derberg derberg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

seems like some duplication of work from another PR

Comment thread apps/generator/lib/generator.js Outdated
const Config = require('@npmcli/config');
const requireg = require('requireg');
const npmPath = requireg.resolve('npm').replace('index.js','');
const npmResolvedPath = requireg.resolve('npm') || '';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

not related to the task, please revert

@Light13008
Light13008 force-pushed the update-python-postmanClient-example.js branch 2 times, most recently from de7fd63 to b2b8515 Compare April 15, 2025 18:29

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
packages/templates/clients/websocket/python/example.py (3)

1-1: Import path seems specific to test environment

The import path temp.snapshotTestResult.client_postman.client appears to be specific to a testing context, which might be confusing for developers trying to use this example in their actual projects. Consider providing a comment explaining this is a demo path or showing the expected production import path.

-from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient
+# Note: In your actual project, the import path will depend on your project structure
+# This path is specific to the generator test environment
+from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient

11-13: Use dynamic timestamp instead of hardcoded value

The outgoing message processor uses a hardcoded timestamp ("2025-03-13T12:00:00Z") which doesn't demonstrate real-world usage where you'd typically want the current time.

 def outgoing_message_processor(message):
     # Modify message before sending (e.g., add a timestamp)
     print(f"\033[92mCustom processing of outgoing message\033[0m: {message}")
-    return {"Processed outgoing message": message, "timestamp": "2025-03-13T12:00:00Z"}
+    from datetime import datetime
+    current_time = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
+    return {"Processed outgoing message": message, "timestamp": current_time}

4-34: Add more explanatory comments

The example would benefit from more detailed comments explaining the purpose and expected behavior of each section, especially for developers new to WebSocket clients.

Consider adding more descriptive comments that explain:

  1. The purpose of each handler function
  2. What to expect in the console output
  3. The flow of the WebSocket connection process
  4. The expected server responses

For example:

 def custom_message_handler(message):
+    # This handler is called whenever a message is received from the server
+    # The blue color helps distinguish incoming messages in the console
     print(f"\033[94mCustom processing of received message\033[0m: {message}")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b5ce6a and 1fe3441.

📒 Files selected for processing (1)
  • packages/templates/clients/websocket/python/example.py (1 hunks)
🔇 Additional comments (1)
packages/templates/clients/websocket/python/example.py (1)

1-37: LGTM overall with suggestions for improvement

The example effectively demonstrates the basic usage of the WebSocket client with custom handlers. The code structure is clear and includes the essential components: connection establishment, message sending, and handler registration. With the suggested improvements for error handling, dynamic timestamps, and better documentation, this will be an excellent reference for users.

Comment on lines +15 to +33
def main():
client = PostmanEchoWebSocketClientClient()
client.register_message_handler(custom_message_handler)
client.register_error_handler(custom_error_handler)
client.register_outgoing_processor(outgoing_message_processor)

client.connect()

# Give some time for the connection to establish
time.sleep(2)

# Send multiple messages to test stream handling
for i in range(5):
message = f'Hello, Echo Yo! {i}'
client.send_message(message)
time.sleep(2) # Wait for a response

# Keep program alive for a while to allow message processing
time.sleep(10)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add proper connection error handling and cleanup

The example lacks error handling for connection issues and doesn't demonstrate how to properly close the WebSocket connection, which is important for resource management in real applications.

 def main():
     client = PostmanEchoWebSocketClientClient()
     client.register_message_handler(custom_message_handler)
     client.register_error_handler(custom_error_handler)
     client.register_outgoing_processor(outgoing_message_processor)
 
-    client.connect()
-    
-    # Give some time for the connection to establish
-    time.sleep(2)
+    try:
+        # Connect to the WebSocket server
+        client.connect()
+        
+        # Give some time for the connection to establish
+        time.sleep(2)
 
-    # Send multiple messages to test stream handling
-    for i in range(5):
-        message = f'Hello, Echo Yo! {i}'
-        client.send_message(message)
-        time.sleep(2)  # Wait for a response
+        # Send multiple messages to test stream handling
+        for i in range(5):
+            message = f'Hello, Echo Yo! {i}'
+            client.send_message(message)
+            time.sleep(2)  # Wait for a response
 
-    # Keep program alive for a while to allow message processing
-    time.sleep(10)
+        # Keep program alive for a while to allow message processing
+        time.sleep(10)
+    except Exception as e:
+        print(f"Error occurred: {e}")
+    finally:
+        # Always close the connection when done
+        print("Closing connection...")
+        client.disconnect()  # Assuming the client has a disconnect method
📝 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
def main():
client = PostmanEchoWebSocketClientClient()
client.register_message_handler(custom_message_handler)
client.register_error_handler(custom_error_handler)
client.register_outgoing_processor(outgoing_message_processor)
client.connect()
# Give some time for the connection to establish
time.sleep(2)
# Send multiple messages to test stream handling
for i in range(5):
message = f'Hello, Echo Yo! {i}'
client.send_message(message)
time.sleep(2) # Wait for a response
# Keep program alive for a while to allow message processing
time.sleep(10)
def main():
client = PostmanEchoWebSocketClientClient()
client.register_message_handler(custom_message_handler)
client.register_error_handler(custom_error_handler)
client.register_outgoing_processor(outgoing_message_processor)
try:
# Connect to the WebSocket server
client.connect()
# Give some time for the connection to establish
time.sleep(2)
# Send multiple messages to test stream handling
for i in range(5):
message = f'Hello, Echo Yo! {i}'
client.send_message(message)
time.sleep(2) # Wait for a response
# Keep program alive for a while to allow message processing
time.sleep(10)
except Exception as e:
print(f"Error occurred: {e}")
finally:
# Always close the connection when done
print("Closing connection...")
client.disconnect() # Assuming the client has a disconnect method

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
packages/templates/clients/websocket/python/README.md (1)

10-10: ⚠️ Potential issue

Fix inconsistent class name in import and instantiation.

There's an inconsistency in the class name: the import statement uses PostmanEchoWebSocketClientClient, but the instantiation should match this name. The correct class name is likely PostmanEchoWebSocketClient. Please update both the import and instantiation to use the same, correct class name.

- from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient
+ from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClient
...
- client = PostmanEchoWebSocketClientClient()
+ client = PostmanEchoWebSocketClient()
🧰 Tools
🪛 LanguageTool

[uncategorized] ~10-~10: Did you mean: “By default,”?
Context: ...ted by the test: python example.py > By default this is testing against Postman echo se...

(BY_DEFAULT_COMMA)


[uncategorized] ~10-~10: You might be missing the article “the” here.
Context: ...python example.py again. You will see example still works but agains different API. T...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

🧹 Nitpick comments (1)
packages/templates/clients/websocket/python/README.md (1)

10-10: Correct grammar and typos for clarity.

  • Add a comma after "By default".
  • Change "agains" to "against".
  • Consider adding "the" before "example" for clarity.
- > By default this is testing against Postman echo service. You can modify `packages/templates/clients/websocket/python/example.py` and change first line to `from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient` and line 16 `client = PostmanEchoWebSocketClientClient()` and run `python example.py` again. You will see example still works but agains different API. This is possible as both AsyncAPI documents have the same name of operation for sending messages: `sendEchoMessage` so each client generated has the same API.
+ > By default, this is testing against the Postman echo service. You can modify `packages/templates/clients/websocket/python/example.py` and change the first line to `from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClient` and line 16 to `client = PostmanEchoWebSocketClient()`, then run `python example.py` again. You will see the example still works but against a different API. This is possible as both AsyncAPI documents have the same name of operation for sending messages: `sendEchoMessage`, so each client generated has the same API.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~10-~10: Did you mean: “By default,”?
Context: ...ted by the test: python example.py > By default this is testing against Postman echo se...

(BY_DEFAULT_COMMA)


[uncategorized] ~10-~10: You might be missing the article “the” here.
Context: ...python example.py again. You will see example still works but agains different API. T...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1fe3441 and a201e30.

📒 Files selected for processing (2)
  • packages/templates/clients/websocket/python/README.md (1 hunks)
  • packages/templates/clients/websocket/python/example.py (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/templates/clients/websocket/python/example.py
🧰 Additional context used
🪛 LanguageTool
packages/templates/clients/websocket/python/README.md

[uncategorized] ~10-~10: Did you mean: “By default,”?
Context: ...ted by the test: python example.py > By default this is testing against Postman echo se...

(BY_DEFAULT_COMMA)


[uncategorized] ~10-~10: You might be missing the article “the” here.
Context: ...python example.py again. You will see example still works but agains different API. T...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

derberg
derberg previously approved these changes Apr 16, 2025
@derberg

derberg commented Apr 16, 2025

Copy link
Copy Markdown
Member

there are some old snapshot tests, run locally npm run test:update to get the refresh of snapshot tests, and push changes to PR

@Light13008

Light13008 commented Apr 16, 2025

Copy link
Copy Markdown
Contributor Author

there are some old snapshot tests, run locally npm run test:update to get the refresh of snapshot tests, and push changes to PR

hey Lukas,
i tried working on this issue,
but like i said previously, My test were failing due to .resolve issue for which i had to make a change in generator.js.
i had discussed it here #1476 (comment)
Im adding some screenshots of my terminal here.
image

and after making those changes in generator.js the tests were running, here is the screenshot after updating generator.js file.
image

Any suggestions ???

I just listed my observation, for this PR i will not add generator.js file. I just documented this issue for you. as it was failing multiple times and i was Continuously pushing that file after running test in almost all my prs.

@Light13008
Light13008 force-pushed the update-python-postmanClient-example.js branch from eb28241 to 4bc549c Compare April 16, 2025 18:57
@sonarqubecloud

Copy link
Copy Markdown

@Light13008
Light13008 requested a review from derberg April 16, 2025 19:01

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/templates/clients/websocket/python/README.md (2)

8-10: Refine grammar and clarity for preparatory steps.

These lines are missing articles and can be made more consistent and readable. For example:

- 4. Go to test folder with `cd test`
+ 4. Go to the test folder with `cd test`

- 5. Install dependencies of the generated client: `pip install -r temp/snapshotTestResult/requirements.txt`
+ 5. Install the dependencies of the generated client: `pip install -r temp/snapshotTestResult/requirements.txt`

- 6. Start example script that uses a client library generated by the test: `python example.py`
+ 6. Start the example script that uses the generated client library: `python example.py`
🧰 Tools
🪛 LanguageTool

[uncategorized] ~8-~8: You might be missing the article “the” here.
Context: ...d run test with npm run test 4. Go to test folder with cd test 5. Install depend...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)


[uncategorized] ~10-~10: You might be missing the article “an” here.
Context: ...otTestResult/requirements.txt` 6. Start example script that uses a client library gener...

(AI_EN_LECTOR_MISSING_DETERMINER_AN)


12-12: Correct typo and improve readability of default testing note.

Line 12 has several minor issues: missing comma after “By default”, missing article “the”, and a typo in “agains”. Suggested diff:

- > By default this is testing against Postman echo service. You can modify `packages/templates/clients/websocket/python/example.py` and change first line to `from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient` and line 16 `client = PostmanEchoWebSocketClientClient()` and run `python example.py` again. You will see example still works but agains different API. This is possible as both AsyncAPI documents have the same name of operation for sending messages: `sendEchoMessage` so each client generated has the same API.
+ > By default, this is testing against the Postman echo service. You can modify `packages/templates/clients/websocket/python/example.py`:
+ > - Change the import on the first line to:
+ >   `from temp.snapshotTestResult.client_postman.client import PostmanEchoWebSocketClientClient`
+ > - Update line 16 to:
+ >   `client = PostmanEchoWebSocketClientClient()`
+ > - Run `python example.py` again. You will see the example still works but against a different API. This is possible because both AsyncAPI documents use the same operation name (`sendEchoMessage`), so each generated client has an identical interface.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~12-~12: Did you mean: “By default,”?
Context: ...ted by the test: python example.py > By default this is testing against Postman echo se...

(BY_DEFAULT_COMMA)


[uncategorized] ~12-~12: You might be missing the article “the” here.
Context: ...python example.py again. You will see example still works but agains different API. T...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a201e30 and 47ad74b.

⛔ Files ignored due to path filters (1)
  • packages/templates/clients/websocket/python/test/__snapshots__/integration.test.js.snap is excluded by !**/*.snap
📒 Files selected for processing (4)
  • packages/templates/clients/websocket/javascript/test/integration.test.js (1 hunks)
  • packages/templates/clients/websocket/python/README.md (1 hunks)
  • packages/templates/clients/websocket/python/example.py (2 hunks)
  • packages/templates/clients/websocket/python/test/integration.test.js (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/templates/clients/websocket/python/example.py
  • packages/templates/clients/websocket/python/test/integration.test.js
  • packages/templates/clients/websocket/javascript/test/integration.test.js
🧰 Additional context used
🪛 LanguageTool
packages/templates/clients/websocket/python/README.md

[uncategorized] ~8-~8: You might be missing the article “the” here.
Context: ...d run test with npm run test 4. Go to test folder with cd test 5. Install depend...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)


[uncategorized] ~10-~10: You might be missing the article “an” here.
Context: ...otTestResult/requirements.txt` 6. Start example script that uses a client library gener...

(AI_EN_LECTOR_MISSING_DETERMINER_AN)


[uncategorized] ~12-~12: Did you mean: “By default,”?
Context: ...ted by the test: python example.py > By default this is testing against Postman echo se...

(BY_DEFAULT_COMMA)


[uncategorized] ~12-~12: You might be missing the article “the” here.
Context: ...python example.py again. You will see example still works but agains different API. T...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

🔇 Additional comments (1)
packages/templates/clients/websocket/python/README.md (1)

12-12: Verify client class name in import and instantiation.

The class name PostmanEchoWebSocketClientClient appears to include “Client” twice. Please confirm that this matches the actual class defined in the generated code. If the class is named PostmanEchoWebSocketClient, adjust the import and instantiation accordingly to avoid confusion.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~12-~12: Did you mean: “By default,”?
Context: ...ted by the test: python example.py > By default this is testing against Postman echo se...

(BY_DEFAULT_COMMA)


[uncategorized] ~12-~12: You might be missing the article “the” here.
Context: ...python example.py again. You will see example still works but agains different API. T...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

@derberg

derberg commented Apr 17, 2025

Copy link
Copy Markdown
Member

/rtm

@asyncapi-bot
asyncapi-bot merged commit 8da5ac0 into asyncapi:master Apr 17, 2025
@derberg

derberg commented May 6, 2025

Copy link
Copy Markdown
Member

@allcontributors please add @Light13008 for test,review

@allcontributors

Copy link
Copy Markdown
Contributor

@derberg

I've put up a pull request to add @Light13008! 🎉

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.

[FEATURE] To add the generation of both postman-echo and hopscotch-echo in snapshot.test.js file of packages/template

4 participants