# Path: postgraas_server/backends/exceptions.py
# class PostgraasApiException(Exception):
#     """Base exception which should be used by backends instead of their own
#     backend specific exceptions.
# 
#     .. example::
# 
#         try:
#             docker_backend.do_something()
#         except docker.errors.APIError as e:
#             raise PostgraasApiException(str(e))
# 
#     """
# 
#     def __init__(self, message=None):
#         self.message = message
# 
#     def __str__(self):
#         return self.message
# 
# Path: postgraas_server/create_app.py
# def create_app(config):
#     app = Flask(__name__)
# 
#     app.config['SQLALCHEMY_DATABASE_URI'] = get_meta_db_config_path(config)
#     app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#     app.config['BUNDLE_ERRORS'] = True
#     app_config = get_application_config(config)
# 
#     for key in app_config:
#         app.config[key.upper()] = int(app_config[key]) if key.upper() in INT_OPTIONS else app_config[key]
#     app.config['SENTRY_INCLUDE_PATHS'] = [
#         'postgraas_server',
#     ]
#     app.config['SENTRY_RELEASE'] = postgraas_server.__version__
#     sentry.init_app(app)
# 
#     restful_api = Api(app)
#     restful_api.add_resource(DBInstanceResource, "/api/v2/postgraas_instances/<int:id>")
#     restful_api.add_resource(DBInstanceCollectionResource, "/api/v2/postgraas_instances")
#     db.init_app(app)
#     app.postgraas_backend = get_backend(config)
# 
#     @app.route('/health')
#     def health():
#         return "ok"
# 
#     return app
# 
# Path: tests/test_integration/utils.py
# def wait_for_postgres_listening(container_id, timeout=10):
#     """
#     Inspect/follow the output of the docker container logs until encountering the
#     message from postgres that it accepts connections.
# 
#     Raises in case the container does not exist.
# 
#     Caveat: this check is specific to the used docker image.
#     Tested for current postgres:9.4 image.
# 
#     :returns: boolean, whether the message has been (True), or the timeout has been hit (False).
#     """
#     c = _docker_client()
#     cont = c.containers.get(container_id)
#     for i in range(max(int(timeout * 10), 1)):
#         # not very efficient to always gather all logs, but as we only use it for testing
#         # and it seems to be fast enough, should be OK.
#         output = cont.logs(stdout=True, stderr=True)
#         # the startup script in the docker image starts postgres twice,
#         # so wait for the second start:
#         if output.count(b'database system is ready to accept connections') >= 2:
#             return True
#         time.sleep(0.1)
#     return False


import json
import os
import uuid
import docker
import pytest
import psycopg2
import postgraas_server.backends.docker.postgres_instance_driver as pid
import postgraas_server.backends.postgres_cluster.postgres_cluster_driver as pgcd
import postgraas_server.configuration as configuration
from mock import patch, MagicMock, Mock
from contextlib import closing
from postgraas_server.backends.exceptions import PostgraasApiException
from postgraas_server.create_app import create_app
from .utils import wait_for_postgres_listening
    from postgraas_server.management_resources import db
    from postgraas_server.management_resources import db
        assert deleted_db["status"] == 'success'

    def test_delete_notfound(self):
        headers = {'Content-Type': 'application/json'}
        res = self.app_client.delete(
            '/api/v2/postgraas_instances/123456789',
            data=json.dumps({
                'db_pwd': '123'
            }),
            headers=headers
        )
        assert res.status_code == 404
        res = json.loads(res.get_data(as_text=True))
        assert res['status'] == 'failed'
        assert "123456789" in res['msg'], 'unexpected error message'

    def test_delete_postgres_instance_api_with_active_sessions(self):
        db_credentials = {
            "postgraas_instance_name": "test_active_sessions_instance",
            "db_name": "test_active_sessions_db",
            "db_username": "test_active_sessions_user",
            "db_pwd": "secret"
        }
        headers = {'Content-Type': 'application/json'}
        result = self.app_client.post(
            '/api/v2/postgraas_instances', headers=headers, data=json.dumps(db_credentials)
        )
        created_db = json.loads(result.get_data(as_text=True))

        if self.backend == 'docker':

