Skip to content

Question: Test postgres container #796

@brunolnetto

Description

@brunolnetto

What are you trying to do?

Run a minimal example with testcontainers. Run command:

pip install pytest
python3 test_postgres_container.py

test_postgres_container.py

import requests
import yaml
import time
import os

from testcontainers.k3s import K3SContainer
from testcontainers.postgres import PostgresContainer
from kubernetes import client, config

def wait_for_pod_ready(config_dict, namespace="default", timeout=120):
    """
    Wait for all pods in the namespace to be ready.
    """
    from kubernetes import client, config

    config.load_kube_config(config_file=config_dict)
    v1 = client.CoreV1Api()

    end_time = time.time() + timeout
    while time.time() < end_time:
        pods = v1.list_namespaced_pod(namespace=namespace)
        if all(p.status.phase == "Running" for p in pods.items):
            return True
        time.sleep(5)
    raise TimeoutError("Timeout waiting for pods to be ready")


def test_kubernetes_app():
    # Spin up PostgreSQL Container
    with PostgresContainer("postgres:15.0") as postgres:
        postgres_host = postgres.get_container_host_ip()
        postgres_port = postgres.get_exposed_port(5432)

        # Set up Kubernetes cluster
        with K3SContainer() as k3s:
            config_dict=yaml.safe_load(k3s.config_yaml())
            
            config.load_kube_config_from_dict(config_dict)

            os.environ["KUBECONFIG"] = config_dict

            # Apply Kubernetes manifests
            os.system(f"kubectl apply -f kubernetes/app.yaml")
            os.system(f"kubectl apply -f kubernetes/postgres.yaml")

            # Wait for all pods to be ready
            wait_for_pod_ready(config_dict)

            # Send an HTTP request to the application
            response = requests.get("http://localhost:8080/health")
            assert response.status_code == 200
            assert "healthy" in response.text

kubernetes/postgres.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - name: postgres
        image: postgres:15.0
        env:
        - name: POSTGRES_USER
          value: "user"
        - name: POSTGRES_PASSWORD
          value: "password"
        - name: POSTGRES_DB
          value: "mydb"

---
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  ports:
  - port: 5432
  selector:
    app: postgres

app.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app
        image: my-app-image:latest
        ports:
        - containerPort: 8080
        env:
        - name: DATABASE_URL
          value: "postgresql://user:password@postgres:5432/mydb"

---
apiVersion: v1
kind: Service
metadata:
  name: my-app
spec:
  type: NodePort
  selector:
    app: my-app
  ports:
  - protocol: TCP
    port: 8080
    targetPort: 8080

Runtime environment

>> uname -a

Linux DESKTOP-UP6B64S 5.15.153.1-microsoft-standard-WSL2 #1 SMP Fri Mar 29 23:14:13 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux

>> docker info
Client: Docker Engine - Community
 Version:    27.5.1
 Context:    default
 Debug Mode: false
 Plugins:
Server:
 Containers: 8
  Running: 7
  Paused: 0
  Stopped: 1
 Images: 34
 Server Version: 27.5.1
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Using metacopy: false
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Cgroup Version: 1
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local splunk syslog
 Swarm: active
  NodeID: q8b9mpmb1zgtsz81plpx97g6q
  Is Manager: true
  ClusterID: ayrevwl1es784e2k38ogh2j8g
  Managers: 1
  Nodes: 1
  Default Address Pool: 10.0.0.0/8
  SubnetSize: 24
  Data Path Port: 4789
  Orchestration:
   Task History Retention Limit: 5
  Raft:
   Snapshot Interval: 10000
   Number of Old Snapshots to Retain: 0
   Heartbeat Tick: 1
   Election Tick: 10
  Dispatcher:
   Heartbeat Period: 5 seconds
  CA Configuration:
   Expiry Duration: 3 months
   Force Rotate: 0
  Autolock Managers: false
  Root Rotation In Progress: false
  Node Address: 172.17.138.216
  Manager Addresses:
   172.17.138.216:2377
 Runtimes: io.containerd.runc.v2 runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: bcc810d6b9066471b0b6fa75f557a15a1cbf31bb
 runc version: v1.2.4-0-g6c52b3f
 init version: de40ad0
 Security Options:
  seccomp
   Profile: builtin
 Kernel Version: 5.15.153.1-microsoft-standard-WSL2
 Operating System: Ubuntu 22.04.5 LTS
 OSType: linux
 Architecture: x86_64
 CPUs: 12
 Total Memory: 7.607GiB
 Name: DESKTOP-UP6B64S
 ID: fe231f46-b911-4db9-b4e0-7a80f27d8058
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Username: brunolnetto1234
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

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

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy