code:
# -*- coding: utf-8 -*-

"""
 (c) 2016 - Copyright Red Hat Inc

 Authors:
   Pierre-Yves Chibon <pingou@pingoured.fr>

"""

__requires__ = ['SQLAlchemy >= 0.8']
import pkg_resources

import json
import unittest
import shutil
import sys
import tempfile
import os

import pygit2
from mock import patch

sys.path.insert(0, os.path.join(os.path.dirname(
    os.path.abspath(__file__)), '..'))

import pagure.lib
import tests
from pagure.lib.repo import PagureRepo

class PagureFlaskSlashInNametests(tests.Modeltests):
    """ Tests for flask application when the project contains a '/'.
    """

    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskSlashInNametests, self).setUp()

        pagure.APP.config['TESTING'] = True
        pagure.SESSION = self.session
        pagure.lib.SESSION = self.session
        pagure.ui.app.SESSION = self.session
        pagure.ui.filters.SESSION = self.session
        pagure.ui.fork.SESSION = self.session
        pagure.ui.repo.SESSION = self.session
        pagure.ui.issues.SESSION = self.session

        pagure.APP.config['GIT_FOLDER'] = os.path.join(tests.HERE, 'repos')
        pagure.APP.config['FORK_FOLDER'] = os.path.join(tests.HERE, 'forks')
        pagure.APP.config['TICKETS_FOLDER'] = os.path.join(
            tests.HERE, 'tickets')
        pagure.APP.config['DOCS_FOLDER'] = os.path.join(
            tests.HERE, 'docs')
        pagure.APP.config['REQUESTS_FOLDER'] = os.path.join(
            tests.HERE, 'requests')
        self.app = pagure.APP.test_client()

    def set_up_git_repo(self, name='test'):
        """ Set up the git repo to play with. """

        # Create a git repo to play with
        gitrepo = os.path.join(tests.HERE, 'repos', '%s.git' % name)
        repo = pygit2.init_repository(gitrepo, bare=True)

        newpath = tempfile.mkdtemp(prefix='pagure-other-test')
        repopath = os.path.join(newpath, 'test')
        clone_repo = pygit2.clone_repository(gitrepo, repopath)

        # Create a file in that git repo
        with open(os.path.join(repopath, 'sources'), 'w') as stream:
            stream.write('foo\n bar')
        clone_repo.index.add('sources')
        clone_repo.index.write()

        # Commits the files added
        tree = clone_repo.index.write_tree()
        author = pygit2.Signature(
            'Alice Author', 'alice@authors.tld')
        committer = pygit2.Signature(
            'Cecil Committer', 'cecil@committers.tld')
        clone_repo.create_commit(
            'refs/heads/master',  # the name of the reference to update
            author,
            committer,
            'Add sources file for testing',
            # binary string representing the tree object ID
            tree,
            # list of binary strings representing parents of the new commit
            []
        )
        refname = 'refs/heads/master'
        ori_remote = clone_repo.remotes[0]
        PagureRepo.push(ori_remote, refname)

    @patch('pagure.lib.notify.send_email')
    def test_view_repo_empty(self, send_email):
        """ Test the view_repo endpoint when the project has a slash in its
        name.
        """
        send_email.return_value = True

        tests.create_projects(self.session)
        # Non-existant git repo
        output = self.app.get('/test')
        self.assertEqual(output.status_code, 404)

        # Create a git repo to play with
        gitrepo = os.path.join(tests.HERE, 'repos', 'test.git')
        repo = pygit2.init_repository(gitrepo, bare=True)

        # With git repo
        output = self.app.get('/test')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '
\n            '
            '
Owners
', output.data)
        self.assertIn(
            '
The Project Creator has not pushed any code yet
',
            output.data)

        # We can't create the project `forks/test` the normal way
        self.assertRaises(
            pagure.exceptions.PagureException,
            pagure.lib.new_project,
            self.session,
            name='forks/test',
            description='test project forks/test',
            url='',
            avatar_email='',
            user='pingou',
            blacklist=pagure.APP.config['BLACKLISTED_PROJECTS'],
            allowed_prefix=pagure.APP.config['ALLOWED_PREFIX'],
            gitfolder=pagure.APP.config['GIT_FOLDER'],
            docfolder=pagure.APP.config['DOCS_FOLDER'],
            ticketfolder=pagure.APP.config['TICKETS_FOLDER'],
            requestfolder=pagure.APP.config['REQUESTS_FOLDER'],
        )

        # So just put it in the DB
        item = pagure.lib.model.Project(
            user_id=1,  # pingou
            name='forks/test',
            description='test project forks/test',
            hook_token='aaabbbcccddd',
        )
        self.session.add(item)
        self.session.commit()

        # Create a git repo to play with
        gitrepo = os.path.join(tests.HERE, 'repos', 'forks/test.git')
        repo = pygit2.init_repository(gitrepo, bare=True)

        output = self.app.get('/forks/test')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '
