def database(request):
    """
    Fixture for starting an ephemeral database instance for the duration
    of the test suite
    """
    def get_psql_version():
        result = subprocess.check_output(["psql", "--version"]).decode("utf-8")
        version = result.split(" ")[-1].strip()
        major, minor, *_ = version.split(".")

        # Get the major and minor version, which are what pytest-postgresql
        # wants
        return f"{major}.{minor}"

    if os.environ.get("POSTGRES_USER"):
        # Use separately launched process if environments variables are defined
        # This is used in Gitlab CI tests which run in a Docker container
        user = os.environ["POSTGRES_USER"]
        host = os.environ["POSTGRES_HOST"]
        password = os.environ["POSTGRES_PASSWORD"]

        # POSTGRES_PORT can also be a value such as "tcp://1.1.1.1:5432"
        # This handles that format as well
        port = int(os.environ.get("POSTGRES_PORT", "5432").split(":")[-1])
        db_name = "passari_test"
        version = os.environ["POSTGRES_VERSION"]
        create_engine(
            f"postgresql://{user}:{password}@{host}:{port}/{db_name}")

        yield request.getfixturevalue("postgresql_nooproc")
    else:
        # Launch PostgreSQL ourselves
        postgresql = request.getfixturevalue("postgresql_proc")

        user = postgresql.user
        host = postgresql.host
        port = postgresql.port
        db_name = "passari_test"

        version = get_psql_version()

        with DatabaseJanitor(user, host, port, db_name, version):
            create_engine(f"postgresql://{user}@{host}:{port}/{db_name}")
            yield postgresql
示例#2
0
def config_database(request):
    connection_template = 'postgresql+psycopg2://{0}:{1}@{2}:{3}/{4}'

    pg_host = os.environ.get('POSTGRES_HOST', 'db')
    pg_port = os.environ.get('POSTGRES_PORT', 5432)
    pg_user = os.environ.get('POSTGRES_USER', 'tests')
    pg_passsword = os.environ.get('POSTGRES_PASSWORD', 'tests')
    pg_db = os.environ.get('POSTGRES_DB', 'tests')
    connection_string = connection_template.format(pg_user, pg_passsword,
                                                   pg_host, pg_port, pg_db)

    # Create the database
    janitor = DatabaseJanitor(pg_user, pg_host, pg_port, pg_db, '11',
                              pg_passsword)
    janitor.init()

    yield connection_string

    # Ensure the database gets deleted
    janitor.drop()