1
0

__init__.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  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 _populate_db(session):
  201. # Create a couple of users
  202. item = pagure.lib.model.User(
  203. user="pingou",
  204. fullname="PY C",
  205. password=b"foo",
  206. default_email="bar@pingou.com",
  207. )
  208. session.add(item)
  209. item = pagure.lib.model.UserEmail(user_id=1, email="bar@pingou.com")
  210. session.add(item)
  211. item = pagure.lib.model.UserEmail(user_id=1, email="foo@pingou.com")
  212. session.add(item)
  213. item = pagure.lib.model.User(
  214. user="foo",
  215. fullname="foo bar",
  216. password=b"foo",
  217. default_email="foo@bar.com",
  218. )
  219. session.add(item)
  220. item = pagure.lib.model.UserEmail(user_id=2, email="foo@bar.com")
  221. session.add(item)
  222. session.commit()
  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 assertURLEqual(self, url_1, url_2):
  433. url_parsed_1 = list(urlparse(url_1))
  434. url_parsed_1[4] = parse_qs(url_parsed_1[4])
  435. url_parsed_2 = list(urlparse(url_2))
  436. url_parsed_2[4] = parse_qs(url_parsed_2[4])
  437. return self.assertListEqual(url_parsed_1, url_parsed_2)
  438. def assertJSONEqual(self, json_1, json_2):
  439. return self.assertEqual(json.loads(json_1), json.loads(json_2))
  440. class Modeltests(SimplePagureTest):
  441. """ Model tests. """
  442. def setUp(self): # pylint: disable=invalid-name
  443. """ Set up the environnment, ran before every tests. """
  444. # Clean up test performance info
  445. super(Modeltests, self).setUp()
  446. self.app.get = create_maybe_waiter(self.app.get, self.app.get)
  447. self.app.post = create_maybe_waiter(self.app.post, self.app.get)
  448. # Refresh the DB session
  449. self.session = pagure.lib.query.create_session(self.dbpath)
  450. def tearDown(self): # pylint: disable=invalid-name
  451. """ Remove the test.db database if there is one. """
  452. tests_state["broker_client"].flushall()
  453. super(Modeltests, self).tearDown()
  454. def create_project_full(self, projectname, extra=None):
  455. """ Create a project via the API.
  456. This makes sure that the repo is fully setup the way a normal new
  457. project would be, with hooks and all setup.
  458. """
  459. headers = {"Authorization": "token aaabbbcccddd"}
  460. data = {"name": projectname, "description": "A test repo"}
  461. if extra:
  462. data.update(extra)
  463. # Valid request
  464. output = self.app.post("/api/0/new/", data=data, headers=headers)
  465. self.assertEqual(output.status_code, 200)
  466. data = json.loads(output.get_data(as_text=True))
  467. self.assertDictEqual(
  468. data, {"message": 'Project "%s" created' % projectname}
  469. )
  470. class FakeGroup(object): # pylint: disable=too-few-public-methods
  471. """ Fake object used to make the FakeUser object closer to the
  472. expectations.
  473. """
  474. def __init__(self, name):
  475. """ Constructor.
  476. :arg name: the name given to the name attribute of this object.
  477. """
  478. self.name = name
  479. self.group_type = "cla"
  480. class FakeUser(object): # pylint: disable=too-few-public-methods
  481. """ Fake user used to test the fedocallib library. """
  482. def __init__(
  483. self, groups=None, username="username", cla_done=True, id=None
  484. ):
  485. """ Constructor.
  486. :arg groups: list of the groups in which this fake user is
  487. supposed to be.
  488. """
  489. if isinstance(groups, six.string_types):
  490. groups = [groups]
  491. self.id = id
  492. self.groups = groups or []
  493. self.user = username
  494. self.username = username
  495. self.name = username
  496. self.email = "foo@bar.com"
  497. self.default_email = "foo@bar.com"
  498. self.approved_memberships = [
  499. FakeGroup("packager"),
  500. FakeGroup("design-team"),
  501. ]
  502. self.dic = {}
  503. self.dic["timezone"] = "Europe/Paris"
  504. self.login_time = datetime.utcnow()
  505. self.cla_done = cla_done
  506. def __getitem__(self, key):
  507. return self.dic[key]
  508. def create_locks(session, project):
  509. for ltype in ("WORKER", "WORKER_TICKET", "WORKER_REQUEST"):
  510. lock = pagure.lib.model.ProjectLock(
  511. project_id=project.id, lock_type=ltype
  512. )
  513. session.add(lock)
  514. def create_projects(session, is_fork=False, user_id=1, hook_token_suffix=""):
  515. """ Create some projects in the database. """
  516. item = pagure.lib.model.Project(
  517. user_id=user_id, # pingou
  518. name="test",
  519. is_fork=is_fork,
  520. parent_id=1 if is_fork else None,
  521. description="test project #1",
  522. hook_token="aaabbbccc" + hook_token_suffix,
  523. )
  524. item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
  525. session.add(item)
  526. session.flush()
  527. create_locks(session, item)
  528. item = pagure.lib.model.Project(
  529. user_id=user_id, # pingou
  530. name="test2",
  531. is_fork=is_fork,
  532. parent_id=2 if is_fork else None,
  533. description="test project #2",
  534. hook_token="aaabbbddd" + hook_token_suffix,
  535. )
  536. item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
  537. session.add(item)
  538. session.flush()
  539. create_locks(session, item)
  540. item = pagure.lib.model.Project(
  541. user_id=user_id, # pingou
  542. name="test3",
  543. is_fork=is_fork,
  544. parent_id=3 if is_fork else None,
  545. description="namespaced test project",
  546. hook_token="aaabbbeee" + hook_token_suffix,
  547. namespace="somenamespace",
  548. )
  549. item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
  550. session.add(item)
  551. session.flush()
  552. create_locks(session, item)
  553. session.commit()
  554. def create_projects_git(folder, bare=False):
  555. """ Create some projects in the database. """
  556. repos = []
  557. for project in [
  558. "test.git",
  559. "test2.git",
  560. os.path.join("somenamespace", "test3.git"),
  561. ]:
  562. repo_path = os.path.join(folder, project)
  563. repos.append(repo_path)
  564. if not os.path.exists(repo_path):
  565. os.makedirs(repo_path)
  566. pygit2.init_repository(repo_path, bare=bare)
  567. return repos
  568. def create_tokens(session, user_id=1, project_id=1):
  569. """ Create some tokens for the project in the database. """
  570. item = pagure.lib.model.Token(
  571. id="aaabbbcccddd",
  572. user_id=user_id,
  573. project_id=project_id,
  574. expiration=datetime.utcnow() + timedelta(days=30),
  575. )
  576. session.add(item)
  577. item = pagure.lib.model.Token(
  578. id="foo_token",
  579. user_id=user_id,
  580. project_id=project_id,
  581. expiration=datetime.utcnow() + timedelta(days=30),
  582. )
  583. session.add(item)
  584. item = pagure.lib.model.Token(
  585. id="expired_token",
  586. user_id=user_id,
  587. project_id=project_id,
  588. expiration=datetime.utcnow() - timedelta(days=1),
  589. )
  590. session.add(item)
  591. session.commit()
  592. def create_tokens_acl(session, token_id="aaabbbcccddd", acl_name=None):
  593. """ Create some ACLs for the token. If acl_name is not set, the token will
  594. have all the ACLs enabled.
  595. """
  596. if acl_name is None:
  597. for aclid in range(len(pagure_config["ACLS"])):
  598. token_acl = pagure.lib.model.TokenAcl(
  599. token_id=token_id, acl_id=aclid + 1
  600. )
  601. session.add(token_acl)
  602. else:
  603. acl = (
  604. session.query(pagure.lib.model.ACL).filter_by(name=acl_name).one()
  605. )
  606. token_acl = pagure.lib.model.TokenAcl(token_id=token_id, acl_id=acl.id)
  607. session.add(token_acl)
  608. session.commit()
  609. def _clone_and_top_commits(folder, branch, branch_ref=False):
  610. """ Clone the repository, checkout the specified branch and return
  611. the top commit of that branch if there is one.
  612. Returns the repo, the path to the clone and the top commit(s) in a tuple
  613. or the repo, the path to the clone and the reference to the branch
  614. object if branch_ref is True.
  615. """
  616. if not os.path.exists(folder):
  617. os.makedirs(folder)
  618. brepo = pygit2.init_repository(folder, bare=True)
  619. newfolder = tempfile.mkdtemp(prefix="pagure-tests")
  620. repo = pygit2.clone_repository(folder, newfolder)
  621. branch_ref_obj = None
  622. if "origin/%s" % branch in repo.listall_branches(pygit2.GIT_BRANCH_ALL):
  623. branch_ref_obj = pagure.lib.git.get_branch_ref(repo, branch)
  624. repo.checkout(branch_ref_obj)
  625. if branch_ref:
  626. return (repo, newfolder, branch_ref_obj)
  627. parents = []
  628. commit = None
  629. try:
  630. if branch_ref_obj:
  631. commit = repo[branch_ref_obj.peel().hex]
  632. else:
  633. commit = repo.revparse_single("HEAD")
  634. except KeyError:
  635. pass
  636. if commit:
  637. parents = [commit.oid.hex]
  638. return (repo, newfolder, parents)
  639. def add_content_git_repo(folder, branch="master", append=None):
  640. """ Create some content for the specified git repo. """
  641. repo, newfolder, parents = _clone_and_top_commits(folder, branch)
  642. # Create a file in that git repo
  643. filename = os.path.join(newfolder, "sources")
  644. content = "foo\n bar"
  645. if os.path.exists(filename):
  646. content = "foo\n bar\nbaz"
  647. if append:
  648. content += append
  649. with open(filename, "w") as stream:
  650. stream.write(content)
  651. repo.index.add("sources")
  652. repo.index.write()
  653. # Commits the files added
  654. tree = repo.index.write_tree()
  655. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  656. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  657. commit = repo.create_commit(
  658. "refs/heads/%s" % branch, # the name of the reference to update
  659. author,
  660. committer,
  661. "Add sources file for testing",
  662. # binary string representing the tree object ID
  663. tree,
  664. # list of binary strings representing parents of the new commit
  665. parents,
  666. )
  667. if commit:
  668. parents = [commit.hex]
  669. subfolder = os.path.join("folder1", "folder2")
  670. if not os.path.exists(os.path.join(newfolder, subfolder)):
  671. os.makedirs(os.path.join(newfolder, subfolder))
  672. # Create a file in that git repo
  673. with open(os.path.join(newfolder, subfolder, "file"), "w") as stream:
  674. stream.write("foo\n bar\nbaz")
  675. repo.index.add(os.path.join(subfolder, "file"))
  676. with open(os.path.join(newfolder, subfolder, "fileŠ"), "w") as stream:
  677. stream.write("foo\n bar\nbaz")
  678. repo.index.add(os.path.join(subfolder, "fileŠ"))
  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 some directory and a file for more 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. # Push to origin
  695. ori_remote = repo.remotes[0]
  696. master_ref = repo.lookup_reference(
  697. "HEAD" if branch == "master" else "refs/heads/%s" % branch
  698. ).resolve()
  699. refname = "%s:%s" % (master_ref.name, master_ref.name)
  700. PagureRepo.push(ori_remote, refname)
  701. shutil.rmtree(newfolder)
  702. def add_readme_git_repo(folder, readme_name="README.rst", branch="master"):
  703. """ Create a README file for the specified git repo. """
  704. repo, newfolder, parents = _clone_and_top_commits(folder, branch)
  705. if readme_name == "README.rst":
  706. content = """Pagure
  707. ======
  708. :Author: Pierre-Yves Chibon <pingou@pingoured.fr>
  709. Pagure is a light-weight git-centered forge based on pygit2.
  710. Currently, Pagure offers a web-interface for git repositories, a ticket
  711. system and possibilities to create new projects, fork existing ones and
  712. create/merge pull-requests across or within projects.
  713. Homepage: https://github.com/pypingou/pagure
  714. Dev instance: http://209.132.184.222/ (/!\\ May change unexpectedly, it's a dev instance ;-))
  715. """
  716. else:
  717. content = (
  718. """Pagure
  719. ======
  720. This is a placeholder """
  721. + readme_name
  722. + """
  723. that should never get displayed on the website if there is a README.rst in the repo.
  724. """
  725. )
  726. # Create a file in that git repo
  727. with open(os.path.join(newfolder, readme_name), "w") as stream:
  728. stream.write(content)
  729. repo.index.add(readme_name)
  730. repo.index.write()
  731. # Commits the files added
  732. tree = repo.index.write_tree()
  733. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  734. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  735. branch_ref = "refs/heads/%s" % branch
  736. repo.create_commit(
  737. branch_ref, # the name of the reference to update
  738. author,
  739. committer,
  740. "Add a README file",
  741. # binary string representing the tree object ID
  742. tree,
  743. # list of binary strings representing parents of the new commit
  744. parents,
  745. )
  746. # Push to origin
  747. ori_remote = repo.remotes[0]
  748. PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref))
  749. shutil.rmtree(newfolder)
  750. def add_commit_git_repo(
  751. folder, ncommits=10, filename="sources", branch="master", symlink_to=None
  752. ):
  753. """ Create some more commits for the specified git repo. """
  754. repo, newfolder, branch_ref_obj = _clone_and_top_commits(
  755. folder, branch, branch_ref=True
  756. )
  757. for index in range(ncommits):
  758. # Create a file in that git repo
  759. if symlink_to:
  760. os.symlink(symlink_to, os.path.join(newfolder, filename))
  761. else:
  762. with open(os.path.join(newfolder, filename), "a") as stream:
  763. stream.write("Row %s\n" % index)
  764. repo.index.add(filename)
  765. repo.index.write()
  766. parents = []
  767. commit = None
  768. try:
  769. if branch_ref_obj:
  770. commit = repo[branch_ref_obj.peel().hex]
  771. else:
  772. commit = repo.revparse_single("HEAD")
  773. except (KeyError, AttributeError):
  774. pass
  775. if commit:
  776. parents = [commit.oid.hex]
  777. # Commits the files added
  778. tree = repo.index.write_tree()
  779. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  780. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  781. branch_ref = "refs/heads/%s" % branch
  782. repo.create_commit(
  783. branch_ref,
  784. author,
  785. committer,
  786. "Add row %s to %s file" % (index, filename),
  787. # binary string representing the tree object ID
  788. tree,
  789. # list of binary strings representing parents of the new commit
  790. parents,
  791. )
  792. branch_ref_obj = pagure.lib.git.get_branch_ref(repo, branch)
  793. # Push to origin
  794. ori_remote = repo.remotes[0]
  795. PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref))
  796. shutil.rmtree(newfolder)
  797. def add_tag_git_repo(folder, tagname, obj_hash, message):
  798. """ Add a tag to the given object of the given repo annotated by given message. """
  799. repo, newfolder, branch_ref_obj = _clone_and_top_commits(
  800. folder, "master", branch_ref=True
  801. )
  802. tag_sha = repo.create_tag(
  803. tagname,
  804. obj_hash,
  805. repo.get(obj_hash).type,
  806. pygit2.Signature("Alice Author", "alice@authors.tld"),
  807. message,
  808. )
  809. # Push to origin
  810. ori_remote = repo.remotes[0]
  811. PagureRepo.push(
  812. ori_remote, "refs/tags/%s:refs/tags/%s" % (tagname, tagname)
  813. )
  814. shutil.rmtree(newfolder)
  815. return tag_sha
  816. def add_content_to_git(
  817. folder, branch="master", filename="sources", content="foo", message=None
  818. ):
  819. """ Create some more commits for the specified git repo. """
  820. repo, newfolder, branch_ref_obj = _clone_and_top_commits(
  821. folder, branch, branch_ref=True
  822. )
  823. # Create a file in that git repo
  824. with open(
  825. os.path.join(newfolder, filename), "a", encoding="utf-8"
  826. ) as stream:
  827. stream.write("%s\n" % content)
  828. repo.index.add(filename)
  829. repo.index.write()
  830. parents = []
  831. commit = None
  832. try:
  833. if branch_ref_obj:
  834. commit = repo[branch_ref_obj.peel().hex]
  835. else:
  836. commit = repo.revparse_single("HEAD")
  837. except (KeyError, AttributeError):
  838. pass
  839. if commit:
  840. parents = [commit.oid.hex]
  841. # Commits the files added
  842. tree = repo.index.write_tree()
  843. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  844. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  845. branch_ref = "refs/heads/%s" % branch
  846. message = message or "Add content to file %s" % (filename)
  847. repo.create_commit(
  848. branch_ref, # the name of the reference to update
  849. author,
  850. committer,
  851. message,
  852. # binary string representing the tree object ID
  853. tree,
  854. # list of binary strings representing parents of the new commit
  855. parents,
  856. )
  857. # Push to origin
  858. ori_remote = repo.remotes[0]
  859. PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref))
  860. shutil.rmtree(newfolder)
  861. def add_binary_git_repo(folder, filename):
  862. """ Create a fake image file for the specified git repo. """
  863. repo, newfolder, parents = _clone_and_top_commits(folder, "master")
  864. content = b"""\x00\x00\x01\x00\x01\x00\x18\x18\x00\x00\x01\x00 \x00\x88
  865. \t\x00\x00\x16\x00\x00\x00(\x00\x00\x00\x18\x00x00\x00\x01\x00 \x00\x00\x00
  866. \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
  867. 00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa7lM\x01\xa6kM\t\xa6kM\x01
  868. \xa4fF\x04\xa2dE\x95\xa2cD8\xa1a
  869. """
  870. # Create a file in that git repo
  871. with open(os.path.join(newfolder, filename), "wb") as stream:
  872. stream.write(content)
  873. repo.index.add(filename)
  874. repo.index.write()
  875. # Commits the files added
  876. tree = repo.index.write_tree()
  877. author = pygit2.Signature("Alice Author", "alice@authors.tld")
  878. committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
  879. repo.create_commit(
  880. "refs/heads/master", # the name of the reference to update
  881. author,
  882. committer,
  883. "Add a fake image file",
  884. # binary string representing the tree object ID
  885. tree,
  886. # list of binary strings representing parents of the new commit
  887. parents,
  888. )
  889. # Push to origin
  890. ori_remote = repo.remotes[0]
  891. master_ref = repo.lookup_reference("HEAD").resolve()
  892. refname = "%s:%s" % (master_ref.name, master_ref.name)
  893. PagureRepo.push(ori_remote, refname)
  894. shutil.rmtree(newfolder)
  895. def remove_file_git_repo(folder, filename, branch="master"):
  896. """ Delete the specified file on the give git repo and branch. """
  897. repo, newfolder, parents = _clone_and_top_commits(folder, branch)
  898. # Remove file
  899. repo.index.remove(filename)
  900. # Write the change and commit it
  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. branch_ref = "refs/heads/%s" % branch
  905. repo.create_commit(
  906. branch_ref, # the name of the reference to update
  907. author,
  908. committer,
  909. "Remove file %s" % filename,
  910. # binary string representing the tree object ID
  911. tree,
  912. # list of binary strings representing parents of the new commit
  913. parents,
  914. )
  915. # Push to origin
  916. ori_remote = repo.remotes[0]
  917. PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref))
  918. shutil.rmtree(newfolder)
  919. @contextmanager
  920. def capture_output(merge_stderr=True):
  921. oldout, olderr = sys.stdout, sys.stderr
  922. try:
  923. out = StringIO()
  924. err = StringIO()
  925. if merge_stderr:
  926. sys.stdout = sys.stderr = out
  927. yield out
  928. else:
  929. sys.stdout, sys.stderr = out, err
  930. yield out, err
  931. finally:
  932. sys.stdout, sys.stderr = oldout, olderr
  933. def get_alerts(html):
  934. soup = BeautifulSoup(html, "html.parser")
  935. alerts = []
  936. for element in soup.find_all("div", class_="alert"):
  937. severity = None
  938. for class_ in element["class"]:
  939. if not class_.startswith("alert-"):
  940. continue
  941. if class_ == "alert-dismissible":
  942. continue
  943. severity = class_[len("alert-") :]
  944. break
  945. element.find("button").decompose() # close button
  946. alerts.append(
  947. dict(severity=severity, text="".join(element.stripped_strings))
  948. )
  949. return alerts
  950. def definitely_wait(result):
  951. """ Helper function for definitely waiting in _maybe_wait. """
  952. result.wait()
  953. if __name__ == "__main__":
  954. SUITE = unittest.TestLoader().loadTestsFromTestCase(Modeltests)
  955. unittest.TextTestRunner(verbosity=2).run(SUITE)