1
0

test_pagure_flask_api_user.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818
  1. # -*- coding: utf-8 -*-
  2. """
  3. (c) 2015-2018 - Copyright Red Hat Inc
  4. Authors:
  5. Pierre-Yves Chibon <pingou@pingoured.fr>
  6. """
  7. from __future__ import unicode_literals, absolute_import
  8. import datetime
  9. import os
  10. import pytz
  11. import shutil
  12. import sys
  13. import unittest
  14. import json
  15. from mock import patch
  16. sys.path.insert(
  17. 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
  18. )
  19. import pagure.api
  20. import pagure.config
  21. import pagure.lib.model as model
  22. import pagure.lib.query
  23. import tests
  24. class PagureFlaskApiUSertests(tests.Modeltests):
  25. """ Tests for the flask API of pagure for issue """
  26. maxDiff = None
  27. def setUp(self):
  28. """ Set up the environnment, ran before every tests. """
  29. super(PagureFlaskApiUSertests, self).setUp()
  30. pagure.config.config["REQUESTS_FOLDER"] = None
  31. def test_api_users(self):
  32. """ Test the api_users function. """
  33. output = self.app.get("/api/0/users")
  34. self.assertEqual(output.status_code, 200)
  35. data = json.loads(output.get_data(as_text=True))
  36. self.assertEqual(sorted(data["users"]), ["foo", "pingou"])
  37. self.assertEqual(
  38. sorted(data.keys()), ["mention", "total_users", "users"]
  39. )
  40. self.assertEqual(data["total_users"], 2)
  41. output = self.app.get("/api/0/users?pattern=p")
  42. self.assertEqual(output.status_code, 200)
  43. data = json.loads(output.get_data(as_text=True))
  44. self.assertEqual(data["users"], ["pingou"])
  45. self.assertEqual(
  46. sorted(data.keys()), ["mention", "total_users", "users"]
  47. )
  48. self.assertEqual(data["total_users"], 1)
  49. def test_api_view_user(self):
  50. """
  51. Test the api_view_user method of the flask api
  52. The tested user has no project or forks.
  53. """
  54. output = self.app.get("/api/0/user/pingou")
  55. self.assertEqual(output.status_code, 200)
  56. exp = {
  57. "forks": [],
  58. "forks_pagination": {
  59. "first": "http://localhost...",
  60. "last": "http://localhost...",
  61. "next": None,
  62. "forkpage": 1,
  63. "pages": 0,
  64. "per_page": 20,
  65. "prev": None,
  66. },
  67. "repos": [],
  68. "repos_pagination": {
  69. "first": "http://localhost...",
  70. "last": "http://localhost...",
  71. "next": None,
  72. "repopage": 1,
  73. "pages": 0,
  74. "per_page": 20,
  75. "prev": None,
  76. },
  77. "user": {
  78. "fullname": "PY C",
  79. "name": "pingou",
  80. "avatar_url": "https://seccdn.libravatar.org/avatar/...",
  81. },
  82. }
  83. data = json.loads(output.get_data(as_text=True))
  84. data["user"]["avatar_url"] = "https://seccdn.libravatar.org/avatar/..."
  85. for k in ["forks_pagination", "repos_pagination"]:
  86. for k2 in ["first", "last"]:
  87. self.assertIsNotNone(data[k][k2])
  88. data[k][k2] = "http://localhost..."
  89. self.assertEqual(data, exp)
  90. def test_api_view_user_with_project(self):
  91. """
  92. Test the api_view_user method of the flask api,
  93. this time the user has some project defined.
  94. """
  95. tests.create_projects(self.session)
  96. output = self.app.get("/api/0/user/pingou")
  97. self.assertEqual(output.status_code, 200)
  98. data = json.loads(output.get_data(as_text=True))
  99. data["repos"][0]["date_created"] = "1490272832"
  100. data["repos"][0]["date_modified"] = "1490272832"
  101. data["repos"][1]["date_created"] = "1490272832"
  102. data["repos"][1]["date_modified"] = "1490272832"
  103. data["repos"][2]["date_created"] = "1490272832"
  104. data["repos"][2]["date_modified"] = "1490272832"
  105. for k in ["forks_pagination", "repos_pagination"]:
  106. for k2 in ["first", "last"]:
  107. self.assertIsNotNone(data[k][k2])
  108. data[k][k2] = "http://localhost..."
  109. expected_data = {
  110. "forks": [],
  111. "forks_pagination": {
  112. "first": "http://localhost...",
  113. "last": "http://localhost...",
  114. "next": None,
  115. "forkpage": 1,
  116. "pages": 0,
  117. "per_page": 20,
  118. "prev": None,
  119. },
  120. "repos": [
  121. {
  122. "access_groups": {"admin": [], "commit": [], "ticket": []},
  123. "access_users": {
  124. "admin": [],
  125. "commit": [],
  126. "owner": ["pingou"],
  127. "ticket": [],
  128. },
  129. "close_status": [
  130. "Invalid",
  131. "Insufficient data",
  132. "Fixed",
  133. "Duplicate",
  134. ],
  135. "custom_keys": [],
  136. "date_created": "1490272832",
  137. "date_modified": "1490272832",
  138. "description": "test project #1",
  139. "fullname": "test",
  140. "url_path": "test",
  141. "id": 1,
  142. "milestones": {},
  143. "name": "test",
  144. "namespace": None,
  145. "parent": None,
  146. "priorities": {},
  147. "tags": [],
  148. "user": {"fullname": "PY C", "name": "pingou"},
  149. },
  150. {
  151. "access_groups": {"admin": [], "commit": [], "ticket": []},
  152. "access_users": {
  153. "admin": [],
  154. "commit": [],
  155. "owner": ["pingou"],
  156. "ticket": [],
  157. },
  158. "close_status": [
  159. "Invalid",
  160. "Insufficient data",
  161. "Fixed",
  162. "Duplicate",
  163. ],
  164. "custom_keys": [],
  165. "date_created": "1490272832",
  166. "date_modified": "1490272832",
  167. "description": "test project #2",
  168. "fullname": "test2",
  169. "url_path": "test2",
  170. "id": 2,
  171. "milestones": {},
  172. "name": "test2",
  173. "namespace": None,
  174. "parent": None,
  175. "priorities": {},
  176. "tags": [],
  177. "user": {"fullname": "PY C", "name": "pingou"},
  178. },
  179. {
  180. "access_groups": {"admin": [], "commit": [], "ticket": []},
  181. "access_users": {
  182. "admin": [],
  183. "commit": [],
  184. "owner": ["pingou"],
  185. "ticket": [],
  186. },
  187. "close_status": [
  188. "Invalid",
  189. "Insufficient data",
  190. "Fixed",
  191. "Duplicate",
  192. ],
  193. "custom_keys": [],
  194. "date_created": "1490272832",
  195. "date_modified": "1490272832",
  196. "description": "namespaced test project",
  197. "fullname": "somenamespace/test3",
  198. "url_path": "somenamespace/test3",
  199. "id": 3,
  200. "milestones": {},
  201. "name": "test3",
  202. "namespace": "somenamespace",
  203. "parent": None,
  204. "priorities": {},
  205. "tags": [],
  206. "user": {"fullname": "PY C", "name": "pingou"},
  207. },
  208. ],
  209. "repos_pagination": {
  210. "first": "http://localhost...",
  211. "last": "http://localhost...",
  212. "next": None,
  213. "repopage": 1,
  214. "pages": 1,
  215. "per_page": 20,
  216. "prev": None,
  217. },
  218. "user": {
  219. "fullname": "PY C",
  220. "name": "pingou",
  221. "avatar_url": "https://seccdn.libravatar.org/avatar/...",
  222. },
  223. }
  224. data["user"]["avatar_url"] = "https://seccdn.libravatar.org/avatar/..."
  225. self.assertEqual(data, expected_data)
  226. @patch("pagure.lib.notify.send_email")
  227. def test_api_view_user_activity_stats(self, mockemail):
  228. """ Test the api_view_user_activity_stats method of the flask user
  229. api. """
  230. mockemail.return_value = True
  231. tests.create_projects(self.session)
  232. tests.create_tokens(self.session)
  233. tests.create_tokens_acl(self.session)
  234. headers = {"Authorization": "token aaabbbcccddd"}
  235. # Create a pull-request
  236. repo = pagure.lib.query._get_project(self.session, "test")
  237. forked_repo = pagure.lib.query._get_project(self.session, "test")
  238. req = pagure.lib.query.new_pull_request(
  239. session=self.session,
  240. repo_from=forked_repo,
  241. branch_from="master",
  242. repo_to=repo,
  243. branch_to="master",
  244. title="test pull-request",
  245. user="pingou",
  246. )
  247. self.session.commit()
  248. self.assertEqual(req.id, 1)
  249. self.assertEqual(req.title, "test pull-request")
  250. # Check comments before
  251. self.session.commit()
  252. request = pagure.lib.query.search_pull_requests(
  253. self.session, project_id=1, requestid=1
  254. )
  255. self.assertEqual(len(request.comments), 0)
  256. data = {"comment": "This is a very interesting question"}
  257. # Valid request
  258. output = self.app.post(
  259. "/api/0/test/pull-request/1/comment", data=data, headers=headers
  260. )
  261. self.assertEqual(output.status_code, 200)
  262. data = json.loads(output.get_data(as_text=True))
  263. self.assertDictEqual(data, {"message": "Comment added"})
  264. # One comment added
  265. self.session.commit()
  266. request = pagure.lib.query.search_pull_requests(
  267. self.session, project_id=1, requestid=1
  268. )
  269. self.assertEqual(len(request.comments), 1)
  270. # Close PR
  271. output = self.app.post(
  272. "/api/0/test/pull-request/1/close", headers=headers
  273. )
  274. self.assertEqual(output.status_code, 200)
  275. data = json.loads(output.get_data(as_text=True))
  276. self.assertDictEqual(data, {"message": "Pull-request closed!"})
  277. # PR closed
  278. self.session.commit()
  279. request = pagure.lib.query.search_pull_requests(
  280. self.session, project_id=1, requestid=1
  281. )
  282. self.assertEqual(request.status, "Closed")
  283. # Finally retrieve the user's logs
  284. output = self.app.get("/api/0/user/pingou/activity/stats")
  285. self.assertEqual(output.status_code, 200)
  286. data = json.loads(output.get_data(as_text=True))
  287. date = datetime.datetime.utcnow().date().strftime("%Y-%m-%d")
  288. self.assertDictEqual(data, {date: 4})
  289. @patch("pagure.lib.notify.send_email")
  290. def test_api_view_user_activity_date(self, mockemail):
  291. """ Test the api_view_user_activity_date method of the flask user
  292. api. """
  293. self.test_api_view_user_activity_stats()
  294. # Invalid date
  295. output = self.app.get("/api/0/user/pingou/activity/AABB")
  296. self.assertEqual(output.status_code, 400)
  297. # Invalid date
  298. output = self.app.get("/api/0/user/pingou/activity/2016asd")
  299. self.assertEqual(output.status_code, 200)
  300. exp = {"activities": [], "date": "2016-01-01"}
  301. self.assertEqual(json.loads(output.get_data(as_text=True)), exp)
  302. # Date parsed, just not really as expected
  303. output = self.app.get("/api/0/user/pingou/activity/20161245")
  304. self.assertEqual(output.status_code, 200)
  305. exp = {"activities": [], "date": "1970-08-22"}
  306. self.assertEqual(json.loads(output.get_data(as_text=True)), exp)
  307. date = datetime.datetime.utcnow().date().strftime("%Y-%m-%d")
  308. # Retrieve the user's logs for today
  309. output = self.app.get("/api/0/user/pingou/activity/%s" % date)
  310. self.assertEqual(output.status_code, 200)
  311. data = json.loads(output.get_data(as_text=True))
  312. exp = {
  313. "activities": [
  314. {
  315. "date": date,
  316. "date_created": "1477558752",
  317. "type": "pull-request",
  318. "description_mk": '<div class="markdown"><p>pingou created PR <a href="/test/pull-request/1" title="[Closed] test pull-request">test#1</a></p></div>',
  319. "id": 1,
  320. "ref_id": "1",
  321. "type": "created",
  322. "user": {"fullname": "PY C", "name": "pingou"},
  323. },
  324. {
  325. "date": date,
  326. "date_created": "1477558752",
  327. "type": "pull-request",
  328. "description_mk": '<div class="markdown"><p>pingou commented on PR <a href="/test/pull-request/1" title="[Closed] test pull-request">test#1</a></p></div>',
  329. "id": 2,
  330. "ref_id": "1",
  331. "type": "commented",
  332. "user": {"fullname": "PY C", "name": "pingou"},
  333. },
  334. {
  335. "date": date,
  336. "date_created": "1477558752",
  337. "type": "pull-request",
  338. "description_mk": '<div class="markdown"><p>pingou closed PR <a href="/test/pull-request/1" title="[Closed] test pull-request">test#1</a></p></div>',
  339. "id": 3,
  340. "ref_id": "1",
  341. "type": "closed",
  342. "user": {"fullname": "PY C", "name": "pingou"},
  343. },
  344. {
  345. "date": date,
  346. "date_created": "1477558752",
  347. "type": "pull-request",
  348. "description_mk": '<div class="markdown"><p>pingou commented on PR <a href="/test/pull-request/1" title="[Closed] test pull-request">test#1</a></p></div>',
  349. "id": 4,
  350. "ref_id": "1",
  351. "type": "commented",
  352. "user": {"fullname": "PY C", "name": "pingou"},
  353. },
  354. ],
  355. "date": date,
  356. }
  357. for idx, act in enumerate(data["activities"]):
  358. act["date_created"] = "1477558752"
  359. data["activities"][idx] = act
  360. self.assertEqual(data, exp)
  361. @patch("pagure.lib.notify.send_email")
  362. def test_api_view_user_activity_date_1_activity(self, mockemail):
  363. """ Test the api_view_user_activity_date method of the flask user
  364. api when the user only did one action. """
  365. tests.create_projects(self.session)
  366. repo = pagure.lib.query._get_project(self.session, "test")
  367. now = datetime.datetime.utcnow()
  368. date = now.date().strftime("%Y-%m-%d")
  369. # Create a single commit log
  370. log = model.PagureLog(
  371. user_id=1,
  372. user_email="foo@bar.com",
  373. project_id=1,
  374. log_type="committed",
  375. ref_id="githash",
  376. date=now.date(),
  377. date_created=now,
  378. )
  379. self.session.add(log)
  380. self.session.commit()
  381. # Retrieve the user's logs for today
  382. output = self.app.get(
  383. "/api/0/user/pingou/activity/%s?grouped=1" % date
  384. )
  385. self.assertEqual(output.status_code, 200)
  386. data = json.loads(output.get_data(as_text=True))
  387. exp = {
  388. "activities": [
  389. {
  390. "description_mk": '<div class="markdown"><p>pingou committed on test#githash</p></div>'
  391. }
  392. ],
  393. "date": date,
  394. }
  395. self.assertEqual(data, exp)
  396. @patch("pagure.lib.notify.send_email")
  397. def test_api_view_user_activity_timezone_negative(self, mockemail):
  398. """Test api_view_user_activity{_stats,_date} with the America/
  399. New York timezone, which is 5 hours behind UTC in winter and
  400. 4 hours behind UTC in summer (daylight savings). The events
  401. will occur on XXXX-02-15 in UTC, but on XXXX-02-14 local.
  402. """
  403. tests.create_projects(self.session)
  404. repo = pagure.lib.query._get_project(self.session, "test")
  405. today = datetime.datetime.utcnow().date()
  406. year = today.year
  407. if today.year == 2 and today.date <= 15:
  408. year = year - 1
  409. elif today.year < 2:
  410. year = year - 1
  411. dateobj = datetime.datetime(year, 2, 15, 3, 30)
  412. utcdate = "%s-02-15" % year
  413. # the Unix timestamp for YYYY-02-15 12:00 UTC
  414. utcts = str(
  415. int(
  416. (
  417. datetime.datetime(year, 2, 15, 12, 0, tzinfo=pytz.UTC)
  418. - datetime.datetime(1970, 1, 1, tzinfo=pytz.UTC)
  419. ).total_seconds()
  420. )
  421. )
  422. localdate = "%s-02-14" % today.year
  423. # the Unix timestamp for YYYY-02-15 18:00 America/New_York
  424. localts = str(
  425. int(
  426. (
  427. datetime.datetime(
  428. year,
  429. 2,
  430. 14,
  431. 17,
  432. 0,
  433. tzinfo=pytz.timezone("America/New_York"),
  434. )
  435. - datetime.datetime(
  436. 1970, 1, 1, tzinfo=pytz.timezone("America/New_York")
  437. )
  438. ).total_seconds()
  439. )
  440. )
  441. # Create a single commit log
  442. log = model.PagureLog(
  443. user_id=1,
  444. user_email="foo@bar.com",
  445. project_id=1,
  446. log_type="committed",
  447. ref_id="githash",
  448. date=dateobj.date(),
  449. date_created=dateobj,
  450. )
  451. self.session.add(log)
  452. self.session.commit()
  453. # Retrieve the user's stats with no timezone specified (==UTC)
  454. output = self.app.get("/api/0/user/pingou/activity/stats")
  455. self.assertEqual(output.status_code, 200)
  456. data = json.loads(output.get_data(as_text=True))
  457. # date in output should be UTC date
  458. self.assertDictEqual(data, {utcdate: 1})
  459. # Now in timestamp format...
  460. output = self.app.get(
  461. "/api/0/user/pingou/activity/stats?format=timestamp"
  462. )
  463. self.assertEqual(output.status_code, 200)
  464. data = json.loads(output.get_data(as_text=True))
  465. # timestamp in output should be UTC ts
  466. self.assertDictEqual(data, {utcts: 1})
  467. # Retrieve the user's stats with local timezone specified
  468. output = self.app.get(
  469. "/api/0/user/pingou/activity/stats?tz=America/New_York"
  470. )
  471. self.assertEqual(output.status_code, 200)
  472. data = json.loads(output.get_data(as_text=True))
  473. # date in output should be local date
  474. self.assertDictEqual(data, {localdate: 1})
  475. # Now in timestamp format...
  476. output = self.app.get(
  477. "/api/0/user/pingou/activity/stats?format=timestamp&tz=America/New_York"
  478. )
  479. self.assertEqual(output.status_code, 200)
  480. data = json.loads(output.get_data(as_text=True))
  481. # timestamp in output should be local ts
  482. self.assertDictEqual(data, {localts: 1})
  483. # Retrieve the user's logs for 2018-02-15 with no timezone
  484. output = self.app.get(
  485. "/api/0/user/pingou/activity/%s?grouped=1" % utcdate
  486. )
  487. self.assertEqual(output.status_code, 200)
  488. data = json.loads(output.get_data(as_text=True))
  489. exp = {
  490. "activities": [
  491. {
  492. "description_mk": '<div class="markdown"><p>pingou committed on test#githash</p></div>'
  493. }
  494. ],
  495. "date": utcdate,
  496. }
  497. self.assertEqual(data, exp)
  498. # Now retrieve the user's logs for 2018-02-14 with local time
  499. output = self.app.get(
  500. "/api/0/user/pingou/activity/%s?grouped=1&tz=America/New_York"
  501. % localdate
  502. )
  503. self.assertEqual(output.status_code, 200)
  504. data = json.loads(output.get_data(as_text=True))
  505. exp["date"] = localdate
  506. self.assertEqual(data, exp)
  507. @patch("pagure.lib.notify.send_email")
  508. def test_api_view_user_activity_timezone_positive(self, mockemail):
  509. """Test api_view_user_activity{_stats,_date} with the Asia/
  510. Dubai timezone, which is 4 hours ahead of UTC. The events will
  511. occur on XXXX-02-15 in UTC, but on XXXX-02-16 in local time.
  512. """
  513. tests.create_projects(self.session)
  514. repo = pagure.lib.query._get_project(self.session, "test")
  515. today = datetime.datetime.utcnow().date()
  516. year = today.year
  517. if today.year == 2 and today.date <= 15:
  518. year = year - 1
  519. elif today.year < 2:
  520. year = year - 1
  521. dateobj = datetime.datetime(year, 2, 15, 22, 30)
  522. utcdate = "%s-02-15" % year
  523. # the Unix timestamp for YYYY-02-15 12:00 UTC
  524. utcts = str(
  525. int(
  526. (
  527. datetime.datetime(year, 2, 15, 12, 0, tzinfo=pytz.UTC)
  528. - datetime.datetime(1970, 1, 1, tzinfo=pytz.UTC)
  529. ).total_seconds()
  530. )
  531. )
  532. localdate = "%s-02-16" % year
  533. # the Unix timestamp for YYYY-02-16 9:00 Asia/Dubai
  534. localts = str(
  535. int(
  536. (
  537. datetime.datetime(
  538. year, 2, 16, 8, 0, tzinfo=pytz.timezone("Asia/Dubai")
  539. )
  540. - datetime.datetime(
  541. 1970, 1, 1, tzinfo=pytz.timezone("Asia/Dubai")
  542. )
  543. ).total_seconds()
  544. )
  545. )
  546. # Create a single commit log
  547. log = model.PagureLog(
  548. user_id=1,
  549. user_email="foo@bar.com",
  550. project_id=1,
  551. log_type="committed",
  552. ref_id="githash",
  553. date=dateobj.date(),
  554. date_created=dateobj,
  555. )
  556. self.session.add(log)
  557. self.session.commit()
  558. # Retrieve the user's stats with no timezone specified (==UTC)
  559. output = self.app.get("/api/0/user/pingou/activity/stats")
  560. self.assertEqual(output.status_code, 200)
  561. data = json.loads(output.get_data(as_text=True))
  562. # date in output should be UTC date
  563. self.assertDictEqual(data, {utcdate: 1})
  564. # Now in timestamp format...
  565. output = self.app.get(
  566. "/api/0/user/pingou/activity/stats?format=timestamp"
  567. )
  568. self.assertEqual(output.status_code, 200)
  569. data = json.loads(output.get_data(as_text=True))
  570. # timestamp in output should be UTC ts
  571. self.assertDictEqual(data, {utcts: 1})
  572. # Retrieve the user's stats with local timezone specified
  573. output = self.app.get(
  574. "/api/0/user/pingou/activity/stats?tz=Asia/Dubai"
  575. )
  576. self.assertEqual(output.status_code, 200)
  577. data = json.loads(output.get_data(as_text=True))
  578. # date in output should be local date
  579. self.assertDictEqual(data, {localdate: 1})
  580. # Now in timestamp format...
  581. output = self.app.get(
  582. "/api/0/user/pingou/activity/stats?format=timestamp&tz=Asia/Dubai"
  583. )
  584. self.assertEqual(output.status_code, 200)
  585. data = json.loads(output.get_data(as_text=True))
  586. # timestamp in output should be local ts
  587. self.assertDictEqual(data, {localts: 1})
  588. # Retrieve the user's logs for 2018-02-15 with no timezone
  589. output = self.app.get(
  590. "/api/0/user/pingou/activity/%s?grouped=1" % utcdate
  591. )
  592. self.assertEqual(output.status_code, 200)
  593. data = json.loads(output.get_data(as_text=True))
  594. exp = {
  595. "activities": [
  596. {
  597. "description_mk": '<div class="markdown"><p>pingou committed on test#githash</p></div>'
  598. }
  599. ],
  600. "date": utcdate,
  601. }
  602. self.assertEqual(data, exp)
  603. # Now retrieve the user's logs for 2018-02-16 with local time
  604. output = self.app.get(
  605. "/api/0/user/pingou/activity/%s?grouped=1&tz=Asia/Dubai"
  606. % localdate
  607. )
  608. self.assertEqual(output.status_code, 200)
  609. data = json.loads(output.get_data(as_text=True))
  610. exp["date"] = localdate
  611. self.assertEqual(data, exp)
  612. class PagureFlaskApiUsertestrequests(tests.Modeltests):
  613. """ Tests for the user requests endpoints """
  614. maxDiff = None
  615. def setUp(self):
  616. """ Set up the environnment, ran before every tests. """
  617. super(PagureFlaskApiUsertestrequests, self).setUp()
  618. pagure.config.config["REQUESTS_FOLDER"] = None
  619. tests.create_projects(self.session)
  620. # Create few pull-requests
  621. repo = pagure.lib.query.get_authorized_project(self.session, "test")
  622. forked_repo = pagure.lib.query.get_authorized_project(
  623. self.session, "test"
  624. )
  625. pagure.lib.query.new_pull_request(
  626. session=self.session,
  627. repo_from=forked_repo,
  628. branch_from="master",
  629. repo_to=repo,
  630. branch_to="master",
  631. title="open pullrequest by user foo on repo test",
  632. user="foo",
  633. )
  634. repo = pagure.lib.query.get_authorized_project(self.session, "test2")
  635. forked_repo = pagure.lib.query.get_authorized_project(
  636. self.session, "test2"
  637. )
  638. pagure.lib.query.new_pull_request(
  639. session=self.session,
  640. repo_from=forked_repo,
  641. branch_from="master",
  642. repo_to=repo,
  643. branch_to="master",
  644. title="open pullrequest by user foo on repo test2",
  645. user="foo",
  646. )
  647. self.session.commit()
  648. repo = pagure.lib.query.get_authorized_project(self.session, "test")
  649. forked_repo = pagure.lib.query.get_authorized_project(
  650. self.session, "test"
  651. )
  652. pagure.lib.query.new_pull_request(
  653. session=self.session,
  654. repo_from=forked_repo,
  655. branch_from="master",
  656. repo_to=repo,
  657. branch_to="master",
  658. title="closed pullrequest by user foo on repo test",
  659. user="foo",
  660. status="Closed",
  661. )
  662. repo = pagure.lib.query.get_authorized_project(self.session, "test2")
  663. forked_repo = pagure.lib.query.get_authorized_project(
  664. self.session, "test2"
  665. )
  666. pagure.lib.query.new_pull_request(
  667. session=self.session,
  668. repo_from=forked_repo,
  669. branch_from="master",
  670. repo_to=repo,
  671. branch_to="master",
  672. title="closed pullrequest by user foo on repo test2",
  673. user="foo",
  674. status="Closed",
  675. )
  676. self.session.commit()
  677. repo = pagure.lib.query.get_authorized_project(self.session, "test")
  678. forked_repo = pagure.lib.query.get_authorized_project(
  679. self.session, "test"
  680. )
  681. pagure.lib.query.new_pull_request(
  682. session=self.session,
  683. repo_from=forked_repo,
  684. branch_from="master",
  685. repo_to=repo,
  686. branch_to="master",
  687. title="merged pullrequest by user foo on repo test",
  688. user="foo",
  689. status="Merged",
  690. )
  691. repo = pagure.lib.query.get_authorized_project(self.session, "test2")
  692. forked_repo = pagure.lib.query.get_authorized_project(
  693. self.session, "test2"
  694. )
  695. pagure.lib.query.new_pull_request(
  696. session=self.session,
  697. repo_from=forked_repo,
  698. branch_from="master",
  699. repo_to=repo,
  700. branch_to="master",
  701. title="merged pullrequest by user foo on repo test2",
  702. user="foo",
  703. status="Merged",
  704. )
  705. self.session.commit()
  706. repo = pagure.lib.query.get_authorized_project(self.session, "test")
  707. forked_repo = pagure.lib.query.get_authorized_project(
  708. self.session, "test"
  709. )
  710. pagure.lib.query.new_pull_request(
  711. session=self.session,
  712. repo_from=forked_repo,
  713. branch_from="master",
  714. repo_to=repo,
  715. branch_to="master",
  716. title="open pullrequest by user pingou on repo test",
  717. user="pingou",
  718. )
  719. self.session.commit()
  720. repo = pagure.lib.query.get_authorized_project(self.session, "test2")
  721. forked_repo = pagure.lib.query.get_authorized_project(
  722. self.session, "test2"
  723. )
  724. pagure.lib.query.new_pull_request(
  725. session=self.session,
  726. repo_from=forked_repo,
  727. branch_from="master",
  728. repo_to=repo,
  729. branch_to="master",
  730. title="open pullrequest by user pingou on repo test2",
  731. user="pingou",
  732. )
  733. self.session.commit()
  734. repo = pagure.lib.query.get_authorized_project(self.session, "test")
  735. forked_repo = pagure.lib.query.get_authorized_project(
  736. self.session, "test"
  737. )
  738. pagure.lib.query.new_pull_request(
  739. session=self.session,
  740. repo_from=forked_repo,
  741. branch_from="master",
  742. repo_to=repo,
  743. branch_to="master",
  744. title="closed pullrequest by user pingou on repo test",
  745. user="pingou",
  746. status="Closed",
  747. )
  748. self.session.commit()
  749. repo = pagure.lib.query.get_authorized_project(self.session, "test2")
  750. forked_repo = pagure.lib.query.get_authorized_project(
  751. self.session, "test2"
  752. )
  753. pagure.lib.query.new_pull_request(
  754. session=self.session,
  755. repo_from=forked_repo,
  756. branch_from="master",
  757. repo_to=repo,
  758. branch_to="master",
  759. title="closed pullrequest by user pingou on repo test2",
  760. user="pingou",
  761. status="Closed",
  762. )
  763. self.session.commit()
  764. repo = pagure.lib.query.get_authorized_project(self.session, "test")
  765. forked_repo = pagure.lib.query.get_authorized_project(
  766. self.session, "test"
  767. )
  768. pagure.lib.query.new_pull_request(
  769. session=self.session,
  770. repo_from=forked_repo,
  771. branch_from="master",
  772. repo_to=repo,
  773. branch_to="master",
  774. title="merged pullrequest by user pingou on repo test",
  775. user="pingou",
  776. status="Merged",
  777. )
  778. self.session.commit()
  779. repo = pagure.lib.query.get_authorized_project(self.session, "test2")
  780. forked_repo = pagure.lib.query.get_authorized_project(
  781. self.session, "test2"
  782. )
  783. pagure.lib.query.new_pull_request(
  784. session=self.session,
  785. repo_from=forked_repo,
  786. branch_from="master",
  787. repo_to=repo,
  788. branch_to="master",
  789. title="merged pullrequest by user pingou on repo test2",
  790. user="pingou",
  791. status="Merged",
  792. )
  793. self.session.commit()
  794. @patch("pagure.lib.notify.send_email")
  795. def test_api_view_user_requests_filed(self, mockemail):
  796. """ Test the api_view_user_requests_filed method of the flask user
  797. api """
  798. # First we test without the status parameter. It should default to `open`
  799. output = self.app.get("/api/0/user/pingou/requests/filed")
  800. self.assertEqual(output.status_code, 200)
  801. data = json.loads(output.get_data(as_text=True))
  802. self.assertEqual(len(data["requests"]), 2)
  803. self.assertEqual(
  804. sorted(data.keys()),
  805. ["args", "pagination", "requests", "total_requests"],
  806. )
  807. self.assertEqual(data["requests"][0]["user"]["name"], "pingou")
  808. self.assertEqual(data["requests"][1]["user"]["name"], "pingou")
  809. self.assertEqual(data["requests"][0]["status"], "Open")
  810. self.assertEqual(data["requests"][1]["status"], "Open")
  811. self.assertEqual(
  812. data["requests"][0]["title"],
  813. "open pullrequest by user pingou on repo test2",
  814. )
  815. self.assertEqual(
  816. data["requests"][1]["title"],
  817. "open pullrequest by user pingou on repo test",
  818. )
  819. self.assertEqual(data["args"]["status"], "open")
  820. self.assertEqual(data["args"]["page"], 1)
  821. # Next test with the status parameter set to `open`.
  822. output = self.app.get("/api/0/user/pingou/requests/filed?status=open")
  823. self.assertEqual(output.status_code, 200)
  824. data = json.loads(output.get_data(as_text=True))
  825. self.assertEqual(len(data["requests"]), 2)
  826. self.assertEqual(
  827. sorted(data.keys()),
  828. ["args", "pagination", "requests", "total_requests"],
  829. )
  830. self.assertEqual(data["requests"][0]["user"]["name"], "pingou")
  831. self.assertEqual(data["requests"][1]["user"]["name"], "pingou")
  832. self.assertEqual(data["requests"][0]["status"], "Open")
  833. self.assertEqual(data["requests"][1]["status"], "Open")
  834. self.assertEqual(
  835. data["requests"][0]["title"],
  836. "open pullrequest by user pingou on repo test2",
  837. )
  838. self.assertEqual(
  839. data["requests"][1]["title"],
  840. "open pullrequest by user pingou on repo test",
  841. )
  842. self.assertEqual(data["args"]["status"], "open")
  843. self.assertEqual(data["args"]["page"], 1)
  844. # Next test with the status parameter set to `closed`.
  845. output = self.app.get(
  846. "/api/0/user/pingou/requests/filed?status=closed"
  847. )
  848. self.assertEqual(output.status_code, 200)
  849. data = json.loads(output.get_data(as_text=True))
  850. self.assertEqual(len(data["requests"]), 2)
  851. self.assertEqual(
  852. sorted(data.keys()),
  853. ["args", "pagination", "requests", "total_requests"],
  854. )
  855. self.assertEqual(data["requests"][0]["user"]["name"], "pingou")
  856. self.assertEqual(data["requests"][1]["user"]["name"], "pingou")
  857. self.assertEqual(data["requests"][0]["status"], "Closed")
  858. self.assertEqual(data["requests"][1]["status"], "Closed")
  859. self.assertEqual(
  860. data["requests"][0]["title"],
  861. "closed pullrequest by user pingou on repo test2",
  862. )
  863. self.assertEqual(
  864. data["requests"][1]["title"],
  865. "closed pullrequest by user pingou on repo test",
  866. )
  867. self.assertEqual(data["args"]["status"], "closed")
  868. self.assertEqual(data["args"]["page"], 1)
  869. # Next test with the status parameter set to `merged`.
  870. output = self.app.get(
  871. "/api/0/user/pingou/requests/filed?status=merged"
  872. )
  873. self.assertEqual(output.status_code, 200)
  874. data = json.loads(output.get_data(as_text=True))
  875. self.assertEqual(len(data["requests"]), 2)
  876. self.assertEqual(
  877. sorted(data.keys()),
  878. ["args", "pagination", "requests", "total_requests"],
  879. )
  880. self.assertEqual(data["requests"][0]["user"]["name"], "pingou")
  881. self.assertEqual(data["requests"][1]["user"]["name"], "pingou")
  882. self.assertEqual(data["requests"][0]["status"], "Merged")
  883. self.assertEqual(data["requests"][1]["status"], "Merged")
  884. self.assertEqual(
  885. data["requests"][0]["title"],
  886. "merged pullrequest by user pingou on repo test2",
  887. )
  888. self.assertEqual(
  889. data["requests"][1]["title"],
  890. "merged pullrequest by user pingou on repo test",
  891. )
  892. self.assertEqual(data["args"]["status"], "merged")
  893. self.assertEqual(data["args"]["page"], 1)
  894. # Finally, test with the status parameter set to `all`.
  895. output = self.app.get("/api/0/user/pingou/requests/filed?status=all")
  896. self.assertEqual(output.status_code, 200)
  897. data = json.loads(output.get_data(as_text=True))
  898. self.assertEqual(len(data["requests"]), 6)
  899. self.assertEqual(
  900. sorted(data.keys()),
  901. ["args", "pagination", "requests", "total_requests"],
  902. )
  903. self.assertEqual(data["requests"][0]["user"]["name"], "pingou")
  904. self.assertEqual(data["requests"][1]["user"]["name"], "pingou")
  905. self.assertEqual(data["requests"][2]["user"]["name"], "pingou")
  906. self.assertEqual(data["requests"][3]["user"]["name"], "pingou")
  907. self.assertEqual(data["requests"][4]["user"]["name"], "pingou")
  908. self.assertEqual(data["requests"][5]["user"]["name"], "pingou")
  909. self.assertEqual(data["requests"][0]["status"], "Merged")
  910. self.assertEqual(data["requests"][1]["status"], "Merged")
  911. self.assertEqual(data["requests"][2]["status"], "Closed")
  912. self.assertEqual(data["requests"][3]["status"], "Closed")
  913. self.assertEqual(data["requests"][4]["status"], "Open")
  914. self.assertEqual(data["requests"][5]["status"], "Open")
  915. self.assertEqual(
  916. data["requests"][0]["title"],
  917. "merged pullrequest by user pingou on repo test2",
  918. )
  919. self.assertEqual(
  920. data["requests"][1]["title"],
  921. "merged pullrequest by user pingou on repo test",
  922. )
  923. self.assertEqual(
  924. data["requests"][2]["title"],
  925. "closed pullrequest by user pingou on repo test2",
  926. )
  927. self.assertEqual(
  928. data["requests"][3]["title"],
  929. "closed pullrequest by user pingou on repo test",
  930. )
  931. self.assertEqual(
  932. data["requests"][4]["title"],
  933. "open pullrequest by user pingou on repo test2",
  934. )
  935. self.assertEqual(
  936. data["requests"][5]["title"],
  937. "open pullrequest by user pingou on repo test",
  938. )
  939. self.assertEqual(data["args"]["status"], "all")
  940. self.assertEqual(data["args"]["page"], 1)
  941. # Test page 2 with the status parameter set to `all`.
  942. output = self.app.get(
  943. "/api/0/user/pingou/requests/filed?status=all&page=2"
  944. )
  945. self.assertEqual(output.status_code, 200)
  946. data = json.loads(output.get_data(as_text=True))
  947. self.assertEqual(len(data["requests"]), 0)
  948. self.assertEqual(
  949. sorted(data.keys()),
  950. ["args", "pagination", "requests", "total_requests"],
  951. )
  952. self.assertEqual(data["args"]["page"], 2)
  953. @patch("pagure.lib.notify.send_email")
  954. def test_api_view_user_requests_filed_created(self, mockemail):
  955. """ Test the api_view_user_requests_filed method of the flask user
  956. api with the created parameter """
  957. today = datetime.datetime.utcnow().date()
  958. output = self.app.get(
  959. "/api/0/user/pingou/requests/filed?status=all&created=%s"
  960. % (today.isoformat())
  961. )
  962. self.assertEqual(output.status_code, 200)
  963. data = json.loads(output.get_data(as_text=True))
  964. self.assertEqual(len(data["requests"]), 6)
  965. yesterday = today - datetime.timedelta(days=1)
  966. output = self.app.get(
  967. "/api/0/user/pingou/requests/filed?status=all&created=%s"
  968. % (yesterday.isoformat())
  969. )
  970. self.assertEqual(output.status_code, 200)
  971. data = json.loads(output.get_data(as_text=True))
  972. self.assertEqual(len(data["requests"]), 6)
  973. tomorrow = today + datetime.timedelta(days=1)
  974. output = self.app.get(
  975. "/api/0/user/pingou/requests/filed?status=all&created=%s"
  976. % (tomorrow.isoformat())
  977. )
  978. self.assertEqual(output.status_code, 200)
  979. data = json.loads(output.get_data(as_text=True))
  980. self.assertEqual(len(data["requests"]), 0)
  981. output = self.app.get(
  982. "/api/0/user/pingou/requests/filed?status=all&created=..%s"
  983. % (today.isoformat())
  984. )
  985. self.assertEqual(output.status_code, 200)
  986. data = json.loads(output.get_data(as_text=True))
  987. self.assertEqual(len(data["requests"]), 0)
  988. output = self.app.get(
  989. "/api/0/user/pingou/requests/filed?status=all&created=..%s"
  990. % (yesterday.isoformat())
  991. )
  992. self.assertEqual(output.status_code, 200)
  993. data = json.loads(output.get_data(as_text=True))
  994. self.assertEqual(len(data["requests"]), 0)
  995. thedaybefore = today - datetime.timedelta(days=1)
  996. output = self.app.get(
  997. "/api/0/user/pingou/requests/filed?status=all&created=..%s"
  998. % (thedaybefore.isoformat())
  999. )
  1000. self.assertEqual(output.status_code, 200)
  1001. data = json.loads(output.get_data(as_text=True))
  1002. self.assertEqual(len(data["requests"]), 0)
  1003. output = self.app.get(
  1004. "/api/0/user/pingou/requests/filed?status=all&created=..%s"
  1005. % (tomorrow.isoformat())
  1006. )
  1007. self.assertEqual(output.status_code, 200)
  1008. data = json.loads(output.get_data(as_text=True))
  1009. self.assertEqual(len(data["requests"]), 6)
  1010. output = self.app.get(
  1011. "/api/0/user/pingou/requests/filed?status=all&created=%s..%s"
  1012. % (thedaybefore.isoformat(), tomorrow.isoformat())
  1013. )
  1014. self.assertEqual(output.status_code, 200)
  1015. data = json.loads(output.get_data(as_text=True))
  1016. self.assertEqual(len(data["requests"]), 6)
  1017. @patch("pagure.lib.notify.send_email")
  1018. def test_api_view_user_requests_filed_updated(self, mockemail):
  1019. """ Test the api_view_user_requests_filed method of the flask user
  1020. api with the created parameter """
  1021. today = datetime.datetime.utcnow().date()
  1022. output = self.app.get(
  1023. "/api/0/user/pingou/requests/filed?status=all&updated=%s"
  1024. % (today.isoformat())
  1025. )
  1026. self.assertEqual(output.status_code, 200)
  1027. data = json.loads(output.get_data(as_text=True))
  1028. self.assertEqual(len(data["requests"]), 0)
  1029. yesterday = today - datetime.timedelta(days=1)
  1030. output = self.app.get(
  1031. "/api/0/user/pingou/requests/filed?status=all&updated=%s"
  1032. % (yesterday.isoformat())
  1033. )
  1034. self.assertEqual(output.status_code, 200)
  1035. data = json.loads(output.get_data(as_text=True))
  1036. self.assertEqual(len(data["requests"]), 0)
  1037. tomorrow = today + datetime.timedelta(days=1)
  1038. output = self.app.get(
  1039. "/api/0/user/pingou/requests/filed?status=all&updated=%s"
  1040. % (tomorrow.isoformat())
  1041. )
  1042. self.assertEqual(output.status_code, 200)
  1043. data = json.loads(output.get_data(as_text=True))
  1044. self.assertEqual(len(data["requests"]), 6)
  1045. @patch("pagure.lib.notify.send_email")
  1046. def test_api_view_user_requests_filed_closed(self, mockemail):
  1047. """ Test the api_view_user_requests_filed method of the flask user
  1048. api with the created parameter """
  1049. today = datetime.datetime.utcnow().date()
  1050. output = self.app.get(
  1051. "/api/0/user/pingou/requests/filed?status=all&closed=%s"
  1052. % (today.isoformat())
  1053. )
  1054. self.assertEqual(output.status_code, 200)
  1055. data = json.loads(output.get_data(as_text=True))
  1056. self.assertEqual(len(data["requests"]), 0)
  1057. yesterday = today - datetime.timedelta(days=1)
  1058. output = self.app.get(
  1059. "/api/0/user/pingou/requests/filed?status=all&closed=%s"
  1060. % (yesterday.isoformat())
  1061. )
  1062. self.assertEqual(output.status_code, 200)
  1063. data = json.loads(output.get_data(as_text=True))
  1064. self.assertEqual(len(data["requests"]), 0)
  1065. tomorrow = today + datetime.timedelta(days=1)
  1066. output = self.app.get(
  1067. "/api/0/user/pingou/requests/filed?status=all&closed=%s"
  1068. % (tomorrow.isoformat())
  1069. )
  1070. self.assertEqual(output.status_code, 200)
  1071. data = json.loads(output.get_data(as_text=True))
  1072. self.assertEqual(len(data["requests"]), 0)
  1073. @patch("pagure.lib.notify.send_email")
  1074. def test_api_view_user_requests_filed_foo(self, mockemail):
  1075. """ Test the api_view_user_requests_filed method of the flask user
  1076. api """
  1077. # Default data returned
  1078. output = self.app.get(
  1079. "/api/0/user/foo/requests/filed?status=all&per_page=6"
  1080. )
  1081. self.assertEqual(output.status_code, 200)
  1082. data = json.loads(output.get_data(as_text=True))
  1083. self.assertEqual(len(data["requests"]), 6)
  1084. self.assertEqual(
  1085. sorted(data.keys()),
  1086. ["args", "pagination", "requests", "total_requests"],
  1087. )
  1088. # There are 6 PRs, that's 1 page at 6 results per page
  1089. self.assertEqual(data["pagination"]["pages"], 1)
  1090. @patch("pagure.lib.notify.send_email")
  1091. def test_api_view_user_requests_filed_foo_grp_access(self, mockemail):
  1092. """ Test when the user has accessed to some PRs via a group. """
  1093. # Add the user to a group
  1094. msg = pagure.lib.query.add_group(
  1095. self.session,
  1096. group_name="some_group",
  1097. display_name="Some Group",
  1098. description=None,
  1099. group_type="bar",
  1100. user="pingou",
  1101. is_admin=False,
  1102. blacklist=[],
  1103. )
  1104. self.session.commit()
  1105. # Add the group to the project `test2`
  1106. project = pagure.lib.query._get_project(self.session, "test2")
  1107. msg = pagure.lib.query.add_group_to_project(
  1108. session=self.session,
  1109. project=project,
  1110. new_group="some_group",
  1111. user="pingou",
  1112. )
  1113. self.session.commit()
  1114. self.assertEqual(msg, "Group added")
  1115. # Add foo to the group
  1116. group = pagure.lib.query.search_groups(
  1117. self.session, group_name="some_group"
  1118. )
  1119. result = pagure.lib.query.add_user_to_group(
  1120. self.session, "foo", group, "pingou", True
  1121. )
  1122. self.session.commit()
  1123. self.assertEqual(result, "User `foo` added to the group `some_group`.")
  1124. # Query the API for foo's filed PRs
  1125. output = self.app.get(
  1126. "/api/0/user/foo/requests/filed?status=all&per_page=6"
  1127. )
  1128. self.assertEqual(output.status_code, 200)
  1129. data = json.loads(output.get_data(as_text=True))
  1130. self.assertEqual(len(data["requests"]), 6)
  1131. self.assertEqual(
  1132. sorted(data.keys()),
  1133. ["args", "pagination", "requests", "total_requests"],
  1134. )
  1135. # There are 6 PRs, that's 1 page at 6 results per page
  1136. self.assertEqual(data["pagination"]["pages"], 1)
  1137. @patch("pagure.lib.notify.send_email")
  1138. def test_api_view_user_requests_actionable(self, mockemail):
  1139. """ Test the api_view_user_requests_actionable method of the flask user
  1140. api """
  1141. # First we test without the status parameter. It should default to `open`
  1142. output = self.app.get("/api/0/user/pingou/requests/actionable")
  1143. self.assertEqual(output.status_code, 200)
  1144. data = json.loads(output.get_data(as_text=True))
  1145. self.assertEqual(len(data["requests"]), 2)
  1146. self.assertEqual(
  1147. sorted(data.keys()),
  1148. ["args", "pagination", "requests", "total_requests"],
  1149. )
  1150. self.assertEqual(data["requests"][0]["user"]["name"], "foo")
  1151. self.assertEqual(data["requests"][1]["user"]["name"], "foo")
  1152. self.assertEqual(data["requests"][0]["status"], "Open")
  1153. self.assertEqual(data["requests"][1]["status"], "Open")
  1154. self.assertEqual(
  1155. data["requests"][0]["title"],
  1156. "open pullrequest by user foo on repo test2",
  1157. )
  1158. self.assertEqual(
  1159. data["requests"][1]["title"],
  1160. "open pullrequest by user foo on repo test",
  1161. )
  1162. self.assertEqual(data["args"]["status"], "open")
  1163. self.assertEqual(data["args"]["page"], 1)
  1164. # Next test with the status parameter set to `open`.
  1165. output = self.app.get(
  1166. "/api/0/user/pingou/requests/actionable?status=open"
  1167. )
  1168. self.assertEqual(output.status_code, 200)
  1169. data = json.loads(output.get_data(as_text=True))
  1170. self.assertEqual(len(data["requests"]), 2)
  1171. self.assertEqual(
  1172. sorted(data.keys()),
  1173. ["args", "pagination", "requests", "total_requests"],
  1174. )
  1175. self.assertEqual(data["requests"][0]["user"]["name"], "foo")
  1176. self.assertEqual(data["requests"][1]["user"]["name"], "foo")
  1177. self.assertEqual(data["requests"][0]["status"], "Open")
  1178. self.assertEqual(data["requests"][1]["status"], "Open")
  1179. self.assertEqual(
  1180. data["requests"][0]["title"],
  1181. "open pullrequest by user foo on repo test2",
  1182. )
  1183. self.assertEqual(
  1184. data["requests"][1]["title"],
  1185. "open pullrequest by user foo on repo test",
  1186. )
  1187. self.assertEqual(data["args"]["status"], "open")
  1188. self.assertEqual(data["args"]["page"], 1)
  1189. # Next test with the status parameter set to `closed`.
  1190. output = self.app.get(
  1191. "/api/0/user/pingou/requests/actionable?status=closed"
  1192. )
  1193. self.assertEqual(output.status_code, 200)
  1194. data = json.loads(output.get_data(as_text=True))
  1195. self.assertEqual(len(data["requests"]), 2)
  1196. self.assertEqual(
  1197. sorted(data.keys()),
  1198. ["args", "pagination", "requests", "total_requests"],
  1199. )
  1200. self.assertEqual(data["requests"][0]["user"]["name"], "foo")
  1201. self.assertEqual(data["requests"][1]["user"]["name"], "foo")
  1202. self.assertEqual(data["requests"][0]["status"], "Closed")
  1203. self.assertEqual(data["requests"][1]["status"], "Closed")
  1204. self.assertEqual(
  1205. data["requests"][0]["title"],
  1206. "closed pullrequest by user foo on repo test2",
  1207. )
  1208. self.assertEqual(
  1209. data["requests"][1]["title"],
  1210. "closed pullrequest by user foo on repo test",
  1211. )
  1212. self.assertEqual(data["args"]["status"], "closed")
  1213. self.assertEqual(data["args"]["page"], 1)
  1214. # Next test with the status parameter set to `merged`.
  1215. output = self.app.get(
  1216. "/api/0/user/pingou/requests/actionable?status=merged"
  1217. )
  1218. self.assertEqual(output.status_code, 200)
  1219. data = json.loads(output.get_data(as_text=True))
  1220. self.assertEqual(len(data["requests"]), 2)
  1221. self.assertEqual(
  1222. sorted(data.keys()),
  1223. ["args", "pagination", "requests", "total_requests"],
  1224. )
  1225. self.assertEqual(data["requests"][0]["user"]["name"], "foo")
  1226. self.assertEqual(data["requests"][1]["user"]["name"], "foo")
  1227. self.assertEqual(data["requests"][0]["status"], "Merged")
  1228. self.assertEqual(data["requests"][1]["status"], "Merged")
  1229. self.assertEqual(
  1230. data["requests"][0]["title"],
  1231. "merged pullrequest by user foo on repo test2",
  1232. )
  1233. self.assertEqual(
  1234. data["requests"][1]["title"],
  1235. "merged pullrequest by user foo on repo test",
  1236. )
  1237. self.assertEqual(data["args"]["status"], "merged")
  1238. self.assertEqual(data["args"]["page"], 1)
  1239. # Finally, test with the status parameter set to `all`.
  1240. output = self.app.get(
  1241. "/api/0/user/pingou/requests/actionable?status=all"
  1242. )
  1243. self.assertEqual(output.status_code, 200)
  1244. data = json.loads(output.get_data(as_text=True))
  1245. self.assertEqual(len(data["requests"]), 6)
  1246. self.assertEqual(
  1247. sorted(data.keys()),
  1248. ["args", "pagination", "requests", "total_requests"],
  1249. )
  1250. self.assertEqual(data["requests"][0]["user"]["name"], "foo")
  1251. self.assertEqual(data["requests"][1]["user"]["name"], "foo")
  1252. self.assertEqual(data["requests"][2]["user"]["name"], "foo")
  1253. self.assertEqual(data["requests"][3]["user"]["name"], "foo")
  1254. self.assertEqual(data["requests"][4]["user"]["name"], "foo")
  1255. self.assertEqual(data["requests"][5]["user"]["name"], "foo")
  1256. self.assertEqual(data["requests"][0]["status"], "Merged")
  1257. self.assertEqual(data["requests"][1]["status"], "Merged")
  1258. self.assertEqual(data["requests"][2]["status"], "Closed")
  1259. self.assertEqual(data["requests"][3]["status"], "Closed")
  1260. self.assertEqual(data["requests"][4]["status"], "Open")
  1261. self.assertEqual(data["requests"][5]["status"], "Open")
  1262. self.assertEqual(
  1263. data["requests"][0]["title"],
  1264. "merged pullrequest by user foo on repo test2",
  1265. )
  1266. self.assertEqual(
  1267. data["requests"][1]["title"],
  1268. "merged pullrequest by user foo on repo test",
  1269. )
  1270. self.assertEqual(
  1271. data["requests"][2]["title"],
  1272. "closed pullrequest by user foo on repo test2",
  1273. )
  1274. self.assertEqual(
  1275. data["requests"][3]["title"],
  1276. "closed pullrequest by user foo on repo test",
  1277. )
  1278. self.assertEqual(
  1279. data["requests"][4]["title"],
  1280. "open pullrequest by user foo on repo test2",
  1281. )
  1282. self.assertEqual(
  1283. data["requests"][5]["title"],
  1284. "open pullrequest by user foo on repo test",
  1285. )
  1286. self.assertEqual(data["args"]["status"], "all")
  1287. self.assertEqual(data["args"]["page"], 1)
  1288. # Test page 2 with the status parameter set to `all`.
  1289. output = self.app.get(
  1290. "/api/0/user/pingou/requests/actionable?status=all&page=2"
  1291. )
  1292. self.assertEqual(output.status_code, 200)
  1293. data = json.loads(output.get_data(as_text=True))
  1294. self.assertEqual(len(data["requests"]), 0)
  1295. self.assertEqual(
  1296. sorted(data.keys()),
  1297. ["args", "pagination", "requests", "total_requests"],
  1298. )
  1299. self.assertEqual(data["args"]["page"], 2)
  1300. @patch("pagure.lib.notify.send_email")
  1301. def test_api_view_user_requests_actionable_created(self, mockemail):
  1302. """ Test the api_view_user_requests_filed method of the flask user
  1303. api with the created parameter """
  1304. today = datetime.datetime.utcnow().date()
  1305. output = self.app.get(
  1306. "/api/0/user/pingou/requests/actionable?status=all&created=%s"
  1307. % (today.isoformat())
  1308. )
  1309. self.assertEqual(output.status_code, 200)
  1310. data = json.loads(output.get_data(as_text=True))
  1311. self.assertEqual(len(data["requests"]), 6)
  1312. yesterday = today - datetime.timedelta(days=1)
  1313. output = self.app.get(
  1314. "/api/0/user/pingou/requests/actionable?status=all&created=%s"
  1315. % (yesterday.isoformat())
  1316. )
  1317. self.assertEqual(output.status_code, 200)
  1318. data = json.loads(output.get_data(as_text=True))
  1319. self.assertEqual(len(data["requests"]), 6)
  1320. tomorrow = today + datetime.timedelta(days=1)
  1321. output = self.app.get(
  1322. "/api/0/user/pingou/requests/actionable?status=all&created=%s"
  1323. % (tomorrow.isoformat())
  1324. )
  1325. self.assertEqual(output.status_code, 200)
  1326. data = json.loads(output.get_data(as_text=True))
  1327. self.assertEqual(len(data["requests"]), 0)
  1328. output = self.app.get(
  1329. "/api/0/user/pingou/requests/actionable?status=all&created=..%s"
  1330. % (today.isoformat())
  1331. )
  1332. self.assertEqual(output.status_code, 200)
  1333. data = json.loads(output.get_data(as_text=True))
  1334. self.assertEqual(len(data["requests"]), 0)
  1335. output = self.app.get(
  1336. "/api/0/user/pingou/requests/actionable?status=all&created=..%s"
  1337. % (yesterday.isoformat())
  1338. )
  1339. self.assertEqual(output.status_code, 200)
  1340. data = json.loads(output.get_data(as_text=True))
  1341. self.assertEqual(len(data["requests"]), 0)
  1342. thedaybefore = today - datetime.timedelta(days=1)
  1343. output = self.app.get(
  1344. "/api/0/user/pingou/requests/actionable?status=all&created=..%s"
  1345. % (thedaybefore.isoformat())
  1346. )
  1347. self.assertEqual(output.status_code, 200)
  1348. data = json.loads(output.get_data(as_text=True))
  1349. self.assertEqual(len(data["requests"]), 0)
  1350. output = self.app.get(
  1351. "/api/0/user/pingou/requests/actionable?status=all&created=..%s"
  1352. % (tomorrow.isoformat())
  1353. )
  1354. self.assertEqual(output.status_code, 200)
  1355. data = json.loads(output.get_data(as_text=True))
  1356. self.assertEqual(len(data["requests"]), 6)
  1357. output = self.app.get(
  1358. "/api/0/user/pingou/requests/actionable?status=all&created=%s..%s"
  1359. % (thedaybefore.isoformat(), tomorrow.isoformat())
  1360. )
  1361. self.assertEqual(output.status_code, 200)
  1362. data = json.loads(output.get_data(as_text=True))
  1363. self.assertEqual(len(data["requests"]), 6)
  1364. @patch("pagure.lib.notify.send_email")
  1365. def test_api_view_user_requests_actionable_updated(self, mockemail):
  1366. """ Test the api_view_user_requests_filed method of the flask user
  1367. api with the created parameter """
  1368. today = datetime.datetime.utcnow().date()
  1369. output = self.app.get(
  1370. "/api/0/user/pingou/requests/actionable?status=all&updated=%s"
  1371. % (today.isoformat())
  1372. )
  1373. self.assertEqual(output.status_code, 200)
  1374. data = json.loads(output.get_data(as_text=True))
  1375. self.assertEqual(len(data["requests"]), 0)
  1376. yesterday = today - datetime.timedelta(days=1)
  1377. output = self.app.get(
  1378. "/api/0/user/pingou/requests/actionable?status=all&updated=%s"
  1379. % (yesterday.isoformat())
  1380. )
  1381. self.assertEqual(output.status_code, 200)
  1382. data = json.loads(output.get_data(as_text=True))
  1383. self.assertEqual(len(data["requests"]), 0)
  1384. tomorrow = today + datetime.timedelta(days=1)
  1385. output = self.app.get(
  1386. "/api/0/user/pingou/requests/actionable?status=all&updated=%s"
  1387. % (tomorrow.isoformat())
  1388. )
  1389. self.assertEqual(output.status_code, 200)
  1390. data = json.loads(output.get_data(as_text=True))
  1391. self.assertEqual(len(data["requests"]), 6)
  1392. @patch("pagure.lib.notify.send_email")
  1393. def test_api_view_user_requests_actionable_closed(self, mockemail):
  1394. """ Test the api_view_user_requests_filed method of the flask user
  1395. api with the created parameter """
  1396. today = datetime.datetime.utcnow().date()
  1397. output = self.app.get(
  1398. "/api/0/user/pingou/requests/actionable?status=all&closed=%s"
  1399. % (today.isoformat())
  1400. )
  1401. self.assertEqual(output.status_code, 200)
  1402. data = json.loads(output.get_data(as_text=True))
  1403. self.assertEqual(len(data["requests"]), 0)
  1404. yesterday = today - datetime.timedelta(days=1)
  1405. output = self.app.get(
  1406. "/api/0/user/pingou/requests/actionable?status=all&closed=%s"
  1407. % (yesterday.isoformat())
  1408. )
  1409. self.assertEqual(output.status_code, 200)
  1410. data = json.loads(output.get_data(as_text=True))
  1411. self.assertEqual(len(data["requests"]), 0)
  1412. tomorrow = today + datetime.timedelta(days=1)
  1413. output = self.app.get(
  1414. "/api/0/user/pingou/requests/actionable?status=all&closed=%s"
  1415. % (tomorrow.isoformat())
  1416. )
  1417. self.assertEqual(output.status_code, 200)
  1418. data = json.loads(output.get_data(as_text=True))
  1419. self.assertEqual(len(data["requests"]), 0)
  1420. class PagureFlaskApiUsertestissues(tests.Modeltests):
  1421. """ Tests for the user issues endpoints """
  1422. maxDiff = None
  1423. def setUp(self):
  1424. """ Set up the environnment, ran before every tests. """
  1425. super(PagureFlaskApiUsertestissues, self).setUp()
  1426. pagure.config.config["REQUESTS_FOLDER"] = None
  1427. tests.create_projects(self.session)
  1428. repo = pagure.lib.query._get_project(self.session, "test")
  1429. # Create issues to play with
  1430. msg = pagure.lib.query.new_issue(
  1431. session=self.session,
  1432. repo=repo,
  1433. title="Test issue",
  1434. content="We should work on this",
  1435. user="pingou",
  1436. )
  1437. self.session.commit()
  1438. self.assertEqual(msg.title, "Test issue")
  1439. def test_user_issues_empty(self):
  1440. """ Return the list of issues associated with the specified user. """
  1441. output = self.app.get("/api/0/user/foo/issues")
  1442. self.assertEqual(output.status_code, 200)
  1443. data = json.loads(output.get_data(as_text=True))
  1444. for k in ["pagination_issues_assigned", "pagination_issues_created"]:
  1445. for k2 in ["first", "last"]:
  1446. self.assertIsNotNone(data[k][k2])
  1447. data[k][k2] = None
  1448. self.assertEqual(
  1449. data,
  1450. {
  1451. "args": {
  1452. "assignee": True,
  1453. "author": True,
  1454. "closed": None,
  1455. "created": None,
  1456. "milestones": [],
  1457. "no_stones": None,
  1458. "order": None,
  1459. "order_key": None,
  1460. "page": 1,
  1461. "since": None,
  1462. "status": None,
  1463. "tags": [],
  1464. "updated": None,
  1465. },
  1466. "issues_assigned": [],
  1467. "issues_created": [],
  1468. "pagination_issues_assigned": {
  1469. "first": None,
  1470. "last": None,
  1471. "next": None,
  1472. "page": 1,
  1473. "pages": 0,
  1474. "per_page": 20,
  1475. "prev": None,
  1476. },
  1477. "pagination_issues_created": {
  1478. "first": None,
  1479. "last": None,
  1480. "next": None,
  1481. "page": 1,
  1482. "pages": 0,
  1483. "per_page": 20,
  1484. "prev": None,
  1485. },
  1486. "total_issues_assigned": 0,
  1487. "total_issues_assigned_pages": 1,
  1488. "total_issues_created": 0,
  1489. "total_issues_created_pages": 1,
  1490. },
  1491. )
  1492. def test_user_issues(self):
  1493. """ Return the list of issues associated with the specified user. """
  1494. output = self.app.get("/api/0/user/pingou/issues")
  1495. self.assertEqual(output.status_code, 200)
  1496. data = json.loads(output.get_data(as_text=True))
  1497. issues = []
  1498. for issue in data["issues_created"]:
  1499. issue["date_created"] = "1513111778"
  1500. issue["last_updated"] = "1513111778"
  1501. issue["project"]["date_created"] = "1513111778"
  1502. issue["project"]["date_modified"] = "1513111778"
  1503. issues.append(issue)
  1504. data["issues_created"] = issues
  1505. for k in ["pagination_issues_assigned", "pagination_issues_created"]:
  1506. for k2 in ["first", "last"]:
  1507. self.assertIsNotNone(data[k][k2])
  1508. data[k][k2] = None
  1509. self.assertEqual(
  1510. data,
  1511. {
  1512. "args": {
  1513. "assignee": True,
  1514. "author": True,
  1515. "closed": None,
  1516. "created": None,
  1517. "milestones": [],
  1518. "no_stones": None,
  1519. "order": None,
  1520. "order_key": None,
  1521. "page": 1,
  1522. "since": None,
  1523. "status": None,
  1524. "tags": [],
  1525. "updated": None,
  1526. },
  1527. "issues_assigned": [],
  1528. "issues_created": [
  1529. {
  1530. "assignee": None,
  1531. "blocks": [],
  1532. "close_status": None,
  1533. "closed_at": None,
  1534. "closed_by": None,
  1535. "comments": [],
  1536. "content": "We should work on this",
  1537. "custom_fields": [],
  1538. "date_created": "1513111778",
  1539. "depends": [],
  1540. "id": 1,
  1541. "last_updated": "1513111778",
  1542. "milestone": None,
  1543. "priority": None,
  1544. "private": False,
  1545. "project": {
  1546. "access_groups": {
  1547. "admin": [],
  1548. "commit": [],
  1549. "ticket": [],
  1550. },
  1551. "access_users": {
  1552. "admin": [],
  1553. "commit": [],
  1554. "owner": ["pingou"],
  1555. "ticket": [],
  1556. },
  1557. "close_status": [
  1558. "Invalid",
  1559. "Insufficient data",
  1560. "Fixed",
  1561. "Duplicate",
  1562. ],
  1563. "custom_keys": [],
  1564. "date_created": "1513111778",
  1565. "date_modified": "1513111778",
  1566. "description": "test project #1",
  1567. "fullname": "test",
  1568. "id": 1,
  1569. "milestones": {},
  1570. "name": "test",
  1571. "namespace": None,
  1572. "parent": None,
  1573. "priorities": {},
  1574. "tags": [],
  1575. "url_path": "test",
  1576. "user": {"fullname": "PY C", "name": "pingou"},
  1577. },
  1578. "status": "Open",
  1579. "tags": [],
  1580. "title": "Test issue",
  1581. "user": {"fullname": "PY C", "name": "pingou"},
  1582. }
  1583. ],
  1584. "pagination_issues_assigned": {
  1585. "first": None,
  1586. "last": None,
  1587. "next": None,
  1588. "page": 1,
  1589. "pages": 0,
  1590. "per_page": 20,
  1591. "prev": None,
  1592. },
  1593. "pagination_issues_created": {
  1594. "first": None,
  1595. "last": None,
  1596. "next": None,
  1597. "page": 1,
  1598. "pages": 1,
  1599. "per_page": 20,
  1600. "prev": None,
  1601. },
  1602. "total_issues_assigned": 0,
  1603. "total_issues_assigned_pages": 1,
  1604. "total_issues_created": 1,
  1605. "total_issues_created_pages": 1,
  1606. },
  1607. )
  1608. def test_user_issues_created(self):
  1609. """ Return the list of issues associated with the specified user
  1610. and play with the created filter. """
  1611. today = datetime.datetime.utcnow().date()
  1612. output = self.app.get(
  1613. "/api/0/user/pingou/issues?created=%s" % (today.isoformat())
  1614. )
  1615. self.assertEqual(output.status_code, 200)
  1616. data = json.loads(output.get_data(as_text=True))
  1617. self.assertEqual(data["total_issues_assigned"], 0)
  1618. self.assertEqual(data["total_issues_created"], 1)
  1619. yesterday = today - datetime.timedelta(days=1)
  1620. output = self.app.get(
  1621. "/api/0/user/pingou/issues?created=%s" % (yesterday.isoformat())
  1622. )
  1623. self.assertEqual(output.status_code, 200)
  1624. data = json.loads(output.get_data(as_text=True))
  1625. self.assertEqual(data["total_issues_assigned"], 0)
  1626. self.assertEqual(data["total_issues_created"], 1)
  1627. tomorrow = today + datetime.timedelta(days=1)
  1628. output = self.app.get(
  1629. "/api/0/user/pingou/issues?created=%s" % (tomorrow.isoformat())
  1630. )
  1631. self.assertEqual(output.status_code, 200)
  1632. data = json.loads(output.get_data(as_text=True))
  1633. self.assertEqual(data["total_issues_assigned"], 0)
  1634. self.assertEqual(data["total_issues_created"], 0)
  1635. output = self.app.get(
  1636. "/api/0/user/pingou/issues?created=..%s" % (yesterday.isoformat())
  1637. )
  1638. self.assertEqual(output.status_code, 200)
  1639. data = json.loads(output.get_data(as_text=True))
  1640. self.assertEqual(data["total_issues_assigned"], 0)
  1641. self.assertEqual(data["total_issues_created"], 0)
  1642. output = self.app.get(
  1643. "/api/0/user/pingou/issues?created=%s..%s"
  1644. % (yesterday.isoformat(), today.isoformat())
  1645. )
  1646. self.assertEqual(output.status_code, 200)
  1647. data = json.loads(output.get_data(as_text=True))
  1648. self.assertEqual(data["total_issues_assigned"], 0)
  1649. self.assertEqual(data["total_issues_created"], 0)
  1650. output = self.app.get(
  1651. "/api/0/user/pingou/issues?created=%s..%s"
  1652. % (yesterday.isoformat(), tomorrow.isoformat())
  1653. )
  1654. self.assertEqual(output.status_code, 200)
  1655. data = json.loads(output.get_data(as_text=True))
  1656. self.assertEqual(data["total_issues_assigned"], 0)
  1657. self.assertEqual(data["total_issues_created"], 1)
  1658. if __name__ == "__main__":
  1659. unittest.main(verbosity=2)