Commits

Pior Bastida committed e7d7d30

Add option to enable maintenance mode when a file exists

Comments (0)

Files changed (3)

 Development
 -----------
+
+* Add option to enable maintenance mode when a file exists

pyramid_health/tests.py

 import unittest
+import mock
 
 import webtest
 from pyramid.config import Configurator
 
         self.assertEqual(response.status_int, 200)
         self.assertEqual(response.body, b'OK')
+
+
+class TestHealthMaintenance(unittest.TestCase):
+
+    maxDiff = None
+
+    def setUp(self):
+        settings = {'health.maintenance.file': '/maintenance/file/test'}
+        config = Configurator(settings=settings)
+        config.include('pyramid_health')
+        self.app = webtest.TestApp(config.make_wsgi_app())
+
+    @mock.patch("os.path.exists")
+    def test_get_maintenance_on(self, m_exists):
+        m_exists.return_value = True
+
+        response = self.app.get('/health', expect_errors=True)
+
+        m_exists.assert_called_with('/maintenance/file/test')
+
+        self.assertEqual(response.status_int, 503)
+
+    @mock.patch("os.path.exists")
+    def test_get_maintenance_off(self, m_exists):
+        m_exists.return_value = False
+
+        response = self.app.get('/health')
+
+        m_exists.assert_called_with('/maintenance/file/test')
+
+        self.assertEqual(response.status_int, 200)
+        self.assertEqual(response.body, b'OK')

pyramid_health/views.py

+import os
+
 from pyramid.view import view_config
 from pyramid.response import Response
+from pyramid.httpexceptions import HTTPServiceUnavailable
 
 
 @view_config(route_name='healthcheck')
 
     For human-friendliness, a body containing 'OK' is also returned.
     """
+    settings = request.registry.settings
+
+    if 'health.maintenance.file' in settings:
+        if os.path.exists(settings['health.maintenance.file']):
+            return HTTPServiceUnavailable()
+
     return Response('OK', content_type='text/plain')