Skip to content

Instantly share code, notes, and snippets.

@asyd
Forked from graphaelli/test_pg_conn_mock.py
Created March 2, 2018 01:15
Show Gist options
  • Select an option

  • Save asyd/6b32d87355ddba1f7995ccf6ad0290b2 to your computer and use it in GitHub Desktop.

Select an option

Save asyd/6b32d87355ddba1f7995ccf6ad0290b2 to your computer and use it in GitHub Desktop.

Revisions

  1. @graphaelli graphaelli created this gist Dec 9, 2016.
    33 changes: 33 additions & 0 deletions test_pg_conn_mock.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    #!/usr/bin/env python

    from __future__ import print_function

    try:
    import mock
    except ImportError:
    from unittest import mock
    import unittest

    import psycopg2


    def ex(user_id):
    with psycopg2.connect("") as conn:
    with conn.cursor() as cursor:
    cursor.execute("SELECT first_name FROM users WHERE id = %s", (user_id,))
    return cursor.fetchall()


    class TestPatchConn(unittest.TestCase):
    def setUp(self):
    self.user_id = 16

    @mock.patch('psycopg2.connect')
    def test_with_context(self, mock_connect):
    mock_connect().__enter__().cursor().__enter__().fetchall.return_value = ['Stacy']
    ex(self.user_id)
    mock_connect().__enter__().cursor().__enter__().execute.assert_called_with('SELECT first_name FROM users WHERE id = %s', (self.user_id, ))


    if __name__ == '__main__':
    unittest.main()