Skip to content

Commit

Permalink
fix(mongodb): waiting for container to start (it was not waiting at a…
Browse files Browse the repository at this point in the history
…ll before?) (testcontainers#461)

we were using this code to test if it was online or
not:`MongoClient(self.get_connection_url())`, but that doesn't actually
perform any connection, instead you have to do something like:

```python
    @wait_container_is_ready()
    def _connect(self):
        client = self.get_connection_client()
        # will raise pymongo.errors.ServerSelectionTimeoutError if no connection is established
        client.admin.command('ismaster')
```

thanks to @smparekh for pointing this out, in his PR:


https://github.com/testcontainers/testcontainers-python/pull/80/files#diff-cf09f76f44db0af04c58ddb456ccae39f7e29ce1d9208acd5f514c0a7dccb646R78

this PR implements the workaround described in the PR:

```python
@pytest.fixture(scope="session")
def test_client():
    # init mongo
    mongo_container = MongoDbContainer("mongo:4").start()
    wait_for_logs(mongo_container, 'waiting for connections on port 27017')
    ...

Co-authored-by: Shaishav Parekh <sparekh@oneweb.net>
  • Loading branch information
alexanderankin and Shaishav Parekh authored Mar 9, 2024
1 parent 5bef18a commit 2c4f171
Showing 1 changed file with 4 additions and 5 deletions.
9 changes: 4 additions & 5 deletions modules/mongodb/testcontainers/mongodb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

from testcontainers.core.generic import DbContainer
from testcontainers.core.utils import raise_for_deprecated_parameter
from testcontainers.core.waiting_utils import wait_container_is_ready
from testcontainers.core.waiting_utils import wait_for_logs


class MongoDbContainer(DbContainer):
Expand Down Expand Up @@ -81,9 +81,8 @@ def get_connection_url(self) -> str:
port=self.port,
)

@wait_container_is_ready()
def _connect(self) -> MongoClient:
return MongoClient(self.get_connection_url())
def _connect(self) -> None:
wait_for_logs(self, "Waiting for connections")

def get_connection_client(self) -> MongoClient:
return self._connect()
return MongoClient(self.get_connection_url())

0 comments on commit 2c4f171

Please sign in to comment.