1

I need to mock postgres select query data in python-unittest

def execute_query(self, query, fetch=False):
    logger.info("Start querying database")
    cursor = None
    connection = None
    try:
        connection = self.connection_pool.getconn()

        logger.info("Successfully received connection from connection pool")
        cursor = connection.cursor()
        logger.info("Successfully connected to database")
        cursor.execute(query)

        if fetch:
            result_list = cursor.fetchall()

1 Answers1

0

If you want a python-centric solution try testing.postgresql from PyPI (also see here).

It might be overkill but you could also easily spin up a docker container with postgres and test against that. The advantage with this approach is that it is more modular and you could add other databases if you need in the future. See the following compose file. By default this image will give you one empty database with admin privileges.

version: '3'
services:

  psql:
    # you can also choose a specific version to test instead 
    # of 'latest' or use your own Dockerfile for custom setup
    image: 'postgres:latest'
    ports:
      - 5432:5432
    environment:
      POSTGRES_USER: test-username
      POSTGRES_PASSWORD: supersecretpassword
      POSTGRES_DB: test-db-name

  # mysql if you want...
  # sqlserver if you want...
petrucci4prez
  • 446
  • 3
  • 4