test_thread_polledit_api.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. from datetime import timedelta
  2. from django.urls import reverse
  3. from django.utils import timezone
  4. from misago.acl import add_acl
  5. from misago.core.utils import serialize_datetime
  6. from misago.threads.models import Poll
  7. from misago.threads.serializers.poll import MAX_POLL_OPTIONS
  8. from .test_thread_poll_api import ThreadPollApiTestCase
  9. class ThreadPollEditTests(ThreadPollApiTestCase):
  10. def setUp(self):
  11. super(ThreadPollEditTests, self).setUp()
  12. self.mock_poll()
  13. def test_anonymous(self):
  14. """api requires you to sign in to edit poll"""
  15. self.logout_user()
  16. response = self.put(self.api_link)
  17. self.assertEqual(response.status_code, 403)
  18. self.assertEqual(response.json(), {
  19. 'detail': "This action is not available to guests.",
  20. })
  21. def test_invalid_thread_id(self):
  22. """api validates that thread id is integer"""
  23. api_link = reverse(
  24. 'misago:api:thread-poll-detail',
  25. kwargs={
  26. 'thread_pk': 'kjha6dsa687sa',
  27. 'pk': self.poll.pk,
  28. }
  29. )
  30. response = self.put(api_link)
  31. self.assertEqual(response.status_code, 404)
  32. self.assertEqual(response.json(), {'detail': 'NOT FOUND'})
  33. def test_nonexistant_thread_id(self):
  34. """api validates that thread exists"""
  35. api_link = reverse(
  36. 'misago:api:thread-poll-detail',
  37. kwargs={
  38. 'thread_pk': self.thread.pk + 1,
  39. 'pk': self.poll.pk,
  40. }
  41. )
  42. response = self.put(api_link)
  43. self.assertEqual(response.status_code, 404)
  44. self.assertEqual(response.json(), {'detail': 'NOT FOUND'})
  45. def test_invalid_poll_id(self):
  46. """api validates that poll id is integer"""
  47. api_link = reverse(
  48. 'misago:api:thread-poll-detail',
  49. kwargs={
  50. 'thread_pk': self.thread.pk,
  51. 'pk': 'sad98as7d97sa98',
  52. }
  53. )
  54. response = self.put(api_link)
  55. self.assertEqual(response.status_code, 404)
  56. self.assertEqual(response.json(), {'detail': 'NOT FOUND'})
  57. def test_nonexistant_poll_id(self):
  58. """api validates that poll exists"""
  59. api_link = reverse(
  60. 'misago:api:thread-poll-detail',
  61. kwargs={
  62. 'thread_pk': self.thread.pk,
  63. 'pk': self.poll.pk + 123,
  64. }
  65. )
  66. response = self.put(api_link)
  67. self.assertEqual(response.status_code, 404)
  68. self.assertEqual(response.json(), {'detail': 'NOT FOUND'})
  69. def test_no_permission(self):
  70. """api validates that user has permission to edit poll in thread"""
  71. self.override_acl({'can_edit_polls': 0})
  72. response = self.put(self.api_link)
  73. self.assertEqual(response.status_code, 403)
  74. self.assertEqual(response.json(), {
  75. 'detail': "You can't edit polls.",
  76. })
  77. def test_no_permission_timeout(self):
  78. """api validates that user's window to edit poll in thread has closed"""
  79. self.override_acl({'can_edit_polls': 1, 'poll_edit_time': 5})
  80. self.poll.posted_on = timezone.now() - timedelta(minutes=15)
  81. self.poll.save()
  82. response = self.put(self.api_link)
  83. self.assertEqual(response.status_code, 403)
  84. self.assertEqual(response.json(), {
  85. 'detail': "You can't edit polls that are older than 5 minutes.",
  86. })
  87. def test_no_permission_poll_closed(self):
  88. """api validates that user's window to edit poll in thread has closed"""
  89. self.override_acl({'can_edit_polls': 1})
  90. self.poll.posted_on = timezone.now() - timedelta(days=15)
  91. self.poll.length = 5
  92. self.poll.save()
  93. response = self.put(self.api_link)
  94. self.assertEqual(response.status_code, 403)
  95. self.assertEqual(response.json(), {
  96. 'detail': "This poll is over. You can't edit it.",
  97. })
  98. def test_no_permission_other_user_poll(self):
  99. """api validates that user has permission to edit other user poll in thread"""
  100. self.override_acl({'can_edit_polls': 1})
  101. self.poll.poster = None
  102. self.poll.save()
  103. response = self.put(self.api_link)
  104. self.assertEqual(response.status_code, 403)
  105. self.assertEqual(response.json(), {
  106. 'detail': "You can't edit other users polls in this category.",
  107. })
  108. def test_no_permission_closed_thread(self):
  109. """api validates that user has permission to edit poll in closed thread"""
  110. self.override_acl(category={'can_close_threads': 0})
  111. self.thread.is_closed = True
  112. self.thread.save()
  113. response = self.put(self.api_link)
  114. self.assertEqual(response.status_code, 403)
  115. self.assertEqual(response.json(), {
  116. 'detail': "This thread is closed. You can't edit polls in it.",
  117. })
  118. self.override_acl(category={'can_close_threads': 1})
  119. response = self.put(self.api_link)
  120. self.assertEqual(response.status_code, 400)
  121. def test_no_permission_closed_category(self):
  122. """api validates that user has permission to edit poll in closed category"""
  123. self.override_acl(category={'can_close_threads': 0})
  124. self.category.is_closed = True
  125. self.category.save()
  126. response = self.put(self.api_link)
  127. self.assertEqual(response.status_code, 403)
  128. self.assertEqual(response.json(), {
  129. 'detail': "This category is closed. You can't edit polls in it.",
  130. })
  131. self.override_acl(category={'can_close_threads': 1})
  132. response = self.put(self.api_link)
  133. self.assertEqual(response.status_code, 400)
  134. def test_empty_data(self):
  135. """api handles empty request data"""
  136. response = self.put(self.api_link)
  137. self.assertEqual(response.status_code, 400)
  138. self.assertEqual(response.json(), {
  139. 'question': ["This field is required."],
  140. 'choices': ["This field is required."],
  141. 'length': ["This field is required."],
  142. 'allowed_choices': ["This field is required."],
  143. })
  144. def test_length_validation(self):
  145. """api validates poll's length"""
  146. response = self.put(
  147. self.api_link, data={
  148. 'length': -1,
  149. }
  150. )
  151. self.assertEqual(response.status_code, 400)
  152. self.assertEqual(response.json(), {
  153. 'question': ["This field is required."],
  154. 'choices': ["This field is required."],
  155. 'length': ["Ensure this value is greater than or equal to 0."],
  156. 'allowed_choices': ["This field is required."],
  157. })
  158. response = self.put(
  159. self.api_link, data={
  160. 'length': 200,
  161. }
  162. )
  163. self.assertEqual(response.status_code, 400)
  164. self.assertEqual(response.json(), {
  165. 'question': ["This field is required."],
  166. 'choices': ["This field is required."],
  167. 'length': ["Ensure this value is less than or equal to 180."],
  168. 'allowed_choices': ["This field is required."],
  169. })
  170. def test_question_validation(self):
  171. """api validates question length"""
  172. response = self.put(
  173. self.api_link, data={
  174. 'question': 'abcd' * 255,
  175. }
  176. )
  177. self.assertEqual(response.status_code, 400)
  178. self.assertEqual(response.json(), {
  179. 'question': ["Ensure this field has no more than 255 characters."],
  180. 'choices': ["This field is required."],
  181. 'length': ["This field is required."],
  182. 'allowed_choices': ["This field is required."],
  183. })
  184. def test_validate_choice_length(self):
  185. """api validates single choice length"""
  186. response = self.put(
  187. self.api_link, data={
  188. 'choices': [
  189. {
  190. 'hash': 'qwertyuiopas',
  191. 'label': '',
  192. },
  193. ],
  194. }
  195. )
  196. self.assertEqual(response.status_code, 400)
  197. self.assertEqual(response.json(), {
  198. 'question': ["This field is required."],
  199. 'choices': ["One or more poll choices are invalid."],
  200. 'length': ["This field is required."],
  201. 'allowed_choices': ["This field is required."],
  202. })
  203. response = self.put(
  204. self.api_link,
  205. data={
  206. 'choices': [
  207. {
  208. 'hash': 'qwertyuiopas',
  209. 'label': 'abcd' * 255,
  210. },
  211. ],
  212. }
  213. )
  214. self.assertEqual(response.status_code, 400)
  215. self.assertEqual(response.json(), {
  216. 'question': ["This field is required."],
  217. 'choices': ["One or more poll choices are invalid."],
  218. 'length': ["This field is required."],
  219. 'allowed_choices': ["This field is required."],
  220. })
  221. def test_validate_two_choices(self):
  222. """api validates that there are at least two choices in poll"""
  223. response = self.put(self.api_link, data={'choices': [{'label': 'Choice'}]})
  224. self.assertEqual(response.status_code, 400)
  225. self.assertEqual(response.json(), {
  226. 'question': ["This field is required."],
  227. 'choices': ["You need to add at least two choices to a poll."],
  228. 'length': ["This field is required."],
  229. 'allowed_choices': ["This field is required."],
  230. })
  231. def test_validate_max_choices(self):
  232. """api validates that there are no more choices in poll than allowed number"""
  233. response = self.put(
  234. self.api_link, data={
  235. 'choices': [
  236. {
  237. 'label': 'Choice',
  238. },
  239. ] * (MAX_POLL_OPTIONS + 1),
  240. }
  241. )
  242. self.assertEqual(response.status_code, 400)
  243. error_formats = (MAX_POLL_OPTIONS, MAX_POLL_OPTIONS + 1)
  244. self.assertEqual(response.json(), {
  245. 'question': ["This field is required."],
  246. 'choices': [
  247. "You can't add more than %s options to a single poll (added %s)." % error_formats
  248. ],
  249. 'length': ["This field is required."],
  250. 'allowed_choices': ["This field is required."],
  251. })
  252. def test_allowed_choices_validation(self):
  253. """api validates allowed choices number"""
  254. response = self.put(self.api_link, data={'allowed_choices': 0})
  255. self.assertEqual(response.status_code, 400)
  256. self.assertEqual(response.json(), {
  257. 'question': ["This field is required."],
  258. 'choices': ["This field is required."],
  259. 'length': ["This field is required."],
  260. 'allowed_choices': ["Ensure this value is greater than or equal to 1."],
  261. })
  262. response = self.put(
  263. self.api_link,
  264. data={
  265. 'length': 0,
  266. 'question': "Lorem ipsum",
  267. 'allowed_choices': 3,
  268. 'choices': [
  269. {
  270. 'label': 'Choice',
  271. },
  272. {
  273. 'label': 'Choice',
  274. },
  275. ],
  276. }
  277. )
  278. self.assertEqual(response.status_code, 400)
  279. self.assertEqual(response.json(), {
  280. 'non_field_errors': [
  281. "Number of allowed choices can't be greater than number of all choices."
  282. ],
  283. })
  284. def test_poll_all_choices_replaced(self):
  285. """api edits all poll choices out"""
  286. response = self.put(
  287. self.api_link,
  288. data={
  289. 'length': 40,
  290. 'question': "Select two best colors",
  291. 'allowed_choices': 2,
  292. 'allow_revotes': True,
  293. 'is_public': True,
  294. 'choices': [
  295. {
  296. 'label': '\nRed ',
  297. },
  298. {
  299. 'label': 'Green',
  300. },
  301. {
  302. 'label': 'Blue',
  303. },
  304. ],
  305. }
  306. )
  307. self.assertEqual(response.status_code, 200)
  308. poll = Poll.objects.all()[0]
  309. add_acl(self.user, poll)
  310. response_json = response.json()
  311. self.assertEqual(response_json['poster_name'], self.user.username)
  312. self.assertEqual(response_json['length'], 40)
  313. self.assertEqual(response_json['question'], "Select two best colors")
  314. self.assertEqual(response_json['allowed_choices'], 2)
  315. self.assertTrue(response_json['allow_revotes'])
  316. # you can't change poll's type after its posted
  317. self.assertFalse(response_json['is_public'])
  318. # choices were updated
  319. self.assertEqual(len(response_json['choices']), 3)
  320. self.assertEqual(len(set([c['hash'] for c in response_json['choices']])), 3)
  321. self.assertEqual([c['label'] for c in response_json['choices']], ['Red', 'Green', 'Blue'])
  322. self.assertEqual([c['votes'] for c in response_json['choices']], [0, 0, 0])
  323. self.assertEqual([c['selected'] for c in response_json['choices']], [False, False, False])
  324. # votes were removed
  325. self.assertEqual(response_json['votes'], 0)
  326. self.assertEqual(self.poll.pollvote_set.count(), 0)
  327. def test_poll_current_choices_edited(self):
  328. """api edits current poll choices"""
  329. response = self.put(
  330. self.api_link,
  331. data={
  332. 'length': 40,
  333. 'question': "Select two best colors",
  334. 'allowed_choices': 2,
  335. 'allow_revotes': True,
  336. 'is_public': True,
  337. 'choices': [
  338. {
  339. 'hash': 'aaaaaaaaaaaa',
  340. 'label': '\nFirst ',
  341. 'votes': 5555,
  342. },
  343. {
  344. 'hash': 'bbbbbbbbbbbb',
  345. 'label': 'Second',
  346. 'votes': 5555,
  347. },
  348. {
  349. 'hash': 'gggggggggggg',
  350. 'label': 'Third',
  351. 'votes': 5555,
  352. },
  353. {
  354. 'hash': 'dddddddddddd',
  355. 'label': 'Fourth',
  356. 'votes': 5555,
  357. },
  358. ],
  359. }
  360. )
  361. self.assertEqual(response.status_code, 200)
  362. poll = Poll.objects.all()[0]
  363. add_acl(self.user, poll)
  364. self.assertEqual(response.json(), {
  365. 'id': poll.id,
  366. 'poster_name': self.user.username,
  367. 'posted_on': serialize_datetime(poll.posted_on),
  368. 'length': 40,
  369. 'question': "Select two best colors",
  370. 'allowed_choices': 2,
  371. 'allow_revotes': True,
  372. 'votes': 4,
  373. 'is_public': False,
  374. 'acl': poll.acl,
  375. 'choices': [
  376. {
  377. 'hash': 'aaaaaaaaaaaa',
  378. 'label': 'First',
  379. 'votes': 1,
  380. 'selected': False,
  381. },
  382. {
  383. 'hash': 'bbbbbbbbbbbb',
  384. 'label': 'Second',
  385. 'votes': 0,
  386. 'selected': False,
  387. },
  388. {
  389. 'hash': 'gggggggggggg',
  390. 'label': 'Third',
  391. 'votes': 2,
  392. 'selected': True,
  393. },
  394. {
  395. 'hash': 'dddddddddddd',
  396. 'label': 'Fourth',
  397. 'votes': 1,
  398. 'selected': True,
  399. },
  400. ],
  401. 'api': {
  402. 'index': poll.get_api_url(),
  403. 'votes': poll.get_votes_api_url(),
  404. },
  405. 'url': {
  406. 'poster': self.user.get_absolute_url(),
  407. },
  408. })
  409. # no votes were removed
  410. self.assertEqual(self.poll.pollvote_set.count(), 4)
  411. def test_poll_some_choices_edited(self):
  412. """api edits some poll choices"""
  413. response = self.put(
  414. self.api_link,
  415. data={
  416. 'length': 40,
  417. 'question': "Select two best colors",
  418. 'allowed_choices': 2,
  419. 'allow_revotes': True,
  420. 'is_public': True,
  421. 'choices': [
  422. {
  423. 'hash': 'aaaaaaaaaaaa',
  424. 'label': '\nFirst ',
  425. 'votes': 5555,
  426. },
  427. {
  428. 'hash': 'bbbbbbbbbbbb',
  429. 'label': 'Second',
  430. 'votes': 5555,
  431. },
  432. {
  433. 'hash': 'dsadsadsa788',
  434. 'label': 'New Option',
  435. 'votes': 5555,
  436. },
  437. ],
  438. }
  439. )
  440. self.assertEqual(response.status_code, 200)
  441. poll = Poll.objects.all()[0]
  442. add_acl(self.user, poll)
  443. self.assertEqual(response.json(), {
  444. 'id': poll.id,
  445. 'poster_name': self.user.username,
  446. 'posted_on': serialize_datetime(poll.posted_on),
  447. 'length': 40,
  448. 'question': "Select two best colors",
  449. 'allowed_choices': 2,
  450. 'allow_revotes': True,
  451. 'votes': 1,
  452. 'is_public': False,
  453. 'acl': poll.acl,
  454. 'choices': [
  455. {
  456. 'hash': 'aaaaaaaaaaaa',
  457. 'label': 'First',
  458. 'votes': 1,
  459. 'selected': False,
  460. },
  461. {
  462. 'hash': 'bbbbbbbbbbbb',
  463. 'label': 'Second',
  464. 'votes': 0,
  465. 'selected': False,
  466. },
  467. {
  468. 'hash': poll.choices[2]['hash'],
  469. 'label': 'New Option',
  470. 'votes': 0,
  471. 'selected': False,
  472. },
  473. ],
  474. 'api': {
  475. 'index': poll.get_api_url(),
  476. 'votes': poll.get_votes_api_url(),
  477. },
  478. 'url': {
  479. 'poster': self.user.get_absolute_url(),
  480. },
  481. })
  482. # no votes were removed
  483. self.assertEqual(self.poll.pollvote_set.count(), 1)
  484. def test_moderate_user_poll(self):
  485. """api edits all poll choices out in other users poll, even if its over"""
  486. self.override_acl({'can_edit_polls': 2, 'poll_edit_time': 5})
  487. self.poll.poster = None
  488. self.poll.posted_on = timezone.now() - timedelta(days=15)
  489. self.poll.length = 5
  490. self.poll.save()
  491. response = self.put(
  492. self.api_link,
  493. data={
  494. 'length': 40,
  495. 'question': "Select two best colors",
  496. 'allowed_choices': 2,
  497. 'allow_revotes': True,
  498. 'is_public': True,
  499. 'choices': [
  500. {
  501. 'label': '\nRed ',
  502. },
  503. {
  504. 'label': 'Green',
  505. },
  506. {
  507. 'label': 'Blue',
  508. },
  509. ],
  510. }
  511. )
  512. self.assertEqual(response.status_code, 200)
  513. poll = Poll.objects.all()[0]
  514. add_acl(self.user, poll)
  515. expected_choices = []
  516. for choice in poll.choices:
  517. self.assertIn(choice['label'], ["Red", "Green", "Blue"])
  518. expected_choices.append(choice.copy())
  519. expected_choices[-1]['selected'] = False
  520. self.assertEqual(response.json(), {
  521. 'id': poll.id,
  522. 'poster_name': self.user.username,
  523. 'posted_on': serialize_datetime(poll.posted_on),
  524. 'length': 40,
  525. 'question': "Select two best colors",
  526. 'allowed_choices': 2,
  527. 'allow_revotes': True,
  528. 'votes': 0,
  529. 'is_public': False,
  530. 'acl': poll.acl,
  531. 'choices': expected_choices,
  532. 'api': {
  533. 'index': poll.get_api_url(),
  534. 'votes': poll.get_votes_api_url(),
  535. },
  536. 'url': {
  537. 'poster': None,
  538. },
  539. })
  540. # votes were removed
  541. self.assertEqual(self.poll.pollvote_set.count(), 0)