__init__.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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 imp
  9. import json
  10. import logging
  11. import os
  12. import re
  13. import resource
  14. import shutil
  15. import subprocess
  16. import sys
  17. import tempfile
  18. import time
  19. import unittest
  20. from io import open, StringIO
  21. logging.basicConfig(stream=sys.stderr)
  22. from bs4 import BeautifulSoup
  23. from contextlib import contextmanager
  24. from datetime import date
  25. from datetime import datetime
  26. from datetime import timedelta
  27. from functools import wraps
  28. from six.moves.urllib.parse import urlparse, parse_qs
  29. import mock
  30. import pygit2
  31. import redis
  32. import six
  33. from bs4 import BeautifulSoup
  34. from celery.app.task import EagerResult
  35. from sqlalchemy import create_engine
  36. from sqlalchemy.orm import sessionmaker
  37. from sqlalchemy.orm import scoped_session
  38. if six.PY2:
  39. # Always enable performance counting for tests
  40. os.environ["PAGURE_PERFREPO"] = "true"
  41. sys.path.insert(
  42. 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
  43. )
  44. import pagure
  45. import pagure.api
  46. from pagure.api.ci import jenkins
  47. import pagure.flask_app
  48. import pagure.lib.git
  49. import pagure.lib.model
  50. import pagure.lib.query
  51. import pagure.lib.tasks_mirror
  52. import pagure.perfrepo as perfrepo
  53. from pagure.config import config as pagure_config, reload_config
  54. from pagure.lib.repo import PagureRepo
  55. HERE = os.path.join(os.path.dirname(os.path.abspath(__file__)))
  56. LOG = logging.getLogger(__name__)
  57. LOG.setLevel(logging.INFO)
  58. PAGLOG = logging.getLogger("pagure")
  59. PAGLOG.setLevel(logging.CRITICAL)
  60. PAGLOG.handlers = []
  61. if "PYTHONPATH" not in os.environ:
  62. os.environ["PYTHONPATH"] = os.path.normpath(os.path.join(HERE, "../"))
  63. CONFIG_TEMPLATE = """
  64. GIT_FOLDER = '%(path)s/repos'
  65. ENABLE_DOCS = %(enable_docs)s
  66. ENABLE_TICKETS = %(enable_tickets)s
  67. REMOTE_GIT_FOLDER = '%(path)s/remotes'
  68. DB_URL = '%(dburl)s'
  69. ALLOW_PROJECT_DOWAIT = True
  70. PAGURE_CI_SERVICES = ['jenkins']
  71. EMAIL_SEND = False
  72. TESTING = True
  73. GIT_FOLDER = '%(path)s/repos'
  74. REQUESTS_FOLDER = '%(path)s/repos/requests'
  75. TICKETS_FOLDER = %(tickets_folder)r
  76. DOCS_FOLDER = %(docs_folder)r
  77. REPOSPANNER_PSEUDO_FOLDER = '%(path)s/repos/pseudo'
  78. ATTACHMENTS_FOLDER = '%(path)s/attachments'
  79. BROKER_URL = 'redis+socket://%(global_path)s/broker'
  80. CELERY_CONFIG = {
  81. "task_always_eager": True,
  82. #"task_eager_propagates": True,
  83. }
  84. GIT_AUTH_BACKEND = '%(authbackend)s'
  85. TEST_AUTH_STATUS = '%(path)s/testauth_status.json'
  86. REPOBRIDGE_BINARY = '%(repobridge_binary)s'
  87. REPOSPANNER_NEW_REPO = %(repospanner_new_repo)s
  88. REPOSPANNER_NEW_REPO_ADMIN_OVERRIDE = %(repospanner_admin_override)s
  89. REPOSPANNER_NEW_FORK = %(repospanner_new_fork)s
  90. REPOSPANNER_ADMIN_MIGRATION = %(repospanner_admin_migration)s
  91. REPOSPANNER_REGIONS = {
  92. 'default': {'url': 'https://repospanner.localhost.localdomain:%(repospanner_gitport)s',
  93. 'repo_prefix': 'pagure/',
  94. 'hook': None,
  95. 'ca': '%(path)s/repospanner/pki/ca.crt',
  96. 'admin_cert': {'cert': '%(path)s/repospanner/pki/admin.crt',
  97. 'key': '%(path)s/repospanner/pki/admin.key'},
  98. 'push_cert': {'cert': '%(path)s/repospanner/pki/pagure.crt',
  99. 'key': '%(path)s/repospanner/pki/pagure.key'}}
  100. }
  101. """
  102. # The Celery docs warn against using task_always_eager:
  103. # http://docs.celeryproject.org/en/latest/userguide/testing.html
  104. # but that warning is only valid when testing the async nature of the task, not
  105. # what the task actually does.
  106. LOG.info("BUILD_ID: %s", os.environ.get("BUILD_ID"))
  107. WAIT_REGEX = re.compile(r"""var _url = '(\/wait\/[a-z0-9-]+\??.*)'""")
  108. def get_wait_target(html):
  109. """ This parses the window.location out of the HTML for the wait page. """
  110. found = WAIT_REGEX.findall(html)
  111. if len(found) == 0:
  112. raise Exception("Not able to get wait target in %s" % html)
  113. return found[-1]
  114. def get_post_target(html):
  115. """ This parses the wait page form to get the POST url. """
  116. soup = BeautifulSoup(html, "html.parser")
  117. form = soup.find(id="waitform")
  118. if not form:
  119. raise Exception("Not able to get the POST url in %s" % html)
  120. return form.get("action")
  121. def get_post_args(html):
  122. """ This parses the wait page for the hidden arguments of the form. """
  123. soup = BeautifulSoup(html, "html.parser")
  124. output = {}
  125. inputs = soup.find_all("input")
  126. if not inputs:
  127. raise Exception("Not able to get the POST arguments in %s" % html)
  128. for inp in inputs:
  129. if inp.get("type") == "hidden":
  130. output[inp.get("name")] = inp.get("value")
  131. return output
  132. def create_maybe_waiter(method, getter):
  133. def maybe_waiter(*args, **kwargs):
  134. """ A wrapper for self.app.get()/.post() that will resolve wait's """
  135. result = method(*args, **kwargs)
  136. # Handle the POST wait case
  137. form_url = None
  138. form_args = None
  139. try:
  140. result_text = result.get_data(as_text=True)
  141. except UnicodeDecodeError:
  142. return result
  143. if 'id="waitform"' in result_text:
  144. form_url = get_post_target(result_text)
  145. form_args = get_post_args(result_text)
  146. form_args["csrf_token"] = result_text.split(
  147. 'name="csrf_token" type="hidden" value="'
  148. )[1].split('">')[0]
  149. count = 0
  150. while "We are waiting for your task to finish." in result_text:
  151. # Resolve wait page
  152. target_url = get_wait_target(result_text)
  153. if count > 10:
  154. time.sleep(0.5)
  155. else:
  156. time.sleep(0.1)
  157. result = getter(target_url, follow_redirects=True)
  158. try:
  159. result_text = result.get_data(as_text=True)
  160. except UnicodeDecodeError:
  161. return result
  162. if count > 50:
  163. raise Exception("Had to wait too long")
  164. else:
  165. if form_url and form_args:
  166. return method(form_url, data=form_args, follow_redirects=True)
  167. return result
  168. return maybe_waiter
  169. @contextmanager
  170. def user_set(APP, user, keep_get_user=False):
  171. """ Set the provided user as fas_user in the provided application."""
  172. # Hack used to remove the before_request function set by
  173. # flask.ext.fas_openid.FAS which otherwise kills our effort to set a
  174. # flask.g.fas_user.
  175. from flask import appcontext_pushed, g
  176. keep = []
  177. for meth in APP.before_request_funcs[None]:
  178. if "flask_fas_openid.FAS" in str(meth):
  179. continue
  180. keep.append(meth)
  181. APP.before_request_funcs[None] = keep
  182. def handler(sender, **kwargs):
  183. g.fas_user = user
  184. g.fas_session_id = b"123"
  185. g.authenticated = True
  186. old_get_user = pagure.flask_app._get_user
  187. if not keep_get_user:
  188. pagure.flask_app._get_user = mock.MagicMock(
  189. return_value=pagure.lib.model.User()
  190. )
  191. with appcontext_pushed.connected_to(handler, APP):
  192. yield
  193. pagure.flask_app._get_user = old_get_user
  194. tests_state = {
  195. "path": tempfile.mkdtemp(prefix="pagure-tests-"),
  196. "broker": None,
  197. "broker_client": None,
  198. "results": {},
  199. }
  200. def create_user(session, username, fullname, emails):
  201. """ Create an user with the provided information.
  202. Note that `emails` should be a list of emails.
  203. """
  204. user = pagure.lib.model.User(
  205. user=username,
  206. fullname=fullname,
  207. password=b"foo",
  208. default_email=emails[0],
  209. )
  210. session.add(user)
  211. session.flush()
  212. for email in emails:
  213. item = pagure.lib.model.UserEmail(user_id=user.id, email=email)
  214. session.add(item)
  215. session.commit()
  216. def _populate_db(session):
  217. # Create a couple of users
  218. create_user(
  219. session, "pingou", "PY C", ["bar@pingou.com", "foo@pingou.com"]
  220. )
  221. create_user(session, "foo", "foo bar", ["foo@bar.com"])
  222. def store_eager_results(*args, **kwargs):
  223. """A wrapper for EagerResult that stores the instance."""
  224. result = EagerResult(*args, **kwargs)
  225. tests_state["results"][result.id] = result
  226. return result
  227. def setUp():
  228. # In order to save time during local test execution, we create sqlite DB
  229. # file only once and then we populate it and empty it for every test case
  230. # (as opposed to creating DB file for every test case).
  231. session = pagure.lib.model.create_tables(
  232. "sqlite:///%s/db.sqlite" % tests_state["path"],
  233. acls=pagure_config.get("ACLS", {}),
  234. )
  235. tests_state["db_session"] = session
  236. # Create a broker
  237. broker_url = os.path.join(tests_state["path"], "broker")
  238. tests_state["broker"] = broker = subprocess.Popen(
  239. [
  240. "/usr/bin/redis-server",
  241. "--unixsocket",
  242. broker_url,
  243. "--port",
  244. "0",
  245. "--loglevel",
  246. "warning",
  247. "--logfile",
  248. "/dev/null",
  249. ],
  250. stdout=None,
  251. stderr=None,
  252. )
  253. broker.poll()
  254. if broker.returncode is not None:
  255. raise Exception("Broker failed to start")
  256. tests_state["broker_client"] = redis.Redis(unix_socket_path=broker_url)
  257. # Store the EagerResults to be able to retrieve them later
  258. tests_state["eg_patcher"] = mock.patch("celery.app.task.EagerResult")
  259. eg_mock = tests_state["eg_patcher"].start()
  260. eg_mock.side_effect = store_eager_results
  261. def tearDown():
  262. tests_state["db_session"].close()
  263. tests_state["eg_patcher"].stop()
  264. broker = tests_state["broker"]
  265. broker.kill()
  266. broker.wait()
  267. shutil.rmtree(tests_state["path"])
  268. class SimplePagureTest(unittest.TestCase):
  269. """
  270. Simple Test class that does not set a broker/worker
  271. """
  272. populate_db = True
  273. config_values = {}
  274. @mock.patch("pagure.lib.notify.fedmsg_publish", mock.MagicMock())
  275. def __init__(self, method_name="runTest"):
  276. """ Constructor. """
  277. unittest.TestCase.__init__(self, method_name)
  278. self.session = None
  279. self.path = None
  280. self.gitrepo = None
  281. self.gitrepos = None
  282. def perfMaxWalks(self, max_walks, max_steps):
  283. """ Check that we have not performed too many walks/steps. """
  284. num_walks = 0
  285. num_steps = 0
  286. for reqstat in perfrepo.REQUESTS:
  287. for walk in reqstat["walks"].values():
  288. num_walks += 1
  289. num_steps += walk["steps"]
  290. self.assertLessEqual(
  291. num_walks,
  292. max_walks,
  293. "%s git repo walks performed, at most %s allowed"
  294. % (num_walks, max_walks),
  295. )
  296. self.assertLessEqual(
  297. num_steps,
  298. max_steps,
  299. "%s git repo steps performed, at most %s allowed"
  300. % (num_steps, max_steps),
  301. )
  302. def perfReset(self):
  303. """ Reset perfrepo stats. """
  304. perfrepo.reset_stats()
  305. perfrepo.REQUESTS = []
  306. def setUp(self):
  307. if self.path:
  308. # This prevents test state leakage.
  309. # This should be None if the previous runs' tearDown didn't finish,
  310. # leaving behind a self.path.
  311. # If we continue in this case, not only did the previous worker and
  312. # redis instances not exit, we also might accidentally use the
  313. # old database connection.
  314. # @pingou, don't delete this again... :)
  315. raise Exception("Previous test failed!")
  316. self.perfReset()
  317. self.path = tempfile.mkdtemp(prefix="pagure-tests-path-")
  318. LOG.debug("Testdir: %s", self.path)
  319. for folder in ["repos", "forks", "releases", "remotes", "attachments"]:
  320. os.mkdir(os.path.join(self.path, folder))
  321. if hasattr(pagure.lib.query, "REDIS") and pagure.lib.query.REDIS:
  322. pagure.lib.query.REDIS.connection_pool.disconnect()
  323. pagure.lib.query.REDIS = None
  324. # Database
  325. self._prepare_db()
  326. # Write a config file
  327. config_values = {
  328. "path": self.path,
  329. "dburl": self.dbpath,
  330. "enable_docs": True,
  331. "docs_folder": "%s/repos/docs" % self.path,
  332. "enable_tickets": True,
  333. "tickets_folder": "%s/repos/tickets" % self.path,
  334. "global_path": tests_state["path"],
  335. "authbackend": "gitolite3",
  336. "repobridge_binary": "/usr/libexec/repobridge",
  337. "repospanner_gitport": str(8443 + sys.version_info.major),
  338. "repospanner_new_repo": "None",
  339. "repospanner_admin_override": "False",
  340. "repospanner_new_fork": "True",
  341. "repospanner_admin_migration": "False",
  342. }
  343. config_values.update(self.config_values)
  344. self.config_values = config_values
  345. config_path = os.path.join(self.path, "config")
  346. if not os.path.exists(config_path):
  347. with open(config_path, "w") as f:
  348. f.write(CONFIG_TEMPLATE % self.config_values)
  349. os.environ["PAGURE_CONFIG"] = config_path
  350. pagure_config.update(reload_config())
  351. imp.reload(pagure.lib.tasks)
  352. imp.reload(pagure.lib.tasks_mirror)
  353. imp.reload(pagure.lib.tasks_services)
  354. self._app = pagure.flask_app.create_app({"DB_URL": self.dbpath})
  355. self.app = self._app.test_client()
  356. self.gr_patcher = mock.patch("pagure.lib.tasks.get_result")
  357. gr_mock = self.gr_patcher.start()
  358. gr_mock.side_effect = lambda tid: tests_state["results"][tid]
  359. # Refresh the DB session
  360. self.session = pagure.lib.query.create_session(self.dbpath)
  361. def tearDown(self):
  362. self.gr_patcher.stop()
  363. self.session.rollback()
  364. self._clear_database()
  365. # Remove testdir
  366. try:
  367. shutil.rmtree(self.path)
  368. except:
  369. # Sometimes there is a race condition that makes deleting the folder
  370. # fail during the first attempt. So just try a second time if that's
  371. # the case.
  372. shutil.rmtree(self.path)
  373. self.path = None
  374. del self.app
  375. del self._app
  376. def shortDescription(self):
  377. doc = self.__str__() + ": " + self._testMethodDoc
  378. return doc or None
  379. def _prepare_db(self):
  380. self.dbpath = "sqlite:///%s" % os.path.join(
  381. tests_state["path"], "db.sqlite"
  382. )
  383. self.session = tests_state["db_session"]
  384. pagure.lib.model.create_default_status(
  385. self.session, acls=pagure_config.get("ACLS", {})
  386. )
  387. if self.populate_db:
  388. _populate_db(self.session)
  389. def _clear_database(self):
  390. tables = reversed(pagure.lib.model_base.BASE.metadata.sorted_tables)
  391. if self.dbpath.startswith("postgresql"):
  392. self.session.execute(
  393. "TRUNCATE %s CASCADE" % ", ".join([t.name for t in tables])
  394. )
  395. elif self.dbpath.startswith("sqlite"):
  396. for table in tables:
  397. self.session.execute("DELETE FROM %s" % table.name)
  398. elif self.dbpath.startswith("mysql"):
  399. self.session.execute("SET FOREIGN_KEY_CHECKS = 0")
  400. for table in tables:
  401. self.session.execute("TRUNCATE %s" % table.name)
  402. self.session.execute("SET FOREIGN_KEY_CHECKS = 1")
  403. self.session.commit()
  404. def set_auth_status(self, value):
  405. """ Set the return value for the test auth """
  406. with open(
  407. os.path.join(self.path, "testauth_status.json"), "w"
  408. ) as statusfile:
  409. statusfile.write(six.u(json.dumps(value)))
  410. def get_csrf(self, url="/new", output=None):
  411. """Retrieve a CSRF token from given URL."""
  412. if output is None:
  413. output = self.app.get(url)
  414. self.assertEqual(output.status_code, 200)
  415. return (
  416. output.get_data(as_text=True)
  417. .split('name="csrf_token" type="hidden" value="')[1]
  418. .split('">')[0]
  419. )
  420. def get_wtforms_version(self):
  421. """Returns the wtforms version as a tuple."""
  422. import wtforms
  423. wtforms_v = wtforms.__version__.split(".")
  424. for idx, val in enumerate(wtforms_v):
  425. try:
  426. val = int(val)
  427. except ValueError:
  428. pass
  429. wtforms_v[idx] = val
  430. return tuple(wtforms_v)
  431. def get_arrow_version(self):
  432. """ Returns the arrow version as a tuple."""
  433. import arrow
  434. arrow_v = arrow.__version__.split(".")
  435. for idx, val in enumerate(arrow_v):
  436. try:
  437. val = int(val)
  438. except ValueError:
  439. pass
  440. arrow_v[idx] = val
  441. return tuple(arrow_v)
  442. def assertURLEqual(self, url_1, url_2):
  443. url_parsed_1 = list(urlparse(url_1))
  444. url_parsed_1[4] = parse_qs(url_parsed_1[4])
  445. url_parsed_2 = list(urlparse(url_2))
  446. url_parsed_2[4] = parse_qs(url_parsed_2[4])
  447. return self.assertListEqual(url_parsed_1, url_parsed_2)
  448. def assertJSONEqual(self, json_1, json_2):
  449. return self.assertEqual(json.loads(json_1), json.loads(json_2))
  450. class Modeltests(SimplePagureTest):
  451. """ Model tests. """
  452. def setUp(self): # pylint: disable=invalid-name
  453. """ Set up the environnment, ran before every tests. """
  454. # Clean up test performance info
  455. super(Modeltests, self).setUp()
  456. self.app.get = create_maybe_waiter(self.app.get, self.app.get)
  457. self.app.post = create_maybe_waiter(self.app.post, self.app.get)
  458. # Refresh the DB session
  459. self.session = pagure.lib.query.create_session(self.dbpath)
  460. def tearDown(self): # pylint: disable=invalid-name
  461. """ Remove the test.db database if there is one. """
  462. tests_state["broker_client"].flushall()
  463. super(Modeltests, self).tearDown()
  464. def create_project_full(self, projectname, extra=None):
  465. """ Create a project via the API.
  466. This makes sure that the repo is fully setup the way a normal new
  467. project would be, with hooks and all setup.
  468. """
  469. headers = {"Authorization": "token aaabbbcccddd"}
  470. data = {"name": projectname, "description": "A test repo"}
  471. if extra:
  472. data.update(extra)
  473. # Valid request
  474. output = self.app.post("/api/0/new/", data=data, headers=headers)
  475. self.assertEqual(output.status_code, 200)
  476. data = json.loads(output.get_data(as_text=True))
  477. self.assertDictEqual(
  478. data, {"message": 'Project "%s" created' % projectname}
  479. )
  480. class FakeGroup(object): # pylint: disable=too-few-public-methods
  481. """ Fake object used to make the FakeUser object closer to the
  482. expectations.
  483. """
  484. def __init__(self, name):
  485. """ Constructor.
  486. :arg name: the name given to the name attribute of this object.
  487. """
  488. self.name = name
  489. self.group_type = "cla"
  490. class FakeUser(object): # pylint: disable=too-few-public-methods
  491. """ Fake user used to test the fedocallib library. """
  492. def __init__(
  493. self, groups=None, username="username", cla_done=True, id=None
  494. ):
  495. """ Constructor.
  496. :arg groups: list of the groups in which this fake user is
  497. supposed to be.
  498. """
  499. if isinstance(groups, six.string_types):
  500. groups = [groups]
  501. self.id = id
  502. self.groups = groups or []
  503. self.user = username
  504. self.username = username
  505. self.name = username
  506. self.email = "foo@bar.com"
  507. self.default_email = "foo@bar.com"
  508. self.approved_memberships = [
  509. FakeGroup("packager"),
  510. FakeGroup("design-team"),
  511. ]
  512. self.dic = {}
  513. self.dic["timezone"] = "Europe/Paris"
  514. self.login_time = datetime.utcnow()
  515. self.cla_done = cla_done
  516. def __getitem__(self, key):
  517. return self.dic[key]
  518. def create_locks(session, project):
  519. for ltype in ("WORKER", "WORKER_TICKET", "WORKER_REQUEST"):
  520. lock = pagure.lib.model.ProjectLock(
  521. project_id=project.id, lock_type=ltype
  522. )
  523. session.add(lock)
  524. def create_projects(session, is_fork=False, user_id=1, hook_token_suffix=""):
  525. """ Create some projects in the database. """
  526. item = pagure.lib.model.Project(
  527. user_id=user_id, # pingou
  528. name="test",
  529. is_fork=is_fork,
  530. parent_id=1 if is_fork else None,
  531. description="test project #1",
  532. hook_token="aaabbbccc" + hook_token_suffix,
  533. )
  534. item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
  535. session.add(item)
  536. session.flush()
  537. create_locks(session, item)
  538. item = pagure.lib.model.Project(
  539. user_id=user_id, # pingou
  540. name="test2",
  541. is_fork=is_fork,
  542. parent_id=2 if is_fork else None,
  543. description="test project #2",
  544. hook_token="aaabbbddd" + hook_token_suffix,
  545. )
  546. item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
  547. session.add(item)
  548. session.flush()
  549. create_locks(session, item)
  550. item = pagure.lib.model.Project(
  551. user_id=user_id, # pingou
  552. name="test3",
  553. is_fork=is_fork,
  554. parent_id=3 if is_fork else None,
  555. description="namespaced test project",
  556. hook_token="aaabbbeee" + hook_token_suffix,
  557. namespace="somenamespace",
  558. )
  559. item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
  560. session.add(item)
  561. session.flush()
  562. create_locks(session, item)
  563. session.commit()
  564. def create_projects_git(folder, bare=False):
  565. """ Create some projects in the database. """
  566. repos = []
  567. for project in [
  568. "test.git",
  569. "test2.git",
  570. os.path.join("somenamespace", "test3.git"),
  571. ]:
  572. repo_path = os.path.join(folder, project)
  573. repos.append(repo_path)
  574. if not os.path.exists(repo_path):
  575. os.makedirs(repo_path)
  576. pygit2.init_repository(repo_path, bare=bare)
  577. return repos
  578. def create_tokens(session, user_id=1, project_id=1, suffix=None):
  579. """ Create some tokens for the project in the database. """
  580. token = "aaabbbcccddd"
  581. if suffix:
  582. token += suffix
  583. item = pagure.lib.model.Token(
  584. id=token,
  585. user_id=user_id,
  586. project_id=project_id,
  587. expiration=datetime.utcnow() + timedelta(days=30),
  588. )
  589. session.add(item)
  590. token = "foo_token"
  591. if suffix:
  592. token += suffix
  593. item = pagure.lib.model.Token(
  594. id=token,
  595. user_id=user_id,
  596. project_id=project_id,
  597. expiration=datetime.utcnow() + timedelta(days=30),
  598. )
  599. session.add(item)
  600. token = "expired_token"
  601. if suffix:
  602. token += suffix
  603. item = pagure.lib.model.Token(
  604. id=token,
  605. user_id=user_id,
  606. project_id=project_id,
  607. expiration=datetime.utcnow() - timedelta(days=1),
  608. )
  609. session.add(item)
  610. session.commit()
  611. def create_tokens_acl(session, token_id="aaabbbcccddd", acl_name=None):
  612. """ Create some ACLs for the token. If acl_name is not set, the token will
  613. have all the ACLs enabled.
  614. """
  615. if acl_name is None:
  616. for aclid in range(len(pagure_config["ACLS"])):
  617. token_acl = pagure.lib.model.TokenAcl(
  618. token_id=token_id, acl_id=aclid + 1
  619. )
  620. session.add(token_acl)
  621. else:
  622. acl = (
  623. session.query(pagure.lib.model.ACL).filter_by(name=acl_name).one()
  624. )
  625. token_acl = pagure.lib.model.TokenAcl(token_id=token_id, acl_id=acl.id)
  626. session.add(token_acl)
  627. session.commit()
  628. def _clone_and_top_commits(folder, branch, branch_ref=False):
  629. """ Clone the repository, checkout the specified branch and return
  630. the top commit of that branch if there is one.
  631. Returns the repo, the path to the clone and the top commit(s) in a tuple
  632. or the repo, the path to the clone and the reference to the branch
  633. object if branch_ref is True.
  634. """
  635. if not os.path.exists(folder):
  636. os.makedirs(folder)
  637. brepo = pygit2.init_repository(folder, bare=True)
  638. newfolder = tempfile.mkdtemp(prefix="pagure-tests")
  639. repo = pygit2.clone_repository(folder, newfolder)
  640. branch_ref_obj = None
  641. if "origin/%s" % branch in repo.listall_branches(pygit2.GIT_BRANCH_ALL):
  642. branch_ref_obj = pagure.lib.git.get_branch_ref(repo, branch)
  643. repo.checkout(branch_ref_obj)
  644. if branch_ref:
  645. return (repo, newfolder, branch_ref_obj)
  646. parents = []
  647. commit = None
  648. try:
  649. if branch_ref_obj:
  650. commit = repo[branch_ref_obj.peel().hex]
  651. else:
  652. commit = repo.revparse_single("HEAD")
  653. except KeyError:
  654. pass
  655. if commit:
  656. parents = [commit.oid.hex]
  657. return (repo, newfolder, parents)
  658. def add_content_git_repo(folder, branch="master", append=None):
  659. """ Create some content for the specified git repo. """
  660. repo, newfolder, parents = _clone_and_top_commits(folder, branch)
  661. # Create a file in that git repo
  662. filename = os.path.join(newfolder, "sources")
  663. content = "foo\n bar"
  664. if os.path.exists(filename):
  665. content = "foo\n bar\nbaz"
  666. if append:
  667. content += append
  668. with open(filename, "w") as stream:
  669. stream.write(content)
  670. repo.index.add("sources")
  671. repo.index.write()
  672. # Commits the files added
  673. tree = repo.index.write_tree()
  674. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  675. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  676. commit = repo.create_commit(
  677. "refs/heads/%s" % branch, # the name of the reference to update
  678. author,
  679. committer,
  680. "Add sources file for testing",
  681. # binary string representing the tree object ID
  682. tree,
  683. # list of binary strings representing parents of the new commit
  684. parents,
  685. )
  686. if commit:
  687. parents = [commit.hex]
  688. subfolder = os.path.join("folder1", "folder2")
  689. if not os.path.exists(os.path.join(newfolder, subfolder)):
  690. os.makedirs(os.path.join(newfolder, subfolder))
  691. # Create a file in that git repo
  692. with open(os.path.join(newfolder, subfolder, "file"), "w") as stream:
  693. stream.write("foo\n bar\nbaz")
  694. repo.index.add(os.path.join(subfolder, "file"))
  695. with open(os.path.join(newfolder, subfolder, "fileŠ"), "w") as stream:
  696. stream.write("foo\n bar\nbaz")
  697. repo.index.add(os.path.join(subfolder, "fileŠ"))
  698. repo.index.write()
  699. # Commits the files added
  700. tree = repo.index.write_tree()
  701. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  702. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  703. commit = repo.create_commit(
  704. "refs/heads/%s" % branch, # the name of the reference to update
  705. author,
  706. committer,
  707. "Add some directory and a file for more testing",
  708. # binary string representing the tree object ID
  709. tree,
  710. # list of binary strings representing parents of the new commit
  711. parents,
  712. )
  713. # Push to origin
  714. ori_remote = repo.remotes[0]
  715. master_ref = repo.lookup_reference(
  716. "HEAD" if branch == "master" else "refs/heads/%s" % branch
  717. ).resolve()
  718. refname = "%s:%s" % (master_ref.name, master_ref.name)
  719. PagureRepo.push(ori_remote, refname)
  720. shutil.rmtree(newfolder)
  721. def add_readme_git_repo(folder, readme_name="README.rst", branch="master"):
  722. """ Create a README file for the specified git repo. """
  723. repo, newfolder, parents = _clone_and_top_commits(folder, branch)
  724. if readme_name == "README.rst":
  725. content = """Pagure
  726. ======
  727. :Author: Pierre-Yves Chibon <pingou@pingoured.fr>
  728. Pagure is a light-weight git-centered forge based on pygit2.
  729. Currently, Pagure offers a web-interface for git repositories, a ticket
  730. system and possibilities to create new projects, fork existing ones and
  731. create/merge pull-requests across or within projects.
  732. Homepage: https://github.com/pypingou/pagure
  733. Dev instance: http://209.132.184.222/ (/!\\ May change unexpectedly, it's a dev instance ;-))
  734. """
  735. else:
  736. content = (
  737. """Pagure
  738. ======
  739. This is a placeholder """
  740. + readme_name
  741. + """
  742. that should never get displayed on the website if there is a README.rst in the repo.
  743. """
  744. )
  745. # Create a file in that git repo
  746. with open(os.path.join(newfolder, readme_name), "w") as stream:
  747. stream.write(content)
  748. repo.index.add(readme_name)
  749. repo.index.write()
  750. # Commits the files added
  751. tree = repo.index.write_tree()
  752. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  753. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  754. branch_ref = "refs/heads/%s" % branch
  755. repo.create_commit(
  756. branch_ref, # the name of the reference to update
  757. author,
  758. committer,
  759. "Add a README file",
  760. # binary string representing the tree object ID
  761. tree,
  762. # list of binary strings representing parents of the new commit
  763. parents,
  764. )
  765. # Push to origin
  766. ori_remote = repo.remotes[0]
  767. PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref))
  768. shutil.rmtree(newfolder)
  769. def add_commit_git_repo(
  770. folder, ncommits=10, filename="sources", branch="master", symlink_to=None
  771. ):
  772. """ Create some more commits for the specified git repo. """
  773. repo, newfolder, branch_ref_obj = _clone_and_top_commits(
  774. folder, branch, branch_ref=True
  775. )
  776. for index in range(ncommits):
  777. # Create a file in that git repo
  778. if symlink_to:
  779. os.symlink(symlink_to, os.path.join(newfolder, filename))
  780. else:
  781. with open(os.path.join(newfolder, filename), "a") as stream:
  782. stream.write("Row %s\n" % index)
  783. repo.index.add(filename)
  784. repo.index.write()
  785. parents = []
  786. commit = None
  787. try:
  788. if branch_ref_obj:
  789. commit = repo[branch_ref_obj.peel().hex]
  790. else:
  791. commit = repo.revparse_single("HEAD")
  792. except (KeyError, AttributeError):
  793. pass
  794. if commit:
  795. parents = [commit.oid.hex]
  796. # Commits the files added
  797. tree = repo.index.write_tree()
  798. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  799. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  800. branch_ref = "refs/heads/%s" % branch
  801. repo.create_commit(
  802. branch_ref,
  803. author,
  804. committer,
  805. "Add row %s to %s file" % (index, filename),
  806. # binary string representing the tree object ID
  807. tree,
  808. # list of binary strings representing parents of the new commit
  809. parents,
  810. )
  811. branch_ref_obj = pagure.lib.git.get_branch_ref(repo, branch)
  812. # Push to origin
  813. ori_remote = repo.remotes[0]
  814. PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref))
  815. shutil.rmtree(newfolder)
  816. def add_tag_git_repo(folder, tagname, obj_hash, message):
  817. """ Add a tag to the given object of the given repo annotated by given message. """
  818. repo, newfolder, branch_ref_obj = _clone_and_top_commits(
  819. folder, "master", branch_ref=True
  820. )
  821. tag_sha = repo.create_tag(
  822. tagname,
  823. obj_hash,
  824. repo.get(obj_hash).type,
  825. pygit2.Signature("Alice Author", "alice@authors.tld"),
  826. message,
  827. )
  828. # Push to origin
  829. ori_remote = repo.remotes[0]
  830. PagureRepo.push(
  831. ori_remote, "refs/tags/%s:refs/tags/%s" % (tagname, tagname)
  832. )
  833. shutil.rmtree(newfolder)
  834. return tag_sha
  835. def add_content_to_git(
  836. folder,
  837. branch="master",
  838. filename="sources",
  839. content="foo",
  840. message=None,
  841. author=("Alice Author", "alice@authors.tld"),
  842. commiter=("Cecil Committer", "cecil@committers.tld"),
  843. ):
  844. """ Create some more commits for the specified git repo. """
  845. repo, newfolder, branch_ref_obj = _clone_and_top_commits(
  846. folder, branch, branch_ref=True
  847. )
  848. # Create a file in that git repo
  849. with open(
  850. os.path.join(newfolder, filename), "a", encoding="utf-8"
  851. ) as stream:
  852. stream.write("%s\n" % content)
  853. repo.index.add(filename)
  854. repo.index.write()
  855. parents = []
  856. commit = None
  857. try:
  858. if branch_ref_obj:
  859. commit = repo[branch_ref_obj.peel().hex]
  860. else:
  861. commit = repo.revparse_single("HEAD")
  862. except (KeyError, AttributeError):
  863. pass
  864. if commit:
  865. parents = [commit.oid.hex]
  866. # Commits the files added
  867. tree = repo.index.write_tree()
  868. author = pygit2.Signature(*author)
  869. committer = pygit2.Signature(*commiter)
  870. branch_ref = "refs/heads/%s" % branch
  871. message = message or "Add content to file %s" % (filename)
  872. repo.create_commit(
  873. branch_ref, # the name of the reference to update
  874. author,
  875. committer,
  876. message,
  877. # binary string representing the tree object ID
  878. tree,
  879. # list of binary strings representing parents of the new commit
  880. parents,
  881. )
  882. # Push to origin
  883. ori_remote = repo.remotes[0]
  884. PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref))
  885. shutil.rmtree(newfolder)
  886. def add_binary_git_repo(folder, filename):
  887. """ Create a fake image file for the specified git repo. """
  888. repo, newfolder, parents = _clone_and_top_commits(folder, "master")
  889. content = b"""\x00\x00\x01\x00\x01\x00\x18\x18\x00\x00\x01\x00 \x00\x88
  890. \t\x00\x00\x16\x00\x00\x00(\x00\x00\x00\x18\x00x00\x00\x01\x00 \x00\x00\x00
  891. \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
  892. 00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa7lM\x01\xa6kM\t\xa6kM\x01
  893. \xa4fF\x04\xa2dE\x95\xa2cD8\xa1a
  894. """
  895. # Create a file in that git repo
  896. with open(os.path.join(newfolder, filename), "wb") as stream:
  897. stream.write(content)
  898. repo.index.add(filename)
  899. repo.index.write()
  900. # Commits the files added
  901. tree = repo.index.write_tree()
  902. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  903. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  904. repo.create_commit(
  905. "refs/heads/master", # the name of the reference to update
  906. author,
  907. committer,
  908. "Add a fake image file",
  909. # binary string representing the tree object ID
  910. tree,
  911. # list of binary strings representing parents of the new commit
  912. parents,
  913. )
  914. # Push to origin
  915. ori_remote = repo.remotes[0]
  916. master_ref = repo.lookup_reference("HEAD").resolve()
  917. refname = "%s:%s" % (master_ref.name, master_ref.name)
  918. PagureRepo.push(ori_remote, refname)
  919. shutil.rmtree(newfolder)
  920. def remove_file_git_repo(folder, filename, branch="master"):
  921. """ Delete the specified file on the give git repo and branch. """
  922. repo, newfolder, parents = _clone_and_top_commits(folder, branch)
  923. # Remove file
  924. repo.index.remove(filename)
  925. # Write the change and commit it
  926. tree = repo.index.write_tree()
  927. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  928. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  929. branch_ref = "refs/heads/%s" % branch
  930. repo.create_commit(
  931. branch_ref, # the name of the reference to update
  932. author,
  933. committer,
  934. "Remove file %s" % filename,
  935. # binary string representing the tree object ID
  936. tree,
  937. # list of binary strings representing parents of the new commit
  938. parents,
  939. )
  940. # Push to origin
  941. ori_remote = repo.remotes[0]
  942. PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref))
  943. shutil.rmtree(newfolder)
  944. def add_pull_request_git_repo(
  945. folder,
  946. session,
  947. repo,
  948. fork,
  949. branch_from="feature",
  950. user="pingou",
  951. allow_rebase=False,
  952. ):
  953. """ Set up the git repo and create the corresponding PullRequest
  954. object.
  955. """
  956. # Clone the main repo
  957. gitrepo = os.path.join(folder, "repos", repo.path)
  958. newpath = tempfile.mkdtemp(prefix="pagure-fork-test")
  959. repopath = os.path.join(newpath, "test")
  960. clone_repo = pygit2.clone_repository(gitrepo, repopath)
  961. # Create a file in that git repo
  962. with open(os.path.join(repopath, "sources"), "w") as stream:
  963. stream.write("foo\n bar")
  964. clone_repo.index.add("sources")
  965. clone_repo.index.write()
  966. # Commits the files added
  967. tree = clone_repo.index.write_tree()
  968. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  969. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  970. clone_repo.create_commit(
  971. "refs/heads/master", # the name of the reference to update
  972. author,
  973. committer,
  974. "Add sources file for testing",
  975. # binary string representing the tree object ID
  976. tree,
  977. # list of binary strings representing parents of the new commit
  978. [],
  979. )
  980. refname = "refs/heads/master:refs/heads/master"
  981. ori_remote = clone_repo.remotes[0]
  982. PagureRepo.push(ori_remote, refname)
  983. first_commit = clone_repo.revparse_single("HEAD")
  984. # Set the second repo
  985. repopath = os.path.join(folder, "repos", fork.path)
  986. new_gitrepo = os.path.join(newpath, "fork_test")
  987. clone_repo = pygit2.clone_repository(repopath, new_gitrepo)
  988. # Add the main project as remote repo
  989. upstream_path = os.path.join(folder, "repos", repo.path)
  990. remote = clone_repo.create_remote("upstream", upstream_path)
  991. remote.fetch()
  992. # Edit the sources file again
  993. with open(os.path.join(new_gitrepo, "sources"), "w") as stream:
  994. stream.write("foo\n bar\nbaz\n boose")
  995. clone_repo.index.add("sources")
  996. clone_repo.index.write()
  997. # Commits the files added
  998. tree = clone_repo.index.write_tree()
  999. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  1000. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  1001. clone_repo.create_commit(
  1002. "refs/heads/%s" % branch_from,
  1003. author,
  1004. committer,
  1005. "A commit on branch %s" % branch_from,
  1006. tree,
  1007. [first_commit.oid.hex],
  1008. )
  1009. refname = "refs/heads/%s" % (branch_from)
  1010. ori_remote = clone_repo.remotes[0]
  1011. PagureRepo.push(ori_remote, refname)
  1012. # Create a PR for these changes
  1013. project = pagure.lib.query.get_authorized_project(session, "test")
  1014. req = pagure.lib.query.new_pull_request(
  1015. session=session,
  1016. repo_from=fork,
  1017. branch_from=branch_from,
  1018. repo_to=project,
  1019. branch_to="master",
  1020. title="PR from the %s branch" % branch_from,
  1021. allow_rebase=allow_rebase,
  1022. user=user,
  1023. )
  1024. session.commit()
  1025. return req
  1026. def clean_pull_requests_path():
  1027. newpath = tempfile.mkdtemp(prefix="pagure-fork-test")
  1028. shutil.rmtree(newpath)
  1029. @contextmanager
  1030. def capture_output(merge_stderr=True):
  1031. oldout, olderr = sys.stdout, sys.stderr
  1032. try:
  1033. out = StringIO()
  1034. err = StringIO()
  1035. if merge_stderr:
  1036. sys.stdout = sys.stderr = out
  1037. yield out
  1038. else:
  1039. sys.stdout, sys.stderr = out, err
  1040. yield out, err
  1041. finally:
  1042. sys.stdout, sys.stderr = oldout, olderr
  1043. def get_alerts(html):
  1044. soup = BeautifulSoup(html, "html.parser")
  1045. alerts = []
  1046. for element in soup.find_all("div", class_="alert"):
  1047. severity = None
  1048. for class_ in element["class"]:
  1049. if not class_.startswith("alert-"):
  1050. continue
  1051. if class_ == "alert-dismissible":
  1052. continue
  1053. severity = class_[len("alert-") :]
  1054. break
  1055. element.find("button").decompose() # close button
  1056. alerts.append(
  1057. dict(severity=severity, text="".join(element.stripped_strings))
  1058. )
  1059. return alerts
  1060. def definitely_wait(result):
  1061. """ Helper function for definitely waiting in _maybe_wait. """
  1062. result.wait()
  1063. if __name__ == "__main__":
  1064. SUITE = unittest.TestLoader().loadTestsFromTestCase(Modeltests)
  1065. unittest.TextTestRunner(verbosity=2).run(SUITE)