8000 [Question] Async Client and testing with RedisContainer · Issue #374 · testcontainers/testcontainers-python · GitHub
[go: up one dir, main page]

Skip to content

[Question] Async Client and testing with RedisContainer #374

@bearrito

Description

@bearrito

Hello,

I'm attempting to use the RedisContainer inside a IsolatedAsyncioTestCase
It seems like the below works

from redis.asyncio import Redis
from testcontainers.redis import RedisContainer


class AsyncRedisContainer(RedisContainer):
    """
    Redis container.

    Example
    -------
    .. doctest::

        >>> from testcontainers.redis import AsyncRedisContainer

        >>> with AsyncRedisContainer() as redis_container:
        ...     redis_client =await  redis_container.get_async_client()
    """

    def __init__(
        self, image="redis:latest", port_to_expose=6379, password=None, **kwargs
    ):
        super(AsyncRedisContainer, self).__init__(
            image, port_to_expose, password, **kwargs
        )

    async def get_async_client(self, **kwargs):
        return await Redis(
            host=self.get_container_host_ip(),
            port=self.get_exposed_port(self.port_to_expose),
            password=self.password,
            **kwargs,
        )


class TestAyncRedisContainerContainer(IsolatedAsyncioTestCase):
    async def test_foo(self):
        with AsyncRedisContainer.AsyncRedisContainer() as container:
            async_redis_client: redis.Redis = await container.get_async_client(
                decode_responses=True
            )
            key = "key"
            expected_value = 1
            await async_redis_client.set(key, expected_value)
            actual_value = await async_redis_client.get(key)
            self.assertEqual(int(actual_value), expected_value)


Is there a cleaner way to do this? If so, would there be any interest in a PR?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0