AssertRaises不能与PsycoPg2一起使用

时间:2018-03-06 15:17:13

标签: python unit-testing psycopg2 python-unittest

我正在尝试使用unittest测试使用Python 3.6在psycopg2中抛出错误。在这种情况下,名为foo的数据库不存在,并且它应该抛出OperationalError,因为数据库不是有效数据库。

以下是一个示例测试用例:

# -*- coding: utf-8 -*-
import unittest
import psycopg2
import logging


def pull_pg_data(conn, cursor, first, last):
    try:
        cursor.execute('SELECT first_name, last_name, email, street FROM user_data WHERE first_name =%s AND last_name=%s',(first, last))
    except psycopg2.OperationalError as msg:
        logging.error(msg)
        raise
    conn.commit()
    result = cursor.fetchall()
    return result


class SampleTestCases(unittest.TestCase):
    def setUp(self):
        try:
            self.conn = psycopg2.connect(dbname='postgres', user='postgres', host='localhost', port=5432,
                                         connect_timeout=10)
        except psycopg2.OperationalError as msg:
            logging.critical(msg)
            raise
        self.conn.autocommit = True
        self.cursor = self.conn.cursor()
        self.cursor.execute('DROP TABLE IF EXISTS user_data', [])
        self.cursor.execute('CREATE TABLE user_data (first_name TEXT, last_name TEXT, email TEXT, street TEXT)', [])
        self.cursor.execute("INSERT INTO user_data(first_name, last_name, email, street) VALUES('someFirstName', 'someLastName', 'some@example.com', '123 road')",[])

    def test_pull_pg_data_fail(self):
        conn = psycopg2.connect(dbname='foo', user='postgres', host='localhost', port=5432, connect_timeout=10)
        cursor = conn.cursor()
        self.assertRaises(psycopg2.OperationalError, pull_pg_data, conn, cursor, 'someFirstName', 'someLastName')


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

当我运行测试时,它确实会引发错误,但它未通过测试。我不知道我对assertRaises做错了什么,因为我确实想测试当我尝试连接到不存在的数据库时会抛出错误。

0 个答案:

没有答案