简体   繁体   中英

Mocking database call in a way that it checks the SQL query

I have a code that executes queries to redshift like this:

def send_sql_query(source, sql_query, lst=None):
        connection = psycopg2.connect(
                host=os.environ["REDSHIFT_HOST"],
                port="5439",
                dbname="dbname",
                user=os.environ["REDSHIFT_USERNAME"],
                password=os.environ["REDSHIFT_PASSWORD"],
        cursor = connection.cursor()
        cursor.execute(sql_query, lst)
        sql_results = cursor.fetchall()


        return sql_results
    finally:
        if connection:
            connection.close()

I would like to mock the method in a way that it will retrieve and sql_query, and the method will hold a fake db data (preferable in json), but will execute the SQL on the fake data with the sql_query and return the result.

Using mock.return_value and mock.side_effect will not help, because I want to verify that the SQL query is correct. Writing a code to return results doesn't really check the SQL query

Is there a framework in python for it?

Testing the SQL requires a SQL engine. As different databases use different dialects and as you use PostgreSQL as you main database, you should install a PostgreSQL instance on you dev environment with fake data and redirect your queries there while testing.

As you use the environment to store the reference of the database, you have just to setup a test environment pointing to the test database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM