如何在 python 中使用 postgresql 测试异常

how to test exception in python working with postgresql

我有自己的 class 文章 旨在与 PostgreSQL 一起工作。从 class 创建的每个对象都用于处理一行。现在我不知道如何测试异常情况。当我创建这样的案例时:

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*/

它应该会抛出错误。它确实) 测试用例应该是什么样的?我使用单元测试。我的测试 class 用我的错误方法无效如下:

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")

我没有如何创建测试用例的经验,也没有太多关于如何创建测试用例的好文档((( 因为我不明白如果测试用例通过(生成异常),unittest 应该 return Ok 语句。现在它只是显示错误。

如果您不向 assertRaisesRegexp() 提供可调用项(N.B。assertRaisesRegexp(),而不是 assertRaisesRegex()),则它充当上下文管理器。在这种情况下,您应该使用这样的 with 语句:

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