__init__.py 40 KB

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