tests.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from django.test import TestCase
  2. from django.core.exceptions import FieldError
  3. from models import Author, Article
  4. def pks(objects):
  5. """ Return pks to be able to compare lists"""
  6. return [o.pk for o in objects]
  7. class CustomColumnRegression(TestCase):
  8. def assertRaisesMessage(self, exc, msg, func, *args, **kwargs):
  9. try:
  10. func(*args, **kwargs)
  11. except Exception, e:
  12. self.assertEqual(msg, str(e))
  13. self.assertTrue(isinstance(e, exc), "Expected %s, got %s" % (exc, type(e)))
  14. def setUp(self):
  15. self.a1 = Author.objects.create(first_name='John', last_name='Smith')
  16. self.a2 = Author.objects.create(first_name='Peter', last_name='Jones')
  17. self.authors = [self.a1, self.a2]
  18. def test_basic_creation(self):
  19. art = Article(headline='Django lets you build Web apps easily', primary_author=self.a1)
  20. art.save()
  21. art.authors = [self.a1, self.a2]
  22. def test_author_querying(self):
  23. self.assertQuerysetEqual(
  24. Author.objects.all().order_by('last_name'),
  25. ['<Author: Peter Jones>', '<Author: John Smith>']
  26. )
  27. def test_author_filtering(self):
  28. self.assertQuerysetEqual(
  29. Author.objects.filter(first_name__exact='John'),
  30. ['<Author: John Smith>']
  31. )
  32. def test_author_get(self):
  33. self.assertEqual(self.a1, Author.objects.get(first_name__exact='John'))
  34. def test_filter_on_nonexistant_field(self):
  35. self.assertRaisesMessage(
  36. FieldError,
  37. "Cannot resolve keyword 'firstname' into field. Choices are: Author_ID, article, first_name, last_name, primary_set",
  38. Author.objects.filter,
  39. firstname__exact='John'
  40. )
  41. def test_author_get_attributes(self):
  42. a = Author.objects.get(last_name__exact='Smith')
  43. self.assertEqual('John', a.first_name)
  44. self.assertEqual('Smith', a.last_name)
  45. self.assertRaisesMessage(
  46. AttributeError,
  47. "'Author' object has no attribute 'firstname'",
  48. getattr,
  49. a, 'firstname'
  50. )
  51. self.assertRaisesMessage(
  52. AttributeError,
  53. "'Author' object has no attribute 'last'",
  54. getattr,
  55. a, 'last'
  56. )
  57. def test_m2m_table(self):
  58. art = Article.objects.create(headline='Django lets you build Web apps easily', primary_author=self.a1)
  59. art.authors = self.authors
  60. self.assertQuerysetEqual(
  61. art.authors.all().order_by('last_name'),
  62. ['<Author: Peter Jones>', '<Author: John Smith>']
  63. )
  64. self.assertQuerysetEqual(
  65. self.a1.article_set.all(),
  66. ['<Article: Django lets you build Web apps easily>']
  67. )
  68. self.assertQuerysetEqual(
  69. art.authors.filter(last_name='Jones'),
  70. ['<Author: Peter Jones>']
  71. )