__init__.py 35 KB

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