Skip to content

Commit 066b178

Browse files
authored
Redis container password support (#195)
* redis container password support * fixed test * fixed test * fixed test_docker_run_redis_with_password test
1 parent 1f0ca14 commit 066b178

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

testcontainers/redis.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,18 @@
1212
# under the License.
1313

1414
import redis
15-
1615
from testcontainers.core.container import DockerContainer
1716
from testcontainers.core.waiting_utils import wait_container_is_ready
1817

1918

2019
class RedisContainer(DockerContainer):
21-
def __init__(self, image="redis:latest", port_to_expose=6379):
20+
def __init__(self, image="redis:latest", port_to_expose=6379, password=None):
2221
super(RedisContainer, self).__init__(image)
2322
self.port_to_expose = port_to_expose
23+
self.password = password
2424
self.with_exposed_ports(self.port_to_expose)
25+
if self.password:
26+
self.with_command(f"redis-server --requirepass {self.password}")
2527

2628
@wait_container_is_ready(redis.exceptions.ConnectionError)
2729
def _connect(self):
@@ -44,7 +46,8 @@ def get_client(self, **kwargs):
4446
"""
4547
return redis.Redis(
4648
host=self.get_container_host_ip(),
47-
port=self.get_exposed_port(6379),
49+
port=self.get_exposed_port(self.port_to_expose),
50+
password=self.password,
4851
**kwargs,
4952
)
5053

tests/test_redis.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ def test_docker_run_redis():
1515
assert b'new_msg', msg['data']
1616

1717

18+
def test_docker_run_redis_with_password():
19+
config = RedisContainer(password="mypass")
20+
with config as redis:
21+
client = redis.get_client(decode_responses=True)
22+
client.set("hello", "world")
23+
assert client.get("hello") == "world"
24+
25+
1826
def wait_for_message(pubsub, timeout=1, ignore_subscribe_messages=True):
1927
now = time.time()
2028
timeout = now + timeout

0 commit comments

Comments
 (0)