我有一个简单的postgres上下文对象,负责执行查询。 我想模拟这个对象的测试,我在下面给出了测试。
pgconn.py
"""PostgresDbContext module"""
import os
import time
import psycopg2.extras
import sys
from log import LOGGER
class PgDbContext(object):
@staticmethod
def build_from_environment():
pg_username = os.environ['POSTGRES_USERNAME']
pg_password = os.environ['POSTGRES_PASSWORD']
try:
conn = psycopg2.connect("user=" + pg_username + " host='localhost' password=" + pg_password)
# program ends if the connection fails.
except psycopg2.OperationalError, oe:
raise oe
sys.exit(1)
return PgDbContext(conn)
def __init__(self, conn,):
self.conn = conn
def execute(self, qry):
""" returns a function that executes the query and returns the result"""
self.conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor).execute(qry)
rows = self.cur.fetchall()
return rows
def close(self):
""" closes the connection"""
self._conn.close()
test.py
import unittest
import os
import mock
import psycopg2
from pgconn import PgDbContext
class TestMock(unittest.TestCase):
def setUp(self):
self.conn = mock.MagicMock(psycopg2.connect)
self.dbcontext = PgDbContext(self.conn)
def test_execute_query(self):
self.dbcontext.conn().cursor().execute().side_effect = psycopg2.DatabaseError
results = [each for each in self.dbcontext.execute('SELECT version()')] # type: object
self.assertEqual(1, 1)
错误: -
raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute 'cursor'