-
Notifications
You must be signed in to change notification settings - Fork 312
fix(nats): Client-Free(ish) NATS container #462
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
.. autoclass:: testcontainers.nats.NatsContainer | ||
.. title:: testcontainers.nats.NatsContainer |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); you may | ||
# not use this file except in compliance with the License. You may obtain | ||
# a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
# License for the specific language governing permissions and limitations | ||
# under the License. | ||
|
||
|
||
from testcontainers.core.container import DockerContainer | ||
from testcontainers.core.waiting_utils import wait_container_is_ready, wait_for_logs | ||
|
||
|
||
class NatsContainer(DockerContainer): | ||
""" | ||
Nats container. | ||
|
||
Example: | ||
|
||
.. doctest:: | ||
|
||
>>> import asyncio | ||
>>> from nats import connect as nats_connect | ||
>>> from testcontainers.nats import NatsContainer | ||
|
||
>>> async def test_doctest_usage(): | ||
... with NatsContainer() as nats_container: | ||
... client = await nats_connect(nats_container.nats_uri()) | ||
... sub_tc = await client.subscribe("tc") | ||
... await client.publish("tc", b"Test-Containers") | ||
... next_message = await sub_tc.next_msg(timeout=5.0) | ||
... await client.close() | ||
... return next_message.data | ||
>>> asyncio.run(test_doctest_usage()) | ||
b'Test-Containers' | ||
""" | ||
|
||
def __init__( | ||
self, | ||
image: str = "nats:latest", | ||
client_port: int = 4222, | ||
management_port: int = 8222, | ||
expected_ready_log: str = "Server is ready", | ||
ready_timeout_secs: int = 120, | ||
**kwargs, | ||
) -> None: | ||
super().__init__(image, **kwargs) | ||
self.client_port = client_port | ||
self.management_port = management_port | ||
self._expected_ready_log = expected_ready_log | ||
self._ready_timeout_secs = max(ready_timeout_secs, 0) | ||
self.with_exposed_ports(self.client_port, self.management_port) | ||
|
||
@wait_container_is_ready() | ||
def _healthcheck(self) -> None: | ||
wait_for_logs(self, self._expected_ready_log, timeout=self._ready_timeout_secs) | ||
|
||
def nats_uri(self) -> str: | ||
return f"nats://{self.get_container_host_ip()}:{self.get_exposed_port(self.client_port)}" | ||
|
||
def nats_host_and_port(self) -> tuple[str, int]: | ||
return self.get_container_host_ip(), self.get_exposed_port(self.client_port) | ||
|
||
def nats_management_uri(self) -> str: | ||
return f"nats://{self.get_container_host_ip()}:{self.get_exposed_port(self.management_port)}" | ||
|
||
def start(self) -> "NatsContainer": | ||
super().start() | ||
self._healthcheck() | ||
return self |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
from testcontainers.nats import NatsContainer | ||
from uuid import uuid4 | ||
import pytest | ||
|
||
from nats import connect as nats_connect | ||
from nats.aio.client import Client as NATSClient | ||
|
||
|
||
async def get_client(container: NatsContainer) -> "NATSClient": | ||
""" | ||
Get a nats client. | ||
|
||
Returns: | ||
client: Nats client to connect to the container. | ||
""" | ||
conn_string = container.nats_uri() | ||
client = await nats_connect(conn_string) | ||
return client | ||
|
||
|
||
def test_basic_container_ops(): | ||
with NatsContainer() as container: | ||
alexanderankin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# Not sure how to get type information without doing this | ||
container: NatsContainer = container | ||
h, p = container.nats_host_and_port() | ||
assert h == "localhost" | ||
uri = container.nats_uri() | ||
management_uri = container.nats_management_uri() | ||
|
||
assert uri != management_uri | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_pubsub(anyio_backend): | ||
with NatsContainer() as container: | ||
nc: NATSClient = await get_client(container) | ||
|
||
topic = str(uuid4()) | ||
|
||
sub = await nc.subscribe(topic) | ||
sent_message = b"Test-Containers" | ||
await nc.publish(topic, b"Test-Containers") | ||
received_msg = await sub.next_msg() | ||
print("Received:", received_msg) | ||
assert sent_message == received_msg.data | ||
await nc.flush() | ||
await nc.close() | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_more_complex_example(anyio_backend): | ||
with NatsContainer() as container: | ||
nc: NATSClient = await get_client(container) | ||
|
||
sub = await nc.subscribe("greet.*") | ||
await nc.publish("greet.joe", b"hello") | ||
|
||
try: | ||
await sub.next_msg(timeout=0.1) | ||
except TimeoutError: | ||
pass | ||
|
||
await nc.publish("greet.joe", b"hello.joe") | ||
await nc.publish("greet.pam", b"hello.pam") | ||
|
||
first = await sub.next_msg(timeout=0.1) | ||
assert b"hello.joe" == first.data | ||
|
||
second = await sub.next_msg(timeout=0.1) | ||
assert b"hello.pam" == second.data | ||
|
||
await nc.publish("greet.bob", b"hello") | ||
|
||
await sub.unsubscribe() | ||
await nc.drain() | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_doctest_usage(): | ||
"""simpler to run test to mirror what is in the doctest""" | ||
with NatsContainer() as nats_container: | ||
client = await nats_connect(nats_container.nats_uri()) | ||
sub_tc = await client.subscribe("tc") | ||
await client.publish("tc", b"Test-Containers") | ||
next_message = await sub_tc.next_msg(timeout=5.0) | ||
await client.close() | ||
assert next_message.data == b"Test-Containers" |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.