Skip to content

Commit

Permalink
improved detection of postgres already running on a port
Browse files Browse the repository at this point in the history
  • Loading branch information
darthbear committed Aug 13, 2015
1 parent c5e147b commit f0d0964
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
19 changes: 10 additions & 9 deletions pyembedpg.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import os
from os.path import expanduser
import re
import socket
import tempfile
from psycopg2._psycopg import OperationalError
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
Expand Down Expand Up @@ -172,15 +173,17 @@ def __init__(self, bin_dir, ports):
'host all all ::1/128 md5\n'.format(admin=DatabaseRunner.ADMIN_USER)
)

for port in ports:
self.proc = Popen([self._postgres_cmd, '-D', self._temp_dir, '-p', str(port)])
# if the process is still running, then there was problem, most likely the port is taken so try the next one
if not self.proc.poll():
self.running_port = port
break
else:
def can_connect(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return sock.connect_ex(('127.0.0.1', port)) != 0

self.running_port = next((port for port in ports if can_connect(port)), None)
if self.running_port is None:
raise PyEmbedPgException('Cannot run postgres on any of these ports [{ports}]'.format(ports=', '.join((str(p) for p in ports))))

self.proc = Popen([self._postgres_cmd, '-D', self._temp_dir, '-p', str(self.running_port)])
logger.debug('Postgres started on port {port}...'.format(port=self.running_port))

# Loop until the server is started
logger.debug('Waiting for Postgres to start...')
start = time.time()
Expand All @@ -194,8 +197,6 @@ def __init__(self, bin_dir, ports):
else:
raise PyEmbedPgException('Cannot start postgres after {timeout} seconds'.format(timeout=DatabaseRunner.TIMEOUT))

logger.debug('Postgres started on port {port}...'.format(port=self.running_port))

def __enter__(self):
return self

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def run_tests(self):

setup(
name='pyembedpg',
version='0.0.2',
version='0.0.3',
description='Run embedded version of Postgres',
long_description='Run embedded version of Postgres',
keywords='postgres, python, tests',
Expand Down

0 comments on commit f0d0964

Please sign in to comment.