Reputation: 1178
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.
Upvotes: 0
Views: 441
Reputation: 87124
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
Upvotes: 2