【问题标题】:how to test exception in python working with postgresql如何在 python 中使用 postgresql 测试异常
【发布时间】:2015-03-20 13:18:56
【问题描述】:

我有自己的类 Article 旨在与 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*/

它应该抛出错误。它确实) 测试用例应该是什么样子?我使用单元测试。我的测试类使用了我的错误方法但不起作用:

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 应该返回 Ok 语句。现在它只是显示错误。

【问题讨论】:

  • 它显示错误,因为它是在您的断言语句之前引发的,在print article.title2 行。 assertRaisesRegexp 用法示例:docs.python.org/2/library/…
  • 这个文档是我检查的第一个文档)我尝试更改为 self.assertRaisesRegexp(article.AttributeError, "No attribute exists", article.atribute)。同样的结果

标签: python postgresql unit-testing exception


【解决方案1】:

如果您不向assertRaisesRegexp() 提供可调用对象(注意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,否则我认为您实际上不需要为此使用正则表达式。只需检查 article.AttributeErrorassertRaises()。这应该足够了:

with self.assertRaisesRegexp(article.AttributeError):
    article = Article(2)
    print article.title2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多