\n            '
            '
Owners
', output.data)
        self.assertIn(
            '
The Project Creator has not pushed any code yet
',
            output.data)

        output = self.app.get('/forks/test/issues')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '<title>Issues - forks/test - Pagure</title>', output.data)
        self.assertIn(
            'No issues found	',
            output.data)

    @patch('pagure.lib.notify.send_email')
    def test_view_repo(self, send_email):
        """ Test the view_repo endpoint when the project has a slash in its
        name.
        """
        send_email.return_value = True

        tests.create_projects(self.session)
        # Non-existant git repo
        output = self.app.get('/test')
        self.assertEqual(output.status_code, 404)

        self.set_up_git_repo()

        # With git repo
        output = self.app.get('/test')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '
\n            '
            '
Owners
', output.data)

        # We can't create the project `forks/test` the normal way
        self.assertRaises(
            pagure.exceptions.PagureException,
            pagure.lib.new_project,
            self.session,
            name='forks/test',
            description='test project forks/test',
            url='',
            avatar_email='',
            user='pingou',
            blacklist=pagure.APP.config['BLACKLISTED_PROJECTS'],
            allowed_prefix=pagure.APP.config['ALLOWED_PREFIX'],
            gitfolder=pagure.APP.config['GIT_FOLDER'],
            docfolder=pagure.APP.config['DOCS_FOLDER'],
            ticketfolder=pagure.APP.config['TICKETS_FOLDER'],
            requestfolder=pagure.APP.config['REQUESTS_FOLDER'],
        )

        # So just put it in the DB
        item = pagure.lib.model.Project(
            user_id=1,  # pingou
            name='forks/test',
            description='test project forks/test',
            hook_token='aaabbbcccddd',
        )
        self.session.add(item)
        self.session.commit()

        self.set_up_git_repo(name='forks/test')

        # Front page shows fine
        output = self.app.get('/forks/test')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '
\n            '
            '
Owners
', output.data)
        self.assertIn('Add sources file for testing', output.data)
        self.assertIn(
            '<title>Overview - forks/test - Pagure</title>', output.data)

        # Issues list shows fine
        output = self.app.get('/forks/test/issues')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '<title>Issues - forks/test - Pagure</title>', output.data)
        self.assertIn(
            'No issues found	',
            output.data)

        # Try accessing the commit
        gitrepo = os.path.join(tests.HERE, 'repos', 'test.git')
        repo = pygit2.Repository(gitrepo)
        master_branch = repo.lookup_branch('master')
        first_commit = master_branch.get_object().hex

        output = self.app.get('/forks/test/c/%s' % first_commit)
        self.assertEqual(output.status_code, 200)
        self.assertIn('<title>Commit - forks/test ', output.data)
        self.assertIn(
            '+2          ',
            output.data)

if __name__ == '__main__':
    SUITE = unittest.TestLoader().loadTestsFromTestCase(
        PagureFlaskSlashInNametests)
    unittest.TextTestRunner(verbosity=2).run(SUITE)

repo_name: bill/auger

license: mit


code:
# -*- coding: utf-8 -*-

"""
 (c) 2016 - Copyright Red Hat Inc

 Authors:
   Pierre-Yves Chibon <pingou@pingoured.fr>

"""

__requires__ = ['SQLAlchemy >= 0.8']
import pkg_resources

import datetime
import json
import unittest
import shutil
import sys
import tempfile
import os

import pygit2
from mock import patch

sys.path.insert(0, os.path.join(os.path.dirname(
    os.path.abspath(__file__)), '..'))

import pagure.lib
import tests
from pagure.lib.repo import PagureRepo