# Path: postgraas_server/backends/exceptions.py
# class PostgraasApiException(Exception):
#     """Base exception which should be used by backends instead of their own
#     backend specific exceptions.
# 
#     .. example::
# 
#         try:
#             docker_backend.do_something()
#         except docker.errors.APIError as e:
#             raise PostgraasApiException(str(e))
# 
#     """
# 
#     def __init__(self, message=None):
#         self.message = message
# 
#     def __str__(self):
#         return self.message
# 
# Path: postgraas_server/create_app.py
# def create_app(config):
#     app = Flask(__name__)
# 
#     app.config['SQLALCHEMY_DATABASE_URI'] = get_meta_db_config_path(config)
#     app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#     app.config['BUNDLE_ERRORS'] = True
#     app_config = get_application_config(config)
# 
#     for key in app_config:
#         app.config[key.upper()] = int(app_config[key]) if key.upper() in INT_OPTIONS else app_config[key]
#     app.config['SENTRY_INCLUDE_PATHS'] = [
#         'postgraas_server',
#     ]
#     app.config['SENTRY_RELEASE'] = postgraas_server.__version__
#     sentry.init_app(app)
# 
#     restful_api = Api(app)
#     restful_api.add_resource(DBInstanceResource, "/api/v2/postgraas_instances/<int:id>")
#     restful_api.add_resource(DBInstanceCollectionResource, "/api/v2/postgraas_instances")
#     db.init_app(app)
#     app.postgraas_backend = get_backend(config)
# 
#     @app.route('/health')
#     def health():
#         return "ok"
# 
#     return app
# 
# Path: tests/test_integration/utils.py
# def wait_for_postgres_listening(container_id, timeout=10):
#     """
#     Inspect/follow the output of the docker container logs until encountering the
#     message from postgres that it accepts connections.
# 
#     Raises in case the container does not exist.
# 
#     Caveat: this check is specific to the used docker image.
#     Tested for current postgres:9.4 image.
# 
#     :returns: boolean, whether the message has been (True), or the timeout has been hit (False).
#     """
#     c = _docker_client()
#     cont = c.containers.get(container_id)
#     for i in range(max(int(timeout * 10), 1)):
#         # not very efficient to always gather all logs, but as we only use it for testing
#         # and it seems to be fast enough, should be OK.
#         output = cont.logs(stdout=True, stderr=True)
#         # the startup script in the docker image starts postgres twice,
#         # so wait for the second start:
#         if output.count(b'database system is ready to accept connections') >= 2:
#             return True
#         time.sleep(0.1)
#     return False


# Path: tests/test_integration/test_postgraas_api.py
import json
import os
import uuid
import docker
import pytest
import psycopg2
import postgraas_server.backends.docker.postgres_instance_driver as pid
import postgraas_server.backends.postgres_cluster.postgres_cluster_driver as pgcd
import postgraas_server.configuration as configuration
from mock import patch, MagicMock, Mock
from contextlib import closing
from postgraas_server.backends.exceptions import PostgraasApiException
from postgraas_server.create_app import create_app
from .utils import wait_for_postgres_listening
    from postgraas_server.management_resources import db
    from postgraas_server.management_resources import db

        assert deleted_db["status"] == 'success'

    def test_delete_notfound(self):
        headers = {'Content-Type': 'application/json'}
        res = self.app_client.delete(
            '/api/v2/postgraas_instances/123456789',
            data=json.dumps({
                'db_pwd': '123'
            }),
            headers=headers
        )
        assert res.status_code == 404
        res = json.loads(res.get_data(as_text=True))
        assert res['status'] == 'failed'
        assert "123456789" in res['msg'], 'unexpected error message'

    def test_delete_postgres_instance_api_with_active_sessions(self):
        db_credentials = {
            "postgraas_instance_name": "test_active_sessions_instance",
            "db_name": "test_active_sessions_db",
            "db_username": "test_active_sessions_user",
            "db_pwd": "secret"
        }
        headers = {'Content-Type': 'application/json'}
        result = self.app_client.post(
            '/api/v2/postgraas_instances', headers=headers, data=json.dumps(db_credentials)
        )
        created_db = json.loads(result.get_data(as_text=True))

        if self.backend == 'docker':

            wait_success = wait_for_postgres_listening(created_db['container_id'])