如何在使用postgresql的python中测试异常
我有我自己的课堂文章,专门为PostgreSQL编写。从类创建的每个对象都用于处理一行。现在我不知道如何测试异常情况。当我创建此类案例时:如何在使用postgresql的python中测试异常,python,postgresql,unit-testing,exception,Python,Postgresql,Unit Testing,Exception,我有我自己的课堂文章,专门为PostgreSQL编写。从类创建的每个对象都用于处理一行。现在我不知道如何测试异常情况。当我创建此类案例时: article = Article(2)/*connects to the db and loads line with id 2*/ print article.title2 /*here my db does not have table title2 and should launch an error*/ 它应该抛出错误。确实如此) 测试用例应该是
article = Article(2)/*connects to the db and loads line with id 2*/
print article.title2 /*here my db does not have table title2 and should launch an error*/
它应该抛出错误。确实如此)
测试用例应该是什么样子的?我使用单元测试。我的测试类使用了错误的方法,但不起作用,如下所示:
import unittest
from article import * /*import my ORM class*/
class EntityTest(unittest.TestCase):
def setUp(self):
Entity.db = psycopg2.connect("dbname='postgres' user='postgres' host='192.168.136.129' password='xxxxxxxxx'")/*creates connection to db*/
def test_should_lounch_attr_error(self):
article = Article(2)
print article.title2
self.assertRaisesRegex(article.AttributeError, "No attribute exists")
我不知道如何创建测试用例,也没有太多关于如何创建测试用例的好文档(((
正如我所理解的,如果通过了testcase(生成了异常),unittest应该返回Ok语句。现在它只显示错误。如果您不提供可调用到
assertRaisesRegexp()
(注意assertRaisesRegexp()
,而不是assertRaisesRegex()
),然后它将充当上下文管理器。在这种情况下,您应该将与
语句一起使用,如下所示:
import unittest
from article import * /*import my ORM class*/
class EntityTest(unittest.TestCase):
def setUp(self):
Entity.db = psycopg2.connect("dbname='postgres' user='postgres' host='192.168.136.129' password='xxxxxxxxx'")/*creates connection to db*/
def test_should_lounch_attr_error(self):
with self.assertRaisesRegexp(article.AttributeError, "No attribute exists"):
article = Article(2)
print article.title2
除非您的代码可以使用不同的字符串表示形式生成article.AttributeError
,否则我认为您实际上不需要为此使用正则表达式。只需使用assertRaises()
检查article.AttributeError
。这就足够了:
with self.assertRaisesRegexp(article.AttributeError):
article = Article(2)
print article.title2
它显示错误,因为它是在您的assert语句之前,在第
行打印article.title2
上引发的。assertRaisesRegexp用法示例:此文档是我第一次检查)我试图更改为self.assertRaisesRegexp(article.AttributeError,“无属性存在”,article.atribute)。结果相同