class PagureFlaskRoadmaptests(tests.Modeltests):
    """ Tests for the pagure's roadmap """

    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskRoadmaptests, self).setUp()

        pagure.APP.config['TESTING'] = True
        pagure.SESSION = self.session
        pagure.ui.SESSION = self.session
        pagure.ui.app.SESSION = self.session
        pagure.ui.filters.SESSION = self.session
        pagure.ui.repo.SESSION = self.session
        pagure.ui.issues.SESSION = self.session

        pagure.APP.config['GIT_FOLDER'] = tests.HERE
        pagure.APP.config['REQUESTS_FOLDER'] = os.path.join(
            tests.HERE, 'requests')
        pagure.APP.config['TICKETS_FOLDER'] = os.path.join(
            tests.HERE, 'tickets')
        pagure.APP.config['DOCS_FOLDER'] = os.path.join(
            tests.HERE, 'docs')
        self.app = pagure.APP.test_client()

    @patch('pagure.lib.git.update_git')
    @patch('pagure.lib.notify.send_email')
    def test_ticket_with_no_roadmap(self, p_send_email, p_ugt):
        """ Test creating a ticket without roadmap. """
        p_send_email.return_value = True
        p_ugt.return_value = True

        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(tests.HERE), bare=True)

        user = tests.FakeUser()
        user.username = 'pingou'
        with tests.user_set(pagure.APP, user):

            # Get the CSRF token
            output = self.app.get('/test/new_issue')
            self.assertEqual(output.status_code, 200)
            self.assertTrue(
                u'
\n        New issue'
                in output.data)

            csrf_token = output.data.split(
                'name="csrf_token" type="hidden" value="')[1].split('">')[0]

            data = {
                'title': 'Test issue',
                'issue_content': 'We really should improve on this issue',
                'status': 'Open',
                'csrf_token': csrf_token,
            }

            # Create the issue
            output = self.app.post(
                '/test/new_issue', data=data, follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            self.assertIn(
                u'<title>Issue #1: Test issue - test - Pagure</title>',
                output.data)
            self.assertIn(
                u'',
                output.data)

    @patch('pagure.lib.git.update_git')
    @patch('pagure.lib.notify.send_email')
    def test_ticket_with_roadmap(self, p_send_email, p_ugt):
        """ Test creating a ticket with roadmap. """
        p_send_email.return_value = True
        p_ugt.return_value = True

        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(tests.HERE), bare=True)

        # Set some milestone
        repo = pagure.lib.get_project(self.session, 'test')
        repo.milestone = {'v1.0': '', 'v2.0': 'Tomorrow!'}
        self.session.add(repo)
        self.session.commit()

        user = tests.FakeUser()
        user.username = 'pingou'
        with tests.user_set(pagure.APP, user):

            # Get the CSRF token
            output = self.app.get('/test/new_issue')
            self.assertEqual(output.status_code, 200)
            self.assertTrue(
                u'
\n        New issue'
                in output.data)

            csrf_token = output.data.split(
                u'name="csrf_token" type="hidden" value="')[1].split(u'">')[0]

            data = {
                'title': 'Test issue',
                'issue_content': 'We really should improve on this issue',
                'status': 'Open',
                'csrf_token': csrf_token,
            }

            # Create the issue
            output = self.app.post(
                '/test/new_issue', data=data, follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            self.assertIn(
                u'<title>Issue #1: Test issue - test - Pagure</title>',
                output.data)
            self.assertIn(
                u'',
                output.data)

            # Mark the ticket for the roadmap
            data = {
                'tag': 'roadmap',
                'csrf_token': csrf_token,
            }
            output = self.app.post(
                '/test/issue/1/update', data=data, follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            self.assertIn(
                u'<title>Issue #1: Test issue - test - Pagure</title>',
                output.data)
            self.assertIn(
                u'',
                output.data)
            self.assertIn(
                u'</button>\n                      Tag added: roadmap',
                output.data)

    def test_update_milestones(self):
        """ Test updating milestones of a repo. """
        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(tests.HERE), bare=True)

        # Set some milestones
        repo = pagure.lib.get_project(self.session, 'test')
        self.assertEqual(repo.milestones, {})

        user = tests.FakeUser()
        user.username = 'pingou'
        with tests.user_set(pagure.APP, user):

            # Get the CSRF token
            output = self.app.get('/test/settings')
            self.assertEqual(output.status_code, 200)
            self.assertIn(
                u'<title>Settings - test - Pagure</title>', output.data)
            self.assertIn(u'
Settings for test
', output.data)

            csrf_token = output.data.split(
                'name="csrf_token" type="hidden" value="')[1].split('">')[0]

            data = {
                'milestones': 1,
                'milestone_dates': 'Tomorrow',
            }
            output = self.app.post(
                '/test/update/milestones', data=data, follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            # Check the redirect
            self.assertIn(
                u'<title>Settings - test - Pagure</title>', output.data)
            self.assertIn('
Settings for test
', output.data)
            # Check the result of the action -- None, no CSRF
            repo = pagure.lib.get_project(self.session, 'test')
            self.assertEqual(repo.milestones, {})

            data = {
                'milestones': 1,
                'milestone_dates': 'Tomorrow',
                'csrf_token': csrf_token,
            }
            output = self.app.post(
                '/test/update/milestones', data=data, follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            # Check the redirect
            self.assertIn(
                u'<title>Settings - test - Pagure</title>', output.data)
            self.assertIn(u'
Settings for test
', output.data)
            self.assertIn(u'Milestones updated', output.data)
            # Check the result of the action -- Milestones recorded
            repo = pagure.lib.get_project(self.session, 'test')
            self.assertEqual(repo.milestones, {u'1': u'Tomorrow'})

            data = {
                'milestones': ['v1.0', 'v2.0'],
                'milestone_dates': ['Tomorrow', ''],
                'csrf_token': csrf_token,
            }
            output = self.app.post(
                '/test/update/milestones', data=data, follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            # Check the redirect
            self.assertIn(
                u'<title>Settings - test - Pagure</title>', output.data)
            self.assertIn(u'
Settings for test
', output.data)
            self.assertIn(u'Milestones updated', output.data)
            # Check the result of the action -- Milestones recorded
            repo = pagure.lib.get_project(self.session, 'test')
            self.assertEqual(
                repo.milestones, {u'v1.0': u'Tomorrow', u'v2.0': u''}
            )

            # Check error - less milestones than dates
            data = {
                'milestones': ['v1.0', 'v2.0'],
                'milestone_dates': ['Tomorrow', 'Next week', 'Next Year'],
                'csrf_token': csrf_token,
            }
            output = self.app.post(
                '/test/update/milestones', data=data, follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            # Check the redirect
            self.assertIn(
                u'<title>Settings - test - Pagure</title>', output.data)
            self.assertIn(u'
Settings for test
', output.data)
            self.assertIn(
                u'</button>\n'
                '                      Milestones and dates are not of the '
                'same length', output.data)
            # Check the result of the action -- Milestones un-changed
            repo = pagure.lib.get_project(self.session, 'test')
            self.assertEqual(
                repo.milestones, {u'v1.0': u'Tomorrow', u'v2.0': u''}
            )

            # Check error - Twice the same milestone
            data = {
                'milestones': ['v1.0', 'v2.0', 'v2.0'],
                'milestone_dates': ['Tomorrow', 'Next week', 'Next Year'],
                'csrf_token': csrf_token,
            }
            output = self.app.post(
                '/test/update/milestones', data=data, follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            # Check the redirect
            self.assertIn(
                u'<title>Settings - test - Pagure</title>', output.data)
            self.assertIn(u'
Settings for test
', output.data)
            self.assertIn(
                u'</button>\n'
                '                      Milestone v2.0 is present 2 times',
                output.data)
            # Check the result of the action -- Milestones un-changed
            repo = pagure.lib.get_project(self.session, 'test')
            self.assertEqual(
                repo.milestones, {u'v1.0': u'Tomorrow', u'v2.0': u''}
            )

            # Check error - Twice the same date
            data = {
                'milestones': ['v1.0', 'v2.0', 'v3.0'],
                'milestone_dates': ['Tomorrow', 'Next week', 'Next week'],
                'csrf_token': csrf_token,
            }
            output = self.app.post(
                '/test/update/milestones', data=data, follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            # Check the redirect
            self.assertIn(
                u'<title>Settings - test - Pagure</title>', output.data)
            self.assertIn(u'
Settings for test
', output.data)
            self.assertIn(
                u'</button>\n'
                '                      Date Next week is present 2 times',
                output.data)
            # Check the result of the action -- Milestones un-changed
            repo = pagure.lib.get_project(self.session, 'test')
            self.assertEqual(
                repo.milestones, {u'v1.0': u'Tomorrow', u'v2.0': u''}
            )

            # Check for an invalid project
            output = self.app.post(
                '/foo/update/milestones', data=data)
            self.assertEqual(output.status_code, 404)

            # Check the behavior if the project disabled the issue tracker
            settings = repo.settings
            settings['issue_tracker'] = False
            repo.settings = settings
            self.session.add(repo)
            self.session.commit()

            output = self.app.post(
                '/test/update/milestones', data=data)
            self.assertEqual(output.status_code, 404)

        # Check for a non-admin user
        settings = repo.settings
        settings['issue_tracker'] = True
        repo.settings = settings
        self.session.add(repo)
        self.session.commit()

        user.username = 'ralph'
        with tests.user_set(pagure.APP, user):
            output = self.app.post(
                '/test/update/milestones', data=data)
            self.assertEqual(output.status_code, 403)

    @patch('pagure.lib.git.update_git')
    @patch('pagure.lib.notify.send_email')
    def test_milestones_without_dates(self, p_send_email, p_ugt):
        """ Test creating two milestones with no dates. """
        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(tests.HERE), bare=True)

        user = tests.FakeUser()
        user.username = 'pingou'
        with tests.user_set(pagure.APP, user):
            # Get the CSRF token
            output = self.app.get('/test/settings')
            csrf_token = output.data.split(
                'name="csrf_token" type="hidden" value="')[1].split('">')[0]

            data = {
                'milestones': ['v1.0', 'v2.0'],
                'milestone_dates': ['', ''],
                'csrf_token': csrf_token,
            }
            output = self.app.post(
                '/test/update/milestones', data=data, follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            # Check the redirect
            self.assertIn(
                u'<title>Settings - test - Pagure</title>', output.data)
            self.assertIn(u'
Settings for test
', output.data)
            self.assertIn(u'Milestones updated', output.data)
            # Check the result of the action -- Milestones recorded
            repo = pagure.lib.get_project(self.session, 'test')
            self.assertEqual(repo.milestones, {u'v1.0': u'', u'v2.0': u''})

    @patch('pagure.lib.git.update_git')
    @patch('pagure.lib.notify.send_email')
    def test_roadmap_ui(self, p_send_email, p_ugt):
        """ Test viewing the roadmap of a repo. """
        p_send_email.return_value = True
        p_ugt.return_value = True

        self.test_update_milestones()

        user = tests.FakeUser()
        user.username = 'pingou'
        with tests.user_set(pagure.APP, user):

            # Get the CSRF token
            output = self.app.get('/test/new_issue')
            self.assertEqual(output.status_code, 200)
            self.assertTrue(
                u'
\n        New issue'
                in output.data)

            csrf_token = output.data.split(
                u'name="csrf_token" type="hidden" value="')[1].split(u'">')[0]

            # Create the issues
            for cnt in range(6):
                cnt += 1
                data = {
                    'title': 'Test issue %s' % cnt,
                    'issue_content': 'We really should improve on this '
                    'issue %s' % cnt,
                    'status': 'Open',
                    'csrf_token': csrf_token,
                }

                output = self.app.post(
                    '/test/new_issue', data=data, follow_redirects=True)
                self.assertEqual(output.status_code, 200)
                self.assertIn(
                    u'<title>Issue #{0}: Test issue {0} - test - '
                    'Pagure</title>'.format(cnt),
                    output.data)
                self.assertIn(
                    u'' % cnt,
                    output.data)

                # Mark the ticket for the roadmap
                data = {
                    'tag': ['roadmap, v%s.0' % cnt],
                    'csrf_token': csrf_token,
                }
                output = self.app.post(
                    '/test/issue/%s/update' % cnt, data=data,
                    follow_redirects=True)
                self.assertEqual(output.status_code, 200)
                self.assertIn(
                    u'<title>Issue #{0}: Test issue {0} - test - '
                    'Pagure</title>'.format(cnt),
                    output.data)
                self.assertIn(
                    u'' % cnt,
                    output.data)
                self.assertIn(
                    u'</button>\n                      '
                    'Tag added: v%s.0, roadmap' % cnt,
                    output.data)

        repo = pagure.lib.get_project(self.session, 'test')

        # Mark ticket #1 as Fixed
        ticket = pagure.lib.search_issues(
            self.session,
            repo,
            issueid=1
        )
        ticket.status = 'Fixed'
        self.session.add(ticket)
        self.session.commit()

        # test the roadmap view
        output = self.app.get('/test/roadmap')
        self.assertEqual(output.status_code, 200)
        self.assertIn(u'2 Milestones', output.data)
        self.assertIn(u'Milestone: v2.0', output.data)
        self.assertIn(u'Milestone: unplanned', output.data)
        self.assertEqual(
            output.data.count(u'#'), 5)

        # test the roadmap view for all milestones
        output = self.app.get('/test/roadmap?status=All')
        self.assertEqual(output.status_code, 200)
        self.assertIn(u'3 Milestones', output.data)
        self.assertIn(u'Milestone: v1.0', output.data)
        self.assertIn(u'Milestone: v2.0', output.data)
        self.assertIn(u'Milestone: unplanned', output.data)
        self.assertEqual(
            output.data.count(u'#'), 6)

        # test the roadmap view for a specific milestone
        output = self.app.get('/test/roadmap?milestone=v2.0')
        self.assertEqual(output.status_code, 200)
        self.assertIn(u'1 Milestones', output.data)
        self.assertIn(u'Milestone: v2.0', output.data)
        self.assertEqual(
            output.data.count(u'#'), 1)

        # test the roadmap view for a specific milestone - closed
        output = self.app.get('/test/roadmap?milestone=v1.0')
        self.assertEqual(output.status_code, 200)
        self.assertIn(u'1 Milestones', output.data)
        self.assertIn(u'Milestone: v1.0', output.data)
        self.assertEqual(
            output.data.count(u'#'), 0)

        # test the roadmap view for a specific milestone - closed
        output = self.app.get('/test/roadmap?milestone=v1.0&status=All')
        self.assertEqual(output.status_code, 200)
        self.assertIn(u'1 Milestones', output.data)
        self.assertIn(u'Milestone: v1.0', output.data)
        self.assertEqual(
            output.data.count(u'#'), 1)

        # test the roadmap view for errors
        output = self.app.get('/foo/roadmap')
        self.assertEqual(output.status_code, 404)

        repo = pagure.lib.get_project(self.session, 'test')
        settings = repo.settings
        settings['issue_tracker'] = False
        repo.settings = settings
        self.session.add(repo)
        self.session.commit()

        output = self.app.get('/test/roadmap', data=data)
        self.assertEqual(output.status_code, 404)

if __name__ == '__main__':
    SUITE = unittest.TestLoader().loadTestsFromTestCase(
        PagureFlaskRoadmaptests)
    unittest.TextTestRunner(verbosity=2).run(SUITE)


code:
# -*- coding: utf-8 -*-

"""
 (c) 2015 - Copyright Red Hat Inc

 Authors:
   Pierre-Yves Chibon <pingou@pingoured.fr>

"""

__requires__ = ['SQLAlchemy >= 0.8']
import pkg_resources

import json
import unittest
import shutil
import sys
import tempfile
import os

import pygit2
from mock import patch

sys.path.insert(0, os.path.join(os.path.dirname(
    os.path.abspath(__file__)), '..'))

import pagure.lib
import tests
from pagure.lib.repo import PagureRepo

class PagureFlaskSlashInBranchtests(tests.Modeltests):
    """ Tests for flask application when the branch name contains a '/'.
    """

    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskSlashInBranchtests, self).setUp()

        pagure.APP.config['TESTING'] = True
        pagure.SESSION = self.session
        pagure.lib.SESSION = self.session
        pagure.ui.app.SESSION = self.session
        pagure.ui.filters.SESSION = self.session
        pagure.ui.fork.SESSION = self.session
        pagure.ui.repo.SESSION = self.session

        pagure.APP.config['GIT_FOLDER'] = os.path.join(tests.HERE, 'repos')
        pagure.APP.config['FORK_FOLDER'] = os.path.join(tests.HERE, 'forks')
        pagure.APP.config['TICKETS_FOLDER'] = os.path.join(
            tests.HERE, 'tickets')
        pagure.APP.config['DOCS_FOLDER'] = os.path.join(
            tests.HERE, 'docs')
        pagure.APP.config['REQUESTS_FOLDER'] = os.path.join(
            tests.HERE, 'requests')
        self.app = pagure.APP.test_client()

    def set_up_git_repo(self):
        """ Set up the git repo to play with. """

        # Create a git repo to play with
        gitrepo = os.path.join(tests.HERE, 'repos', 'test.git')
        repo = pygit2.init_repository(gitrepo, bare=True)

        newpath = tempfile.mkdtemp(prefix='pagure-other-test')
        repopath = os.path.join(newpath, 'test')
        clone_repo = pygit2.clone_repository(gitrepo, repopath)

        # Create a file in that git repo
        with open(os.path.join(repopath, 'sources'), 'w') as stream:
            stream.write('foo\n bar')
        clone_repo.index.add('sources')
        clone_repo.index.write()

        # Commits the files added
        tree = clone_repo.index.write_tree()
        author = pygit2.Signature(
            'Alice Author', 'alice@authors.tld')
        committer = pygit2.Signature(
            'Cecil Committer', 'cecil@committers.tld')
        clone_repo.create_commit(
            'refs/heads/master',  # the name of the reference to update
            author,
            committer,
            'Add sources file for testing',
            # binary string representing the tree object ID
            tree,
            # list of binary strings representing parents of the new commit
            []
        )
        refname = 'refs/heads/master'
        ori_remote = clone_repo.remotes[0]
        PagureRepo.push(ori_remote, refname)

        master_branch = clone_repo.lookup_branch('master')
        first_commit = master_branch.get_object().hex

        # Second commit
        with open(os.path.join(repopath, '.gitignore'), 'w') as stream:
            stream.write('*~')
        clone_repo.index.add('.gitignore')
        clone_repo.index.write()

        tree = clone_repo.index.write_tree()
        author = pygit2.Signature(
            'Alice Author', 'alice@authors.tld')
        committer = pygit2.Signature(
            'Cecil Committer', 'cecil@committers.tld')
        clone_repo.create_commit(
            'refs/heads/maxamilion/feature',
            author,
            committer,
            'Add .gitignore file for testing',
            # binary string representing the tree object ID
            tree,
            # list of binary strings representing parents of the new commit
            [first_commit]
        )

        refname = 'refs/heads/maxamilion/feature'
        ori_remote = clone_repo.remotes[0]
        PagureRepo.push(ori_remote, refname)

        shutil.rmtree(newpath)

    @patch('pagure.lib.notify.send_email')
    def test_view_repo(self, send_email):
        """ Test the view_repo endpoint when the git repo has no master
        branch.
        """
        send_email.return_value = True

        tests.create_projects(self.session)
        # Non-existant git repo
        output = self.app.get('/test')
        self.assertEqual(output.status_code, 404)

        self.set_up_git_repo()

        # With git repo
        output = self.app.get('/test')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '
\n            '
            '
Owners
', output.data)

    @patch('pagure.lib.notify.send_email')
    def test_view_repo_branch(self, send_email):
        """ Test the view_repo_branch endpoint when the git repo has no
        master branch.
        """
        send_email.return_value = True

        tests.create_projects(self.session)
        # Non-existant git repo
        output = self.app.get('/test/branch/master')
        self.assertEqual(output.status_code, 404)

        self.set_up_git_repo()

        # With git repo
        output = self.app.get('/test/branch/maxamilion/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '
\n            '
            '
Owners
', output.data)

    @patch('pagure.lib.notify.send_email')
    def test_view_commits(self, send_email):
        """ Test the view_commits endpoint when the git repo has no
        master branch.
        """
        send_email.return_value = True

        tests.create_projects(self.session)
        # Non-existant git repo
        output = self.app.get('/test/commits')
        self.assertEqual(output.status_code, 404)

        self.set_up_git_repo()

        # With git repo
        output = self.app.get('/test/commits')
        self.assertEqual(output.status_code, 200)
        self.assertEqual(output.data.count('<span class="commitdate"'), 1)

        output = self.app.get('/test/commits/maxamilion/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn('<title>Commits - test - Pagure</title>', output.data)
        self.assertIn('Add sources file for testing', output.data)
        self.assertIn('Add .gitignore file for testing', output.data)
        self.assertEqual(output.data.count('<span class="commitdate"'), 3)

    @patch('pagure.lib.notify.send_email')
    def test_view_file(self, send_email):
        """ Test the view_file endpoint when the git repo has no
        master branch.
        """
        send_email.return_value = True

        tests.create_projects(self.session)
        # Non-existant git repo
        output = self.app.get('/test/blob/master/f/sources')
        self.assertEqual(output.status_code, 404)

        self.set_up_git_repo()

        # With git repo
        output = self.app.get('/test/blob/master/f/sources')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '''

                master

              sources

''', output.data)

        output = self.app.get('/test/blob/master/f/.gitignore')
        self.assertEqual(output.status_code, 404)

        output = self.app.get('/test/blob/maxamilion/feature/f/.gitignore')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '''

                maxamilion/feature

              .gitignore

''', output.data)
        self.assertTrue(
            # new version of pygments
            '
*~
	' in output.data
            or
            # old version of pygments
            '
*~
	' in output.data)

    @patch('pagure.lib.notify.send_email')
    def test_view_raw_file(self, send_email):
        """ Test the view_raw_file endpoint when the git repo has no
        master branch.
        """
        send_email.return_value = True

        tests.create_projects(self.session)
        # Non-existant git repo
        output = self.app.get('/test/raw/master')
        self.assertEqual(output.status_code, 404)
        output = self.app.get('/test/raw/master/f/sources')
        self.assertEqual(output.status_code, 404)

        self.set_up_git_repo()

        # With git repo
        output = self.app.get('/test/raw/master')
        self.assertEqual(output.status_code, 200)
        self.assertIn('diff --git a/sources b/sources', output.data)
        self.assertIn('+foo\n+ bar', output.data)
        output = self.app.get('/test/raw/master/f/sources')
        self.assertEqual(output.status_code, 200)
        self.assertEqual(output.data, 'foo\n bar')

        output = self.app.get('/test/raw/maxamilion/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn('diff --git a/.gitignore b/.gitignore', output.data)
        self.assertIn('+*~', output.data)

        output = self.app.get('/test/raw/maxamilion/feature/f/sources')
        self.assertEqual(output.status_code, 200)
        self.assertEqual('foo\n bar', output.data)

    @patch('pagure.lib.notify.send_email')
    def test_view_tree(self, send_email):
        """ Test the view_tree endpoint when the git repo has no
        master branch.
        """
        send_email.return_value = True

        tests.create_projects(self.session)
        # Non-existant git repo
        output = self.app.get('/test/tree/')
        self.assertEqual(output.status_code, 404)
        output = self.app.get('/test/tree/master')
        self.assertEqual(output.status_code, 404)

        self.set_up_git_repo()

        # With git repo
        output = self.app.get('/test/tree/master')
        self.assertEqual(output.status_code, 200)
        self.assertIn('', output.data)
        self.assertEqual(
            output.data.count(''), 1)

        output = self.app.get('/test/tree/master/sources')
        self.assertEqual(output.status_code, 200)
        self.assertIn('', output.data)
        self.assertEqual(
            output.data.count(''), 1)

        output = self.app.get('/test/tree/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn('', output.data)
        self.assertEqual(
            output.data.count(''), 1)

        output = self.app.get('/test/tree/maxamilion/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '',
            output.data)
        self.assertEqual(
            output.data.count(''), 2)

        # Wrong identifier, back onto master
        output = self.app.get('/test/tree/maxamilion/feature/f/.gitignore')
        self.assertEqual(output.status_code, 200)
        self.assertIn('', output.data)
        self.assertEqual(
            output.data.count(''), 1)

    @patch('pagure.lib.notify.send_email')
    def test_new_request_pull(self, send_email):
        """ Test the new_request_pull endpoint when the git repo has no
        master branch.
        """
        send_email.return_value = True

        tests.create_projects(self.session)
        # Non-existant git repo
        output = self.app.get('/test/diff/master..maxamilion/feature')
        # (used to be 302 but seeing a diff is allowed even logged out)
        self.assertEqual(output.status_code, 404)

        user = tests.FakeUser()
        with tests.user_set(pagure.APP, user):
            output = self.app.get('/test/diff/master..maxamilion/feature')
            self.assertEqual(output.status_code, 404)

        self.set_up_git_repo()

        output = self.app.get('/test/diff/master..maxamilion/feature')
        # (used to be 302 but seeing a diff is allowed even logged out)
        self.assertEqual(output.status_code, 200)
        self.assertEqual(
            output.data.count('<span class="commitdate" title='), 1)
        self.assertIn(
            ''
            '+1', output.data)
        self.assertIn(
            '
file added

', output.data)

        user = tests.FakeUser()
        with tests.user_set(pagure.APP, user):
            output = self.app.get('/test/diff/master..maxamilion/feature')
            self.assertEqual(output.status_code, 200)
            self.assertEqual(
                output.data.count('<span class="commitdate" title='), 1)
            self.assertIn(
                ''
                '+1', output.data)
            self.assertIn(
                '
file added

', output.data)

if __name__ == '__main__':
    SUITE = unittest.TestLoader().loadTestsFromTestCase(
        PagureFlaskSlashInBranchtests)
    unittest.TextTestRunner(verbosity=2).run(SUITE)