aboutsummaryrefslogtreecommitdiff
path: root/tests/test_postgres.py
blob: 92eed716c657f8ea5fe7e24cbf017f2640bbf04b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import socket
import subprocess

from pydantic import PostgresDsn

from generalresearch.models.custom_types import InternalHostname
from generalresearch.pg_helper import PostgresConfig


def is_port_open(host: InternalHostname, port: int = 5432, timeout: int = 3):
    try:
        with socket.create_connection((host, port), timeout=timeout):
            return True
    except (socket.timeout, ConnectionRefusedError, OSError):
        return False


def can_ping(host: InternalHostname):
    return (
        subprocess.call(
            ["ping", "-c", "1", str(host)],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        == 0
    )


class TestPostgresDSN:

    def test_ping(self, postgres_instance_host: InternalHostname):
        assert can_ping(host=postgres_instance_host)

    def test_port(self, postgres_instance_host: InternalHostname):
        assert is_port_open(host=postgres_instance_host)

    def test_conn(self, postgres_instance: PostgresDsn):
        config = PostgresConfig(
            dsn=postgres_instance,
            connect_timeout=1,
            statement_timeout=1,
        )
        res = config.execute_sql_query(query="SELECT 1;")
        assert len(res) == 1