0

I have my own class Article designed to wrok with PostgreSQL. Each object created from the class is used to work with one row. Now I dont know how to test exception case. When I create such case:

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

it should throw error. And it does) How should test case looks like? I use unittest. My test class with my wrong method which does not work is below:

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

I have no expirience how to create test cases and no much good documentation of how to do it((( As I undestood if testcase is passed (exception is generated), unittest should return Ok statement. Now it just shows error.

2
  • It shows error, because it's raised before your assert statement, on line print article.title2. Example of assertRaisesRegexp usage: docs.python.org/2/library/… Commented Mar 20, 2015 at 13:41
  • This doc was the first I checked) I tried to change to self.assertRaisesRegexp(article.AttributeError, "No attribute exists", article.atribute). The same result Commented Mar 20, 2015 at 14:00

1 Answer 1

2

If you do not supply a callable to assertRaisesRegexp() (N.B. assertRaisesRegexp(), not assertRaisesRegex()), then it acts as a context manager. In that case you should use a with statement like this:

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

Unless your code can raise article.AttributeError with different string representations, I don't think that you actually need to use a regex for this. Just check for article.AttributeError with assertRaises(). This should suffice:

with self.assertRaisesRegexp(article.AttributeError):
    article = Article(2)
    print article.title2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.