__init__.py 40 KB

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