PageRenderTime 4ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/modeltests/order_with_respect_to/tests.py

https://code.google.com/p/mango-py/
Python | 71 lines | 51 code | 12 blank | 8 comment | 2 complexity | a43b51a9bd40afab018fd350d180f0e7 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from operator import attrgetter
  2. from django.test import TestCase
  3. from models import Post, Question, Answer
  4. class OrderWithRespectToTests(TestCase):
  5. def test_basic(self):
  6. q1 = Question.objects.create(text="Which Beatle starts with the letter 'R'?")
  7. q2 = Question.objects.create(text="What is your name?")
  8. Answer.objects.create(text="John", question=q1)
  9. Answer.objects.create(text="Jonno", question=q2)
  10. Answer.objects.create(text="Paul", question=q1)
  11. Answer.objects.create(text="Paulo", question=q2)
  12. Answer.objects.create(text="George", question=q1)
  13. Answer.objects.create(text="Ringo", question=q1)
  14. # The answers will always be ordered in the order they were inserted.
  15. self.assertQuerysetEqual(
  16. q1.answer_set.all(), [
  17. "John", "Paul", "George", "Ringo",
  18. ],
  19. attrgetter("text"),
  20. )
  21. # We can retrieve the answers related to a particular object, in the
  22. # order they were created, once we have a particular object.
  23. a1 = Answer.objects.filter(question=q1)[0]
  24. self.assertEqual(a1.text, "John")
  25. a2 = a1.get_next_in_order()
  26. self.assertEqual(a2.text, "Paul")
  27. a4 = list(Answer.objects.filter(question=q1))[-1]
  28. self.assertEqual(a4.text, "Ringo")
  29. self.assertEqual(a4.get_previous_in_order().text, "George")
  30. # Determining (and setting) the ordering for a particular item is also
  31. # possible.
  32. id_list = [o.pk for o in q1.answer_set.all()]
  33. self.assertEqual(a2.question.get_answer_order(), id_list)
  34. a5 = Answer.objects.create(text="Number five", question=q1)
  35. # It doesn't matter which answer we use to check the order, it will
  36. # always be the same.
  37. self.assertEqual(
  38. a2.question.get_answer_order(), a5.question.get_answer_order()
  39. )
  40. # The ordering can be altered:
  41. id_list = [o.pk for o in q1.answer_set.all()]
  42. x = id_list.pop()
  43. id_list.insert(-1, x)
  44. self.assertNotEqual(a5.question.get_answer_order(), id_list)
  45. a5.question.set_answer_order(id_list)
  46. self.assertQuerysetEqual(
  47. q1.answer_set.all(), [
  48. "John", "Paul", "George", "Number five", "Ringo"
  49. ],
  50. attrgetter("text")
  51. )
  52. def test_recursive_ordering(self):
  53. p1 = Post.objects.create(title='1')
  54. p2 = Post.objects.create(title='2')
  55. p1_1 = Post.objects.create(title="1.1", parent=p1)
  56. p1_2 = Post.objects.create(title="1.2", parent=p1)
  57. p2_1 = Post.objects.create(title="2.1", parent=p2)
  58. p1_3 = Post.objects.create(title="1.3", parent=p1)
  59. self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])