Merge pull request #13 from zalando/feature/unittests

Add Tests for testing the statuspage, extend the PostgreSQL test to r…
This commit is contained in:
Feike Steenbergen
2015-05-21 15:03:31 +02:00
3 changed files with 87 additions and 43 deletions
+1 -30
View File
@@ -33,7 +33,7 @@ class StatusPage(BaseHTTPRequestHandler):
self.send_response(response)
self.send_header('Content-Type', content_type)
self.end_headers()
self.wfile.write(content)
self.wfile.write(content.encode('utf-8'))
def pg_is_in_recovery(self):
cursor = self.server.postgresql.cursor()
@@ -63,32 +63,3 @@ def getHTTPServer(postgresql, http_port=8081, listen_address='0.0.0.0'):
server.postgresql = postgresql
return server
if __name__ == '__main__':
import sys
import logging
logging.basicConfig(format='%(levelname)-6s %(asctime)s - %(message)s', level=logging.DEBUG)
logging.debug('Starting as a standalone application')
# Create a dummy configuration to be able to use the Postgresql class
from postgresql import Postgresql
postgres_config = {
'name': 'dummy',
'listen': 'localhost:5432',
'data_dir': 'nonsense',
'replication': {'username': None, 'password': None},
'superuser': None,
'admin': None,
}
aws_host_address = None
if len(sys.argv) > 1:
postgres_config['listen'] = sys.argv[1]
postgresql = Postgresql(postgres_config, aws_host_address)
http_port = 8081
if len(sys.argv) > 2:
http_port = int(sys.argv[2])
getHTTPServer(postgresql, http_port, '0.0.0.0').serve_forever()
+48 -13
View File
@@ -1,3 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import psycopg2
import unittest
@@ -21,25 +24,48 @@ def false(*args, **kwargs):
class MockCursor:
def __init__(self):
def __init__(self, server):
self.current = 0
self.results = []
self.server = server
def execute(self, sql, *params):
if sql.startswith('blabla'):
raise psycopg2.OperationalError()
elif sql.startswith('SELECT slot_name'):
self.results = [('blabla'), ('foobar')]
self.results = [('blabla',), ('foobar',)]
elif sql.startswith('SELECT pg_current_xlog_location()'):
self.results = [(0,)]
self.results = [(0, )]
elif sql.startswith('SELECT %s - (pg_last_xlog_replay_location()'):
self.results = [(0,)]
self.results = [(0, )]
elif sql.startswith('SELECT pg_last_xlog_replay_location()'):
self.results = [(0,)]
self.results = [(0, )]
elif sql.startswith('SELECT pg_is_in_recovery()'):
self.results = [(False, )]
self.results = [(
self.server.mock_values['mock_recovery'],
None,
None,
None,
None,
None,
None,
None,
None,
None,
)]
else:
self.results = []
self.results = [(
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
)]
def fetchone(self):
return self.results[0]
@@ -56,9 +82,10 @@ class MockConnect:
def __init__(self):
self.autocommit = False
self.mock_values = {'mock_recovery': False}
def cursor(self):
return MockCursor()
return MockCursor(self)
def close(self):
if not self.autocommit:
@@ -84,11 +111,17 @@ class TestPostgresql(unittest.TestCase):
def set_up(self):
os.system = os_system
shutil.copy = nop
self.p = Postgresql({'name': 'test0', 'data_dir': 'data/test0', 'listen': '127.0.0.1, 127.0.0.2:5432',
'connect_address': '127.0.0.2:5432', 'superuser': {'password': ''},
'admin': {'username': 'admin', 'password': 'admin'}, 'replication': {
'username': 'replicator', 'password': 'rep-pass', 'network': '127.0.0.1/32'},
'parameters': {'foo': 'bar'}, 'recovery_conf': {'foo': 'bar'}})
self.p = Postgresql({
'name': 'test0',
'data_dir': 'data/test0',
'listen': '127.0.0.1, 127.0.0.2:5432',
'connect_address': '127.0.0.2:5432',
'superuser': {'password': ''},
'admin': {'username': 'admin', 'password': 'admin'},
'replication': {'username': 'replicator', 'password': 'rep-pass', 'network': '127.0.0.1/32'},
'parameters': {'foo': 'bar'},
'recovery_conf': {'foo': 'bar'},
})
psycopg2.connect = psycopg2_connect
if not os.path.exists(self.p.data_dir):
os.makedirs(self.p.data_dir)
@@ -156,3 +189,5 @@ class TestPostgresql(unittest.TestCase):
def test_last_operation(self):
self.assertEquals(self.p.last_operation(), 0)
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
from helpers.statuspage import StatusPage
from test_postgresql import MockConnect
if sys.hexversion >= 0x03000000:
from io import BytesIO as IO
else:
from StringIO import StringIO as IO
class TestStatusPage(unittest.TestCase):
def test_do_GET(self):
for mock_recovery in [True, False]:
for page in [b'GET /pg_master', b'GET /pg_slave', b'GET /pg_status', b'GET /not_found']:
self.http_server = MockServer(('0.0.0.0', 8888), StatusPage, page, mock_recovery)
class MockRequest(object):
def __init__(self, path):
self.path = path
def makefile(self, *args, **kwargs):
return IO(self.path)
class MockServer(object):
def __init__(self, ip_port, Handler, path, mock_recovery=False):
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)