__init__.py 40 KB

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