PageRenderTime 60ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/jabber_main/generic/tests.py

https://bitbucket.org/bacher09/jabber_vn
Python | 388 lines | 379 code | 7 blank | 2 comment | 0 complexity | 043390b3f6cdabfa855a77faf4d98e7b MD5 | raw file
Possible License(s): BSD-2-Clause
  1. """
  2. This file demonstrates writing tests using the unittest module. These will pass
  3. when you run "manage.py test".
  4. Replace this with more appropriate tests for your application.
  5. """
  6. from django.test import TestCase
  7. from django.db import models
  8. from django.test.client import RequestFactory
  9. from django.template import Template, Context, TemplateSyntaxError
  10. from django.http import Http404
  11. from django.conf.urls import url, patterns
  12. from django.http import HttpResponse
  13. from django.core.urlresolvers import reverse
  14. from operator import attrgetter
  15. from . import views
  16. from .templatetags import active_link, paginator
  17. import re
  18. import datetime
  19. def test_view(request, *args, **kwargs):
  20. return HttpResponse('')
  21. urlpatterns = patterns('',
  22. url(r'^test/$', test_view, name = 'test'),
  23. url(r'^test2/(?P<extra>extra)(?P<args>args)$', test_view, name = 'test2'),
  24. )
  25. class Tag(models.Model):
  26. name = models.CharField(unique = True, max_length = 40)
  27. def __unicode__(self):
  28. return self.name
  29. class Messages(models.Model):
  30. title = models.CharField(max_length = 120)
  31. text = models.TextField()
  32. published = models.BooleanField(default = False)
  33. created_datetime = models.DateTimeField(auto_now_add = True)
  34. updated_datetime = models.DateTimeField(auto_now = True)
  35. tags = models.ManyToManyField(Tag, blank = True)
  36. def __unicode__(self):
  37. return self.title
  38. class TestingViewMixin(object):
  39. def init_test_args(self, request, *args, **kwargs):
  40. self.request = request
  41. self.args = args
  42. self.kwargs = kwargs
  43. def get_queryset(self):
  44. return self.queryset
  45. def get_context_data(self, **kwargs):
  46. dct = kwargs.copy()
  47. return dct
  48. class MessagesFilter(views.MultipleFilterListViewMixin, TestingViewMixin):
  49. queryset = Messages.objects.all()
  50. m2m_filter = set(['tags'])
  51. allowed_many = {'tags': 3 }
  52. boolean_filters = ('published',)
  53. allowed_filter = { 'title':'title',
  54. 'published' : 'published',
  55. 'tags' : 'tags__name' }
  56. allowed_order = { 'create': 'created_datetime',
  57. 'update': 'updated_datetime',
  58. None : 'created_datetime' }
  59. def init_test(self, request):
  60. url_re = re.compile(r'^%s$' % self.get_url_part())
  61. m = url_re.match(request.path[1:])
  62. if m is None:
  63. raise Http404('Bad url')
  64. kwargs = m.groupdict()
  65. self.init_test_args(request, **kwargs)
  66. def __init__(self, request):
  67. self.init_test(request)
  68. class SimpleTest(TestCase):
  69. def setUp(self):
  70. self.factory = RequestFactory()
  71. tags = []
  72. for tag in ['one', 'two', 'three', 'four', 'five', 'six', 'seven']:
  73. tag_obj = Tag.objects.create(name = tag)
  74. tags.append(tag_obj)
  75. m_obj = Messages.objects.create(title = 'First message',
  76. text = 'Message',
  77. published = True)
  78. m_obj.tags.add(*tags[:2])
  79. m_obj = Messages.objects.create(title = 'Second message',
  80. text = 'Message',
  81. published = False)
  82. m_obj.tags.add(*tags[2:4])
  83. mu_obj = Messages.objects.create(title = 'Update',
  84. text = 'Message',
  85. published = False)
  86. mu_obj.tags.add(*tags[4:])
  87. m_obj = Messages.objects.create(title = 'New',
  88. text = 'Message',
  89. published = True)
  90. m_obj.tags.add(tags[0], tags[6])
  91. m_obj = Messages.objects.create(title = 'title',
  92. text = 'Message',
  93. published = False)
  94. m_obj.tags.add(tags[3], tags[5])
  95. m_obj = Messages.objects.create(title = 'message',
  96. text = 'Message',
  97. published = True)
  98. m_obj.tags.add(tags[6])
  99. m_obj = Messages.objects.create(title = 'cats',
  100. text = 'Message',
  101. published = True)
  102. m_obj.tags.add(tags[5])
  103. m_obj = Messages.objects.create(title = 'dogs',
  104. text = 'Message',
  105. published = False)
  106. m_obj.tags.add(tags[5])
  107. # For changed updated_datetime
  108. nd = datetime.datetime.now() + datetime.timedelta(0, 5)
  109. Messages.objects.filter(pk = mu_obj.pk). \
  110. update(text = 'Updated', updated_datetime = nd)
  111. def test_basic_addition(self):
  112. self.assertEqual(1 + 1, 2)
  113. def test_filtering_view_url(self):
  114. url = MessagesFilter.get_url_part()
  115. self.assertEqual(url, '(?:published/(?P<published>yes|no)/)?' \
  116. '(?:tags/(?P<tags>[^/]+)/)?' \
  117. '(?:title/(?P<title>[^/]+)/)?' \
  118. '(?:order/(?P<order>[a-z]*)/)?(?P<rev>rev/)?')
  119. def test_filtering_view_query_boolean(self):
  120. active = [
  121. "First message",
  122. "New",
  123. "message",
  124. "cats"
  125. ]
  126. inactive = [
  127. "Second message",
  128. "Update",
  129. "title",
  130. "dogs"
  131. ]
  132. request = self.factory.get('/published/yes/')
  133. self.assertQuerysetEqual(
  134. MessagesFilter(request).get_queryset(),
  135. active,
  136. attrgetter("title")
  137. )
  138. request = self.factory.get('/published/no/')
  139. self.assertQuerysetEqual(
  140. MessagesFilter(request).get_queryset(),
  141. inactive,
  142. attrgetter("title")
  143. )
  144. request = self.factory.get('/?published=yes')
  145. self.assertQuerysetEqual(
  146. MessagesFilter(request).get_queryset(),
  147. active,
  148. attrgetter("title")
  149. )
  150. request = self.factory.get('/?published=no')
  151. self.assertQuerysetEqual(
  152. MessagesFilter(request).get_queryset(),
  153. inactive,
  154. attrgetter("title")
  155. )
  156. def test_filtering_view_query_ordering(self):
  157. request = self.factory.get('/order/update/rev/')
  158. first = MessagesFilter(request).get_queryset()[0]
  159. self.assertEqual(first.title, "Update")
  160. request = self.factory.get('/order/test/')
  161. with self.assertRaises(Http404):
  162. MessagesFilter(request).get_queryset()
  163. request = self.factory.get('/order/newtest/rev/')
  164. with self.assertRaises(Http404):
  165. MessagesFilter(request).get_queryset()
  166. request = self.factory.get('/?order=update&rev=1')
  167. first = MessagesFilter(request).get_queryset()[0]
  168. self.assertEqual(first.title, "Update")
  169. request = self.factory.get('/?order=test')
  170. with self.assertRaises(Http404):
  171. MessagesFilter(request).get_queryset()
  172. request = self.factory.get('/?order=newtest&rev=1')
  173. with self.assertRaises(Http404):
  174. MessagesFilter(request).get_queryset()
  175. def test_filtering_view_query_search(self):
  176. def title_test(title):
  177. request = self.factory.get('/title/%s/' % title)
  178. obj = MessagesFilter(request).get_queryset()[0]
  179. self.assertEqual(obj.title, title)
  180. title_test("title")
  181. title_test("cats")
  182. title_test("dogs")
  183. title_test("New")
  184. def title_test2(title):
  185. request = self.factory.get('/?title=%s' % title)
  186. obj = MessagesFilter(request).get_queryset()[0]
  187. self.assertEqual(obj.title, title)
  188. title_test2("First message")
  189. title_test2("Second message")
  190. request = self.factory.get('/title/empty/')
  191. self.assertEqual(len(MessagesFilter(request).get_queryset()), 0)
  192. def test_filtering_view_query_m2m_search(self):
  193. first_tag = [
  194. "First message",
  195. "New",
  196. ]
  197. last_tag = [
  198. "Update",
  199. "message"
  200. ]
  201. four_tag = [
  202. "Second message",
  203. "title"
  204. ]
  205. six_tag = [
  206. "Update",
  207. "title",
  208. "cats",
  209. "dogs"
  210. ]
  211. first_last_tag = first_tag + last_tag
  212. four_six_tag = list(set(six_tag + four_tag))
  213. first_four_last = list(set(first_last_tag + four_tag))
  214. def test_m2m_tags(link, args_cmp):
  215. request = self.factory.get(link)
  216. self.assertQuerysetEqual(
  217. MessagesFilter(request).get_queryset(),
  218. args_cmp,
  219. attrgetter("title"),
  220. ordered = False
  221. )
  222. test_m2m_tags('/tags/one/', first_tag)
  223. test_m2m_tags('/?tags=one', first_tag)
  224. test_m2m_tags('/tags/one,seven/', first_last_tag)
  225. test_m2m_tags('/?tags=one,seven', first_last_tag)
  226. test_m2m_tags('/tags/four,six/', four_six_tag)
  227. test_m2m_tags('/?tags=four,six', four_six_tag)
  228. test_m2m_tags('/tags/one,four,seven/', first_four_last)
  229. test_m2m_tags('/?tags=one,four,seven', first_four_last)
  230. # last tag should be rejected due the limit in allowed_many
  231. test_m2m_tags('/tags/one,four,seven,six/', first_four_last)
  232. test_m2m_tags('/?tags=one,four,seven,six', first_four_last)
  233. def test_filtering_view_query_complex(self):
  234. def test_complex(link, args_cmp):
  235. request = self.factory.get(link)
  236. self.assertQuerysetEqual(
  237. MessagesFilter(request).get_queryset(),
  238. args_cmp,
  239. attrgetter("title"),
  240. ordered = False
  241. )
  242. test_complex('/published/yes/tags/six/', ["cats"])
  243. test_complex('/?published=yes&tags=six', ["cats"])
  244. test_complex('/published/yes/tags/seven/title/message/', ["message"])
  245. test_complex('/?published=yes&tags=seven&title=message', ["message"])
  246. class TemplateTagsTest(TestCase):
  247. urls = "generic.tests"
  248. def setUp(self):
  249. self.factory = RequestFactory()
  250. def test_basic_addition(self):
  251. self.assertEqual(1 + 1, 2)
  252. def test_settings(self):
  253. url = reverse('test')
  254. self.assertEqual(url, '/test/')
  255. def test_templatetag_fun1(self):
  256. request = self.factory.get('/test/')
  257. self.assertEqual(
  258. active_link.active_str({'request': request}, '/test/'),
  259. "active"
  260. )
  261. request = self.factory.get('/test/?query=val')
  262. self.assertEqual(
  263. active_link.active_str({'request': request}, '/test/'),
  264. "active"
  265. )
  266. request = self.factory.get('/test2/')
  267. self.assertEqual(
  268. active_link.active_str({'request': request}, '/test/'),
  269. ""
  270. )
  271. request = self.factory.get('/test/')
  272. self.assertEqual(
  273. active_link.active_str({'request': request}, '/test'),
  274. ""
  275. )
  276. def test_templatetag_fun2(self):
  277. fun2 = active_link.active_link
  278. request = self.factory.get('/test/')
  279. self.assertEqual(
  280. fun2({'request': request}, 'test', 'text'),
  281. '<li class="active"><a href="/test/">text</a><li>'
  282. )
  283. request = self.factory.get('/another_test/')
  284. self.assertEqual(
  285. fun2({'request': request}, 'test', 'text'),
  286. '<li><a href="/test/">text</a><li>'
  287. )
  288. request = self.factory.get('/another_test/')
  289. self.assertEqual(
  290. fun2({'request': request}, 'bad_test', 'text'),
  291. '<li><a href="#">text</a><li>'
  292. )
  293. request = self.factory.get('/test/')
  294. self.assertEqual(
  295. fun2({'request': request}, 'test', 'text', id = 'test_id'),
  296. '<li class="active"><a href="/test/" id="test_id">text</a><li>'
  297. )
  298. request = self.factory.get('/test2/extraargs')
  299. self.assertEqual(
  300. fun2({'request': request}, 'test2', 'text',
  301. id = 'test_id', extra = 'extra', args = 'args'),
  302. '<li class="active"><a href="/test2/extraargs" '\
  303. 'id="test_id">text</a><li>'
  304. )
  305. def test_templatetag_active_str(self):
  306. request = self.factory.get('/test/')
  307. out = Template(
  308. "{% load active_link %}"
  309. "{% active_str '/test/' %}"
  310. ).render(Context({'request': request}))
  311. self.assertEqual(out, "active")
  312. request = self.factory.get('/test/?query=val')
  313. out = Template(
  314. "{% load active_link %}"
  315. "{% active_str '/test/' %}"
  316. ).render(Context({'request': request}))
  317. self.assertEqual(out, "active")
  318. request = self.factory.get('/test2/')
  319. out = Template(
  320. "{% load active_link %}"
  321. "{% active_str '/test/' %}"
  322. ).render(Context({'request': request}))
  323. self.assertEqual(out, "")