1
0

__init__.py 40 KB

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