Example #1
0
    def test_auth(self):
        """ Test the token based authentication.
        """
        tests.create_projects(self.session)
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

        output = self.app.post('/api/0/test/new_issue')
        self.assertEqual(output.status_code, 401)
        data = json.loads(output.data)
        self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name,
                         data['error_code'])
        self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error'])

        headers = {'Authorization': 'token aaabbbcccddd'}

        output = self.app.post('/api/0/test/new_issue', headers=headers)
        self.assertEqual(output.status_code, 400)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Invalid or incomplete input submited",
              "error_code": "EINVALIDREQ",
              "errors": {
                "issue_content": ["This field is required."],
                "title": ["This field is required."]
              }
            }
        )
    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..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..feature')
            self.assertEqual(output.status_code, 404)

        self.set_up_git_repo()

        output = self.app.get('/test/diff/master..feature')
        # (used to be 302 but seeing a diff is allowed even logged out)
        self.assertEqual(output.status_code, 400)
        self.assertIn(
            '<p>Branch master could not be found in the target repo</p>',
            output.data)

        user = tests.FakeUser()
        with tests.user_set(pagure.APP, user):
            output = self.app.get('/test/diff/master..feature')
            self.assertEqual(output.status_code, 400)
            self.assertIn(
                '<p>Branch master could not be found in the target repo</p>',
                output.data)
    def test_watch_list(self):
        ''' Test for watch list of a user '''

        user = tests.FakeUser(username='******')
        with tests.user_set(pagure.APP, user):
            output = self.app.get('/')
            self.assertIn(
                '<div class="text-xs-center">You have no projects</div>',
                output.data)
            self.assertIn(
                '<p>You have no forks</p>',
                output.data)
            self.assertIn(
                '<p>No project in watch list</p>',
                output.data)

            tests.create_projects(self.session)

            output = self.app.get('/')
            self.assertIn(
                'My Projects <span class="label label-default">2</span>',
                output.data)
            self.assertIn(
                'My Forks <span class="label label-default">0</span>',
                output.data)
            self.assertIn(
                'My Watch List <span class="label label-default">2</span>',
                output.data)
    def test_index(self):
        """ Test the index endpoint. """

        output = self.app.get('/')
        self.assertEqual(output.status_code, 200)
        self.assertTrue('<h2>All Projects (0)</h2>' in output.data)

        tests.create_projects(self.session)

        output = self.app.get('/?page=abc')
        self.assertEqual(output.status_code, 200)
        self.assertTrue('<h2>All Projects (2)</h2>' in output.data)

        # Add a 3rd project with a long description
        item = pagure.lib.model.Project(
            user_id=2,  # foo
            name='test3',
            description='test project #3 with a very long description',
            hook_token='aaabbbeee',
        )
        self.session.add(item)
        self.session.commit()

        user = tests.FakeUser()
        with tests.user_set(pagure.APP, user):
            output = self.app.get('/?repopage=abc&forkpage=def')
            self.assertTrue(
                '<section class="project_list" id="repos">' in output.data)
            self.assertTrue('<h3>My Forks (0)</h3>' in output.data)
            self.assertTrue(
                '<section class="project_list" id="myforks">' in output.data)
            self.assertTrue('<h3>My Projects (0)</h3>' in output.data)
            self.assertTrue(
                '<section class="project_list" id="myrepos">' in output.data)
            self.assertTrue('<h3>All Projects (3)</h3>' in output.data)
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskApiIssueCreatetests, self).setUp()

        pagure.config.config["TICKETS_FOLDER"] = None

        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(self.path, "tickets"))
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

        # Create project-less token for user foo
        item = pagure.lib.model.Token(
            id="project-less-foo",
            user_id=2,
            project_id=None,
            expiration=datetime.datetime.utcnow()
            + datetime.timedelta(days=30),
        )
        self.session.add(item)
        self.session.commit()
        tests.create_tokens_acl(self.session, token_id="project-less-foo")

        # Create project-specific token for user foo
        item = pagure.lib.model.Token(
            id="project-specific-foo",
            user_id=2,
            project_id=1,
            expiration=datetime.datetime.utcnow()
            + datetime.timedelta(days=30),
        )
        self.session.add(item)
        self.session.commit()
        tests.create_tokens_acl(self.session, token_id="project-specific-foo")
    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.assertIn(
            '<div class="list-group m-t-1">\n      </div>', output.data)
        self.assertNotIn(
            '<div class="btn-group pull-xs-right">', output.data)

        output = self.app.get('/test/commits/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '<div class="container p-t-3">\n  <div class="row m-b-1">',
            output.data)
        self.assertIn('Add sources file for testing', output.data)
        self.assertIn('Add .gitignore file for testing', output.data)
        self.assertNotIn(
            '<div class="list-group m-t-1">\n      </div>', output.data)
        self.assertEqual(
            output.data.count('class="list-group-item p-l-3"'), 2)
    def setUp(self):
        super(PagureLibGitAuthPagureGitAuthtests, self).setUp()

        tests.create_projects(self.session)
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)
        self.create_project_full("acltest")
        project = pagure.lib.query._get_project(self.session, "acltest")
        # Create non-push deploy key
        non_push_dkey = pagure.lib.model.SSHKey(
            project_id=project.id,
            pushaccess=False,
            public_ssh_key="\n foo bar",
            ssh_short_key="\n foo bar",
            ssh_search_key="\n foo bar",
            creator_user_id=1,  # pingou
        )
        self.session.add(non_push_dkey)
        # Create push deploy key
        push_dkey = pagure.lib.model.SSHKey(
            project_id=project.id,
            pushaccess=True,
            public_ssh_key="\n bar foo",
            ssh_short_key="\n bar foo",
            ssh_search_key="\n bar foo",
            creator_user_id=1,  # pingou
        )
        self.session.add(push_dkey)
        self.session.commit()
    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, 404)
        output = self.app.get('/test/raw/master/f/sources')
        self.assertEqual(output.status_code, 404)

        output = self.app.get('/test/raw/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/feature/f/sources')
        self.assertEqual(output.status_code, 200)
        self.assertEqual('foo\n bar', output.data)
    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)
        output_text = output.get_data(as_text=True)
        self.assertIn('<section class="no-readme">', output_text)
        self.assertIn(
            "The test project's README file is empty or unavailable.",
            output_text,
        )
        self.assertEqual(
            output_text.count('<a class="dropdown-item" href="/test/branch/'),
            0,
        )
    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, 404)
        output = self.app.get("/test/raw/master/f/sources")
        self.assertEqual(output.status_code, 404)

        output = self.app.get("/test/raw/feature")
        self.assertEqual(output.status_code, 200)
        output_text = output.get_data(as_text=True)
        self.assertIn("diff --git a/.gitignore b/.gitignore", output_text)
        self.assertIn("+*~", output_text)

        output = self.app.get("/test/raw/feature/f/sources")
        self.assertEqual(output.status_code, 200)
        self.assertEqual("foo\n bar", output.get_data(as_text=True))
    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)
        output_text = output.get_data(as_text=True)
        self.assertIn(
            '<div class="list-group my-2">\n\n\n          </div>', output_text
        )
        self.assertNotIn('<div class="btn-group pull-xs-right">', output_text)

        output = self.app.get("/test/commits/feature")
        self.assertEqual(output.status_code, 200)
        output_text = output.get_data(as_text=True)
        self.assertIn(
            'Commits <span class="badge badge-secondary"> 2</span>',
            output_text,
        )
        self.assertIn("Add sources file for testing", output_text)
        self.assertIn("Add .gitignore file for testing", output_text)
        self.assertNotIn(
            '<div class="list-group my-2">\n\n\n          </div>', output_text
        )
        self.assertEqual(output_text.count('class="list-group-item "'), 2)
    def setUp(self):
        super(PagureFlaskAppClonetests, self).setUp()

        tests.create_projects(self.session)
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)
        self.create_project_full("clonetest", {"create_readme": "y"})
    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 = '******'
        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'<h3>Settings for test</h3>', 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''})
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskPluginPagureHooktests, self).setUp()

        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(self.path, "repos"))
        tests.create_projects_git(os.path.join(self.path, "repos", "docs"))
    def test_reload_ticket(self, send_email):
        """ Test reloading a ticket from a JSON blob. """
        send_email.return_value = True
        ticket_json = os.path.join(tests.HERE, "test_ticket.json")
        self.assertTrue(os.path.exists(ticket_json))

        tests.create_projects(self.session)

        jsondata = None
        with open(ticket_json) as stream:
            jsondata = json.load(stream)
        self.assertNotEqual(jsondata, None)

        pagure.lib.git.update_ticket_from_git(
            self.session, reponame="test", username=None, issue_uid="foobar", json_data=jsondata
        )

        # Post loading
        repo = pagure.lib.get_project(self.session, "test")
        self.assertEqual(len(repo.issues), 1)
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)

        # Check after re-loading
        self.assertEqual(len(issue.comments), 2)
        self.assertEqual(len(issue.tags), 2)
        self.assertEqual(issue.tags_text, ["future", "feature"])
        self.assertEqual(issue.assignee.username, "pingou")
        self.assertEqual(issue.children, [])
        self.assertEqual(issue.parents, [])

        self.assertTrue(os.path.exists(ticket_json))
        os.unlink(ticket_json)
        self.assertFalse(os.path.exists(ticket_json))
    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('<a href="/test/blob/master/f/sources">', output.data)
        self.assertEqual(
            output.data.count('<span class="oi text-muted" data-glyph="file">'), 1)

        output = self.app.get('/test/tree/master/sources')
        self.assertEqual(output.status_code, 200)
        self.assertIn('<a href="/test/blob/master/f/sources">', output.data)
        self.assertEqual(
            output.data.count('<span class="oi text-muted" data-glyph="file">'), 1)

        output = self.app.get('/test/tree/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn('<a href="/test/blob/master/f/sources">', output.data)
        self.assertIn(
            '<td class-"pagure-table-filehex">\n'
            '                            9f4435', output.data)
        self.assertEqual(
            output.data.count('<span class="oi text-muted" data-glyph="file">'), 1)

        output = self.app.get('/test/tree/maxamilion/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '<a href="/test/blob/maxamilion/feature/f/sources">',
            output.data)
        self.assertIn(
            '<td class-"pagure-table-filehex">\n'
            '                            9f4435', output.data)
        self.assertIn(
            '<td class-"pagure-table-filehex">\n'
            '                            e4e5f6', output.data)
        self.assertEqual(
            output.data.count('<span class="oi text-muted" data-glyph="file">'), 2)

        # Wrong identifier, back onto master
        output = self.app.get('/test/tree/maxamilion/feature/f/.gitignore')
        self.assertEqual(output.status_code, 200)
        self.assertIn('<a href="/test/blob/master/f/sources">', output.data)
        self.assertIn(
            '<td class-"pagure-table-filehex">\n'
            '                            9f4435', output.data)
        self.assertEqual(
            output.data.count('<span class="oi text-muted" data-glyph="file">'), 1)
    def test_index(self):
        """ Test the index endpoint. """

        output = self.app.get("/")
        self.assertEqual(output.status_code, 200)
        self.assertIn('<h2 class=" m-b-1">All Projects ' '<span class="label label-default">0</span></h2>', output.data)

        tests.create_projects(self.session)

        output = self.app.get("/?page=abc")
        self.assertEqual(output.status_code, 200)
        self.assertIn('<h2 class=" m-b-1">All Projects ' '<span class="label label-default">2</span></h2>', output.data)

        # Add a 3rd project with a long description
        item = pagure.lib.model.Project(
            user_id=2,  # foo
            name="test3",
            description="test project #3 with a very long description",
            hook_token="aaabbbeee",
        )
        self.session.add(item)
        self.session.commit()

        user = tests.FakeUser(username="******")
        with tests.user_set(pagure.APP, user):
            output = self.app.get("/?repopage=abc&forkpage=def")
            self.assertIn('Projects <span class="label label-default">1</span>', output.data)
            self.assertIn('Forks <span class="label label-default">0</span>', output.data)
            self.assertEqual(output.data.count("<p>No projects found</p>"), 1)
            self.assertEqual(output.data.count("<p>No group found</p>"), 1)
            self.assertEqual(output.data.count('<div class="card-header">'), 3)
    def test_auth_noacl(self):
        """ Test the authentication when the token does not have any ACL.
        """
        tests.create_projects(self.session)
        tests.create_tokens(self.session)

        output = self.app.post("/api/0/test/new_issue")
        self.assertEqual(output.status_code, 401)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
                "error": "Invalid or expired token. Please visit "
                "https://pagure.org/ to get or renew your API token.",
                "error_code": "EINVALIDTOK",
            },
        )

        headers = {"Authorization": "token aaabbbcccddd"}

        output = self.app.post("/api/0/test/new_issue", headers=headers)
        self.assertEqual(output.status_code, 401)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
                "error": "Invalid or expired token. Please visit "
                "https://pagure.org/ to get or renew your API token.",
                "error_code": "EINVALIDTOK",
            },
        )
Example #19
0
    def test_api_project(self):
        """ Test the api_project method of the flask api. """
        tests.create_projects(self.session)

        # Check before adding
        repo = pagure.lib.get_project(self.session, 'test')
        self.assertEqual(repo.tags, [])

        # Adding a tag
        output = pagure.lib.update_tags(
            self.session, repo, 'infra', 'pingou',
            ticketfolder=None)
        self.assertEqual(output, ['Tag added: infra'])

        # Check after adding
        repo = pagure.lib.get_project(self.session, 'test')
        self.assertEqual(len(repo.tags), 1)
        self.assertEqual(repo.tags_text, ['infra'])

        # Check the API

        # Non-existing project
        output = self.app.get('/api/0/random')
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'error_code': 'ENOPROJECT', 'error': 'Project not found'}
        )

        # Existing project
        output = self.app.get('/api/0/test')
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        data['date_created'] = "1436527638"
        self.assertDictEqual(
            data,
            {
              "close_status": [
                "Invalid",
                "Insufficient data",
                "Fixed",
                "Duplicate"
              ],
              "custom_keys": [],
              "date_created": "1436527638",
              "description": "test project #1",
              "id": 1,
              "milestones": {},
              "name": "test",
              "namespace": None,
              "parent": None,
              "priorities": {},
              "tags": ["infra"],
              "user": {
                "fullname": "PY C",
                "name": "pingou"
              }
            }
        )
    def test_auth_expired(self):
        """ Test the authentication when the token has expired.
        """
        tests.create_projects(self.session)
        tests.create_tokens(self.session)

        output = self.app.post('/api/0/test/new_issue')
        self.assertEqual(output.status_code, 401)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Invalid or expired token. Please visit " \
                  "https://pagure.org/ to get or renew your API token.",
              "error_code": "EINVALIDTOK",
            }
        )

        headers = {'Authorization': 'token expired_token'}

        output = self.app.post('/api/0/test/new_issue', headers=headers)
        self.assertEqual(output.status_code, 401)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Invalid or expired token. Please visit " \
                  "https://pagure.org/ to get or renew your API token.",
              "error_code": "EINVALIDTOK",
            }
        )
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureLibAddUserToProjecttests, self).setUp()

        tests.create_projects(self.session)

        item = pagure.lib.model.User(
            user="******",
            fullname="bar baz",
            password="******",
            default_email="*****@*****.**",
        )
        self.session.add(item)
        item = pagure.lib.model.UserEmail(user_id=3, email="*****@*****.**")
        self.session.add(item)

        self.session.commit()

        # Before
        repo = pagure.lib.query._get_project(self.session, "test")
        self.assertEqual(len(repo.users), 0)

        msg = pagure.lib.query.add_user_to_project(
            session=self.session, project=repo, new_user="******", user="******"
        )
        self.session.commit()
        self.assertEqual(msg, "User added")

        # After
        repo = pagure.lib.query._get_project(self.session, "test")
        self.assertEqual(len(repo.users), 1)
        self.assertEqual(repo.users[0].user, "foo")
        self.assertEqual(repo.admins[0].user, "foo")
    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('<h5>.gitignore', 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('<h5>.gitignore', output.data)
    def setUp(self):
        super(PagureLibGitAuthtests, self).setUp()

        tests.create_projects(self.session)
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)
        self.create_project_full("hooktest")
    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('No content found in this repository', output.data)
        output = self.app.get('/test/tree/master/sources')
        self.assertEqual(output.status_code, 200)
        self.assertIn('No content found in this repository', output.data)

        output = self.app.get('/test/tree/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn('<a href="/test/blob/feature/f/sources">', output.data)
        self.assertIn(
            '<td class-"pagure-table-filehex">\n'
            '                9f4435\n            </td>',
            output.data)

        output = self.app.get('/test/tree/feature/sources')
        self.assertEqual(output.status_code, 200)
        self.assertIn('No content found in this repository', output.data)
    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.assertIn(
            '<h3>Commits list</h3>\n    <ul>\n    </ul>', output.data)
        self.assertTrue(output.data.count('<a href="/test/branch/'), 1)

        output = self.app.get('/test/commits/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn('<h3>Commits list</h3>', output.data)
        self.assertIn('Add sources file for testing', output.data)
        self.assertIn('Add .gitignore file for testing', output.data)
        self.assertNotIn(
            '<h3>Commits list</h3>\n    <ul>\n    </ul>', output.data)
        self.assertTrue(output.data.count('<a href="/test/branch/'), 1)
    def test_index_logged_in(self):
        """
            Test the index endpoint when logged in.
            It should redirect to the userdash.
        """
        tests.create_projects(self.session)

        # Add a 3rd project with a long description
        item = pagure.lib.model.Project(
            user_id=2,  # foo
            name="test3",
            description="test project #3 with a very long description",
            hook_token="aaabbbeeefff",
        )
        self.session.add(item)
        self.session.commit()

        user = tests.FakeUser(username="******")
        with tests.user_set(self.app.application, user):
            output = self.app.get("/", follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            output_text = output.get_data(as_text=True)
            self.assertIn(
                '<span class="btn btn-outline-secondary disabled '
                'opacity-100 border-0 ml-auto font-weight-bold">'
                "1 Projects</span>\n",
                output_text,
            )
            self.assertNotIn(
                '<h3 class="m-0 font-weight-bold">All Projects '
                '<span class="badge badge-secondary">3</span></h3>',
                output_text,
            )
    def test_http_push(self):
        """ Test that the HTTP push endpoint works for repoSpanner. """
        tests.create_projects(self.session)
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)
        self.create_project_full("clonetest", {"create_readme": "y"})

        # Verify the new project is indeed on repoSpanner
        project = pagure.lib.query._get_project(self.session, "clonetest")
        self.assertTrue(project.is_on_repospanner)

        # Unfortunately, actually testing a git clone would need the app to
        # run on a TCP port, which the test environment doesn't do.
        output = self.app.get(
            "/clonetest.git/info/refs?service=git-receive-pack",
            environ_overrides={"REMOTE_USER": "******"},
        )
        self.assertEqual(output.status_code, 200)
        self.assertEqual(
            output.content_type, "application/x-git-receive-pack-advertisement"
        )
        output_text = output.get_data(as_text=True)
        self.assertIn("# service=git-receive-pack", output_text)
        self.assertIn("agent=repoSpanner", output_text)
        self.assertIn("symref=HEAD:refs/heads/master", output_text)
        self.assertIn(" refs/heads/master\x00", output_text)
    def test_index_logged_in_private_project(self):
        """ Test the index endpoint when logged in with a private project. """
        tests.create_projects(self.session)

        # Add a 3rd project with a long description
        item = pagure.lib.model.Project(
            user_id=2,  # foo
            name="test3",
            description="test project #3 with a very long description",
            hook_token="aaabbbeeefff",
            private=True,
        )
        self.session.add(item)
        self.session.commit()

        user = tests.FakeUser(username="******")
        with tests.user_set(self.app.application, user):
            output = self.app.get("/dashboard/projects")
            self.assertEqual(output.status_code, 200)
            output_text = output.get_data(as_text=True)
            self.assertIn(
                '<h4 class="font-weight-bold mb-0">My Projects</h4>\n'
                '          <span class="btn btn-outline-secondary disabled'
                ' opacity-100 border-0 ml-auto font-weight-bold">1 Projects</span>\n',
                output_text,
            )
            self.assertIn(
                '<span title="Private project" class="text-danger '
                'fa fa-fw fa-lock"></span>',
                output_text,
            )
            self.assertEqual(output_text.count('title="Private project"'), 1)
    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, 404)

        output = self.app.get("/test/blob/feature/f/sources")
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '<a href="/test/tree/feature">' '<span class="oi" data-glyph="random"></span>&nbsp; feature</a>',
            output.data,
        )
        self.assertIn(
            '</li><li class="active"><span class="oi" data-glyph="file">' "</span>&nbsp; sources</li>", output.data
        )
        self.assertIn('<td class="cell2"><pre>foo</pre></td>', output.data)
    def test_auth(self):
        """ Test the token based authentication.
        """
        tests.create_projects(self.session)
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

        output = self.app.post('/api/0/test/new_issue')
        self.assertEqual(output.status_code, 401)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Invalid or expired token. Please visit " \
                  "https://pagure.org/ to get or renew your API token.",
              "error_code": "EINVALIDTOK",
            }
        )

        headers = {'Authorization': 'token aaabbbcccddd'}

        output = self.app.post('/api/0/test/new_issue', headers=headers)
        self.assertEqual(output.status_code, 400)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Invalid or incomplete input submited",
              "error_code": "EINVALIDREQ",
            }
        )
Example #31
0
    def test_api_whoami_auth(self):
        """ Test the api_whoami function with a valid token. """
        tests.create_projects(self.session)
        tests.create_tokens(self.session)

        headers = {"Authorization": "token aaabbbcccddd"}

        output = self.app.post("/api/0/-/whoami", headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.get_data(as_text=True))
        self.assertEqual(data, {"username": "******"})
Example #32
0
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(ViewCommitFlagtests, self).setUp()

        tests.create_projects(self.session)
        tests.create_tokens(self.session)

        # Add a README to the git repo - First commit
        tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git"))
        repo = pygit2.Repository(os.path.join(self.path, "repos", "test.git"))
        self.commit = repo.revparse_single("HEAD")
Example #33
0
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskApiIssueCommenttests, self).setUp()

        pagure.APP.config['TESTING'] = True
        pagure.SESSION = self.session
        pagure.api.SESSION = self.session
        pagure.api.issue.SESSION = self.session
        pagure.lib.SESSION = self.session

        pagure.APP.config['TICKETS_FOLDER'] = None

        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(self.path, 'tickets'))
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

        # Create normal issue
        repo = pagure.get_authorized_project(self.session, 'test')
        msg = pagure.lib.new_issue(
            session=self.session,
            repo=repo,
            title='Test issue #1',
            content='We should work on this',
            user='******',
            ticketfolder=None,
            private=False,
        )
        self.session.commit()
        self.assertEqual(msg.title, 'Test issue #1')

        # Create private issue
        msg = pagure.lib.new_issue(
            session=self.session,
            repo=repo,
            title='Test issue #2',
            content='We should work on this',
            user='******',
            ticketfolder=None,
            private=True,
        )
        self.session.commit()
        self.assertEqual(msg.title, 'Test issue #2')

        # Create project-less token for user foo
        item = pagure.lib.model.Token(id='project-less-foo',
                                      user_id=2,
                                      project_id=None,
                                      expiration=datetime.datetime.utcnow() +
                                      datetime.timedelta(days=30))
        self.session.add(item)
        self.session.commit()
        tests.create_tokens_acl(self.session, token_id='project-less-foo')
    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(self.path, "repos"), bare=True)

        user = tests.FakeUser()
        user.username = "******"
        with tests.user_set(self.app.application, user):
            # Get the CSRF token
            output = self.app.get("/test/settings")
            output_text = output.get_data(as_text=True)
            csrf_token = output_text.split(
                'name="csrf_token" type="hidden" value="')[1].split('">')[0]

            data = {
                "milestones": [1, 2],
                "milestone_1_name": "v1.0",
                "milestone_2_name": "v2.0",
                "milestone_1_date": "",
                "milestone_2_date": "",
                "csrf_token": csrf_token,
            }
            output = self.app.post("/test/update/milestones",
                                   data=data,
                                   follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            output_text = output.get_data(as_text=True)
            # Check the redirect
            self.assertIn("<title>Settings - test - Pagure</title>",
                          output_text)
            self.assertIn(
                '<h5 class="pl-2 font-weight-bold text-muted">'
                "Project Settings</h5>\n",
                output_text,
            )
            self.assertIn("Milestones updated", output_text)
            # Check the result of the action -- Milestones recorded
            self.session.commit()
            repo = pagure.lib.query.get_authorized_project(
                self.session, "test")
            self.assertEqual(
                repo.milestones,
                {
                    "v1.0": {
                        "active": False,
                        "date": None
                    },
                    "v2.0": {
                        "active": False,
                        "date": None
                    },
                },
            )
Example #35
0
    def test_index_commit_access_while_admin(self):
        """ Test the index endpoint filter for commit access only when user
        is an admin. """
        tests.create_projects(self.session)

        # Add a 3rd project just for foo
        item = pagure.lib.model.Project(
            user_id=2,  # foo
            name="test3",
            description="test project #3 with a very long description",
            hook_token="aaabbbeeefff",
        )
        self.session.add(item)
        self.session.commit()

        user = tests.FakeUser(username="******")
        with tests.user_set(self.app.application, user):
            # Before
            output = self.app.get("/dashboard/projects?acl=commit")
            self.assertEqual(output.status_code, 200)
            output_text = output.get_data(as_text=True)
            self.assertIn(
                '<span class="btn btn-outline-secondary disabled opacity-100'
                ' border-0 ml-auto font-weight-bold">1 Projects</span>',
                output_text,
            )
            self.assertIn(
                '<div class="text-center">No Projects match this filter</div>',
                output_text,
            )

            # Add foo to test with admin level
            project = pagure.lib.query._get_project(self.session, "test")
            msg = pagure.lib.query.add_user_to_project(
                self.session,
                project=project,
                new_user="******",
                user="******",
                access="admin",
            )
            self.session.commit()
            self.assertEqual(msg, "User added")

            # After
            self.assertIn(
                '<span class="btn btn-outline-secondary disabled opacity-100'
                ' border-0 ml-auto font-weight-bold">1 Projects</span>',
                output_text,
            )
            self.assertIn(
                '<div class="text-center">No Projects match this filter</div>',
                output_text,
            )
Example #36
0
    def test_get_relation_fixes(self):
        """ Test the get_relation function of pagure.lib.link with fixes.
        """

        link = pagure.lib.link.get_relation(
            self.session,
            reponame='test',
            namespace=None,
            username=None,
            text=COMMENTS[0],
            reftype='fixes',
        )
        self.assertEqual(link, [])

        tests.create_projects(self.session)

        link = pagure.lib.link.get_relation(
            self.session,
            reponame='test',
            namespace=None,
            username=None,
            text=COMMENTS[2],
            reftype='fixes',
        )
        self.assertEqual(link, [])

        # Create the issue
        repo = pagure.lib.get_project(self.session, 'test')
        pagure.lib.new_issue(
            self.session,
            repo,
            title='issue 3',
            content='content issue 3',
            user='******',
            ticketfolder=None,
            issue_id=3,
            notify=False)
        self.session.commit()

        for idx, comment in enumerate(COMMENTS):
            link = pagure.lib.link.get_relation(
                self.session,
                reponame='test',
                namespace=None,
                username=None,
                text=comment,
                reftype='fixes')
            if idx == 2:
                self.assertEqual(
                    str(link),
                    '[Issue(3, project:test, user:pingou, title:issue 3)]')
            else:
                self.assertEqual(link, [])
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskGiveRepotests, self).setUp()

        pagure.config.config['VIRUS_SCAN_ATTACHMENTS'] = False
        pagure.config.config['UPLOAD_FOLDER_URL'] = '/releases/'
        pagure.config.config['UPLOAD_FOLDER_PATH'] = os.path.join(
            self.path, 'releases')

        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True)
        self._check_user(user='******')
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskApiProjectGitTagstests, self).setUp()

        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(self.path, "repos"), bare=True)
        tests.add_commit_git_repo(
            folder=os.path.join(self.path, "repos", "test.git"))
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)
        # token for user = pingou (user_id = 1)
        self.headers = {"Authorization": "token aaabbbcccddd"}
Example #39
0
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskGiveRepotests, self).setUp()

        pagure.config.config["VIRUS_SCAN_ATTACHMENTS"] = False
        pagure.config.config["UPLOAD_FOLDER_URL"] = "/releases/"
        pagure.config.config["UPLOAD_FOLDER_PATH"] = os.path.join(
            self.path, "releases")

        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(self.path, "repos"), bare=True)
        self._check_user(user="******")
    def test_api_project_tag_delete_wrong_tag(self):
        """ Test the api_project_tag_delete method of flask api. """
        tests.create_projects(self.session)
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

        headers = {"Authorization": "token aaabbbcccddd"}
        output = self.app.delete("/api/0/test/tag/blue", headers=headers)
        self.assertEqual(output.status_code, 404)
        expected_rv = {"error": "Tag not found", "error_code": "ENOTAG"}
        data = json.loads(output.get_data(as_text=True))
        self.assertDictEqual(data, expected_rv)
Example #41
0
    def test_api_git_tags(self):
        """ Test the api_git_tags method of the flask api. """
        tests.create_projects(self.session)

        # 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-fork-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', '*****@*****.**')
        committer = pygit2.Signature(
            'Cecil Committer', '*****@*****.**')
        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:refs/heads/master'
        ori_remote = clone_repo.remotes[0]
        PagureRepo.push(ori_remote, refname)

        # Tag our first commit
        first_commit = repo.revparse_single('HEAD')
        tagger = pygit2.Signature('Alice Doe', '*****@*****.**', 12347, 0)
        repo.create_tag(
            "0.0.1", first_commit.oid.hex, pygit2.GIT_OBJ_COMMIT, tagger,
            "Release 0.0.1")

        # Check tags
        output = self.app.get('/api/0/test/git/tags')
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'tags': ['0.0.1'], 'total_tags': 1}
        )
    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('<a href="/test/blob/master/f/sources">', output.data)
        self.assertEqual(
            output.data.count(
                '<span class="oi text-muted" data-glyph="file">'), 1)

        output = self.app.get('/test/tree/master/sources')
        self.assertEqual(output.status_code, 200)
        self.assertIn('<a href="/test/blob/master/f/sources">', output.data)
        self.assertEqual(
            output.data.count(
                '<span class="oi text-muted" data-glyph="file">'), 1)

        output = self.app.get('/test/tree/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn('<a href="/test/blob/master/f/sources">', output.data)
        self.assertEqual(
            output.data.count(
                '<span class="oi text-muted" data-glyph="file">'), 1)

        output = self.app.get('/test/tree/maxamilion/feature')
        self.assertEqual(output.status_code, 200)
        self.assertIn('<a href="/test/blob/maxamilion/feature/f/sources">',
                      output.data)
        self.assertEqual(
            output.data.count(
                '<span class="oi text-muted" data-glyph="file">'), 2)

        # Wrong identifier, back onto master
        output = self.app.get('/test/tree/maxamilion/feature/f/.gitignore')
        self.assertEqual(output.status_code, 200)
        self.assertIn('<a href="/test/blob/master/f/sources">', output.data)
        self.assertEqual(
            output.data.count(
                '<span class="oi text-muted" data-glyph="file">'), 1)
Example #43
0
    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(
            '''<ol class="breadcrumb p-0 bg-transparent mb-0">
          <li class="breadcrumb-item">
            <a href="/test/tree/master">
              <span class="fa fa-random">
              </span>&nbsp; master
            </a>
          </li>
          <li class="active breadcrumb-item">
            <span class="fa fa-file" data-glyph="">
            </span>&nbsp; sources
          </li>
        </ol>''', output.get_data(as_text=True))

        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)
        output_text = output.get_data(as_text=True)
        self.assertIn(
            '''<ol class="breadcrumb p-0 bg-transparent mb-0">
          <li class="breadcrumb-item">
            <a href="/test/tree/maxamilion/feature">
              <span class="fa fa-random">
              </span>&nbsp; maxamilion/feature
            </a>
          </li>
          <li class="active breadcrumb-item">
            <span class="fa fa-file" data-glyph="">
            </span>&nbsp; .gitignore
          </li>
        </ol>''', output_text)
        self.assertIn(
            '<pre class="syntaxhighlightblock"><code>*~</code></pre>',
            output_text)
Example #44
0
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureLibGitMirrorProjecttests, self).setUp()

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

        # Make the test project mirrored from elsewhere
        self.project = pagure.lib.query.get_authorized_project(
            self.session, "test")
        self.project.mirrored_from = "https://example.com/foo/bar.git"
        self.session.add(self.project)
        self.session.commit()
Example #45
0
    def test_view_docs_project_no_git(self):
        """ Test the view_docs endpoint with a project that has no
        corresponding git repo.
        """
        tests.create_projects(self.session)

        output = self.app.get('/test/docs', follow_redirects=True)
        self.assertEqual(output.status_code, 404)
        self.assertTrue('<p>Documentation not found</p>' in output.data)

        output = self.app.get('/test', follow_redirects=True)
        self.assertEqual(output.status_code, 404)
        self.assertTrue('<p>Documentation not found</p>' in output.data)
    def test_view_commit_old_with_bogus_url(self):
        """ Test the view_commit_old endpoint. """

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

        # Add a README to the git repo - First commit
        tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git'))
        pygit2.Repository(os.path.join(self.path, 'repos', 'test.git'))

        # View first commit
        output = self.app.get('/apple-touch-icon-152x152-precomposed.png')
        self.assertEqual(output.status_code, 404)
Example #47
0
    def test_view_history_file_no_git_content(self):
        """ Test the view_history_file endpoint """
        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(self.path, "repos"), bare=True)

        output = self.app.get("/test/history/sources")
        # project and associated repo, but no file
        self.assertEqual(output.status_code, 404)
        output_text = output.get_data(as_text=True)
        self.assertIn("<title>Page not found :'( - Pagure</title>",
                      output_text)
        self.assertIn("<h2>Page not found (404)</h2>", output_text)
        self.assertIn("<p>Empty repo cannot have a file</p>", output_text)
    def test_plugin_is_enabled_for(self, load):
        """ Test the is_enabled_for method of plugins is properly
        handled by pagure.lib.plugins.get_enabled_plugins.
        """
        tests.create_projects(self.session)
        project = pagure.lib.query._get_project(self.session, "test")

        load.return_value = [EnabledForAll]
        self.assertEqual(pagure.lib.plugins.get_enabled_plugins(project),
                         [(EnabledForAll, None)])

        load.return_value = [DisabledForAll]
        self.assertEqual(pagure.lib.plugins.get_enabled_plugins(project), [])
Example #49
0
 def test_pr_edit_no_pull_requests(self):
     """ Test the edit pull request endpoint """
     tests.create_projects(self.session)
     tests.create_projects_git(os.path.join(self.path, "repos"), bare=True)
     user = tests.FakeUser()
     with tests.user_set(self.app.application, user):
         output = self.app.get("/test/pull-request/1/edit")
         self.assertEqual(output.status_code, 404)
         output_text = output.get_data(as_text=True)
         self.assertIn(
             "<title>Page not found :'( - Pagure</title>", output_text
         )
         self.assertIn("<p>Pull-request not found</p>", output_text)
Example #50
0
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskPrNoSourcestests, self).setUp()

        pagure.APP.config['TESTING'] = True
        pagure.SESSION = self.session
        pagure.lib.SESSION = self.session
        pagure.ui.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

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

        # Create foo's fork of pingou's test project
        item = pagure.lib.model.Project(
            user_id=2,  # foo
            name='test',
            description='test project #1',
            hook_token='aaabbb',
            is_fork=True,
            parent_id=1,
        )
        self.session.add(item)
        self.session.commit()
        # Create the fork's git repo
        repo_path = os.path.join(self.path, 'repos', item.path)
        pygit2.init_repository(repo_path, bare=True)

        project = pagure.get_authorized_project(self.session, 'test')
        fork = pagure.get_authorized_project(self.session, 'test', user='******')

        self.set_up_git_repo(repo=project, fork=fork)

        # Ensure things got setup straight
        project = pagure.get_authorized_project(self.session, 'test')
        self.assertEqual(len(project.requests), 1)

        # wait for the worker to process the task
        path = os.path.join(self.path, 'repos', 'test.git', 'refs', 'pull',
                            '1', 'head')
        cnt = 0
        while not os.path.exists(path):
            time.sleep(0.1)
            cnt += 1
            if cnt == 100:
                # We're about 10 seconds in, let's bail
                raise Exception('Sorry, worker took too long')
Example #51
0
    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(self.app.application, 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)
        output_text = output.get_data(as_text=True)
        self.assertEqual(output_text.count('<span class="commitdate"'), 1)
        self.assertIn(
            '<span class="font-weight-bold btn btn-sm btn-success disabled opacity-100">'
            "+1</span>\n",
            output_text,
        )
        self.assertIn(
            '<div class="btn btn-outline-success disabled opacity-100 border-0 font-weight-bold">\n'
            "    file added\n",
            output_text,
        )

        user = tests.FakeUser()
        with tests.user_set(self.app.application, user):
            output = self.app.get("/test/diff/master..maxamilion/feature")
            self.assertEqual(output.status_code, 200)
            output_text = output.get_data(as_text=True)
            self.assertEqual(output_text.count('<span class="commitdate"'), 1)
            self.assertIn(
                '<span class="font-weight-bold btn btn-sm btn-success disabled opacity-100">'
                "+1</span>\n",
                output_text,
            )
            self.assertIn(
                '<div class="btn btn-outline-success disabled opacity-100 border-0 font-weight-bold">\n'
                "    file added\n",
                output_text,
            )
    def setUp(self):
        """Set up the environnment, run before every test."""
        super(StreamingServerTests, self).setUp()

        # Make sure the server uses the existing session
        pss.SESSION = self.session

        # Mock send_email, we never want to send or see emails here.
        self.mailpatcher = mock.patch('pagure.lib.notify.send_email')
        self.mailpatcher.start()

        # Setup projects
        tests.create_projects(self.session)
        self.repo = pagure.lib._get_project(self.session, 'test')
        self.repo2 = pagure.lib._get_project(self.session, 'test2')

        # Disable repo 2's issue tracker and PR tracker
        pagure.lib.update_project_settings(session=self.session,
                                           repo=self.repo2,
                                           user='******',
                                           settings={
                                               'issue_tracker': False,
                                               'pull_requests': False,
                                           })

        # Create a public issue
        pagure.lib.new_issue(session=self.session,
                             repo=self.repo,
                             title='Test issue',
                             content='We should work on this',
                             user='******',
                             ticketfolder=None)

        # Create a private issue
        pagure.lib.new_issue(session=self.session,
                             repo=self.repo,
                             title='Private issue #2',
                             content='The world can see my p**n folder',
                             user='******',
                             private=True,
                             ticketfolder=None)

        # Create a PR
        pagure.lib.new_pull_request(session=self.session,
                                    repo_from=self.repo,
                                    repo_to=self.repo,
                                    branch_from='feature',
                                    branch_to='master',
                                    title='Test PR',
                                    user='******',
                                    requestfolder=None)
Example #53
0
    def test_do_login_and_redirect(self):
        """ Test the do_login endpoint with a non-default redirect. """
        # This has all the data needed
        data = {
            'username': '******',
            'password': '******',
            'csrf_token': self.get_csrf(url='/login/'),
            'next_url': 'http://localhost/test/',
        }

        # Create a local user
        self.test_new_user()
        self.session.commit()

        # Confirm the user so that we can log in
        item = pagure.lib.query.search_user(self.session, username='******')
        self.assertEqual(item.user, 'foouser')
        self.assertNotEqual(item.token, None)

        # Remove the token
        item.token = None
        self.session.add(item)
        self.session.commit()

        # Check the user
        item = pagure.lib.query.search_user(self.session, username='******')
        self.assertEqual(item.user, 'foouser')
        self.assertEqual(item.token, None)

        # Add a test project to the user
        tests.create_projects(self.session, user_id=3)
        tests.create_projects_git(os.path.join(self.path, 'repos'))
        output = self.app.get('/test')
        output_text = output.get_data(as_text=True)
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '<title>Overview - test - Pagure</title>', output_text)

        # Login and redirect to the test project
        output = self.app.post(
            '/dologin', data=data, follow_redirects=True,
            environ_base={'REMOTE_ADDR': '127.0.0.1'})
        self.assertEqual(output.status_code, 200)
        output_text = output.get_data(as_text=True)
        self.assertIn(
            '<title>Overview - test - Pagure</title>', output_text)
        self.assertIn(
            '<a class="dropdown-item" '
            'href="/logout/?next=http://localhost/test/">', output_text)
        self.assertIn(
            '<span class="d-none d-md-inline">Settings</span>', output_text)
Example #54
0
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureAdminAdminRefreshGitolitetests, self).setUp()

        self.configfile = os.path.join(self.path, 'config')
        self.dbpath = "sqlite:///%s/pagure_dev.sqlite" % self.path
        with open(self.configfile, 'w') as stream:
            stream.write('DB_URL="%s"\n' % self.dbpath)

        os.environ['PAGURE_CONFIG'] = self.configfile

        createdb = os.path.abspath(
            os.path.join(tests.HERE, '..', 'createdb.py'))
        cmd = ['python', createdb]
        _get_ouput(cmd)

        self.session = pagure.lib.model.create_tables(
            self.dbpath, acls=pagure.APP.config.get('ACLS', {}))

        # Create the user pingou
        item = pagure.lib.model.User(
            user='******',
            fullname='PY C',
            password='******',
            default_email='*****@*****.**',
        )
        self.session.add(item)
        item = pagure.lib.model.UserEmail(user_id=1, email='*****@*****.**')
        self.session.add(item)
        self.session.commit()

        # Create a couple of projects
        tests.create_projects(self.session)

        # Add a group
        msg = pagure.lib.add_group(
            self.session,
            group_name='foo',
            display_name='foo group',
            description=None,
            group_type='bar',
            user='******',
            is_admin=False,
            blacklist=[],
        )
        self.session.commit()
        self.assertEqual(msg, 'User `pingou` added to the group `foo`.')

        # Make the imported pagure use the correct db session
        pagure.cli.admin.SESSION = self.session
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(TestStarProjectUI, 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

        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True)
Example #56
0
    def test_index_fork_without_parent(self):
        """ Test the index view: forks should display either their parent
        project or mention that it was deleted. """
        tests.create_projects(self.session)

        # Add a 3rd project just for foo
        item = pagure.lib.model.Project(
            user_id=2,  # foo
            name='test3',
            description='test project #3',
            hook_token='aaabbbeeefff',
            is_fork=True,
            parent_id=1,
        )
        self.session.add(item)
        self.session.commit()

        user = tests.FakeUser(username='******')
        with tests.user_set(self.app.application, user):
            # Before
            output = self.app.get('/')
            self.assertEqual(output.status_code, 200)

            self.assertIn(
                'My Forks <span class="label label-default">1</span>',
                output.data)
            segment = output.data.split('My Forks')[1].split('My Groups')[0]
            self.assertRegexpMatches(
                segment,
                r'foo/test3(\s*<[^>]+?>\s*)*?forked from(\s*<[^>]+?>\s*)*?test'
            )

            # Delete the parent (or fake it)
            proj = pagure.lib._get_project(self.session, 'test3', user='******')
            proj.parent_id = None
            self.session.add(proj)
            self.session.commit()

            # Check page again
            output = self.app.get('/')
            self.assertEqual(output.status_code, 200)

            self.assertIn(
                'My Forks <span class="label label-default">1</span>',
                output.data)
            segment = output.data.split('My Forks')[1].split('My Groups')[0]
            self.assertRegexpMatches(
                segment,
                r'foo/test3(\s*<[^>]+?>\s*)*?forked from a deleted repository'
            )
Example #57
0
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskRepoViewFiletests, self).setUp()
        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True)

        # Add some content to the git repo
        tests.add_content_git_repo(os.path.join(self.path, 'repos',
                                                'test.git'))
        tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git'))
        tests.add_binary_git_repo(os.path.join(self.path, 'repos', 'test.git'),
                                  'test.jpg')
        tests.add_binary_git_repo(os.path.join(self.path, 'repos', 'test.git'),
                                  'test_binary')
Example #58
0
    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(self.path, 'repos'), bare=True)

        user = tests.FakeUser()
        user.username = '******'
        with tests.user_set(self.app.application, user):
            # Get the CSRF token
            output = self.app.get('/test/settings')
            output_text = output.get_data(as_text=True)
            csrf_token = output_text.split(
                'name="csrf_token" type="hidden" value="')[1].split('">')[0]

            data = {
                'milestones': [1, 2],
                'milestone_1_name': 'v1.0',
                'milestone_2_name': 'v2.0',
                'milestone_1_date': '',
                'milestone_2_date': '',
                'csrf_token': csrf_token,
            }
            output = self.app.post('/test/update/milestones',
                                   data=data,
                                   follow_redirects=True)
            self.assertEqual(output.status_code, 200)
            output_text = output.get_data(as_text=True)
            # Check the redirect
            self.assertIn('<title>Settings - test - Pagure</title>',
                          output_text)
            self.assertIn(
                '<h5 class="pl-2 font-weight-bold text-muted">'
                'Project Settings</h5>\n', output_text)
            self.assertIn('Milestones updated', output_text)
            # Check the result of the action -- Milestones recorded
            self.session.commit()
            repo = pagure.lib.query.get_authorized_project(
                self.session, 'test')
            self.assertEqual(
                repo.milestones, {
                    'v1.0': {
                        'active': False,
                        'date': None
                    },
                    'v2.0': {
                        'active': False,
                        'date': None
                    }
                })
Example #59
0
    def test_pullrequest__repr__(self, p_send_email, p_ugt):
        """ Test the PullRequest.__repr__ function of pagure.lib.model. """
        p_send_email.return_value = True
        p_ugt.return_value = True

        tests.create_projects(self.session)
        # Create a forked repo
        item = pagure.lib.model.Project(
            user_id=1,  # pingou
            name="test",
            description="test project #1",
            is_fork=True,
            parent_id=1,
            hook_token="aaabbbyyy",
        )
        self.session.commit()
        self.session.add(item)

        repo = pagure.lib.query.get_authorized_project(self.session, "test")
        forked_repo = pagure.lib.query.get_authorized_project(self.session,
                                                              "test",
                                                              user="******")

        # Create an pull-request
        req = pagure.lib.query.new_pull_request(
            session=self.session,
            repo_from=forked_repo,
            branch_from="master",
            repo_to=repo,
            branch_to="master",
            title="test pull-request",
            user="******",
        )
        self.assertEqual(req.id, 1)
        self.assertEqual(req.title, "test pull-request")

        self.assertEqual(
            str(req),
            "PullRequest(1, project:test, user:pingou, "
            "title:test pull-request)",
        )

        request = pagure.lib.query.search_pull_requests(self.session,
                                                        requestid=1)
        self.assertEqual(
            str(request),
            "PullRequest(1, project:test, user:pingou, "
            "title:test pull-request)",
        )
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureLibTaskServicesWithWebHooktests, self).setUp()

        pagure.config.config['REQUESTS_FOLDER'] = None
        self.sshkeydir = os.path.join(self.path, 'sshkeys')
        pagure.config.config['MIRROR_SSHKEYS_FOLDER'] = self.sshkeydir

        tests.create_projects(self.session)
        project = pagure.lib.query._get_project(self.session, 'test')
        settings = project.settings
        settings['Web-hooks'] = 'http://foo.com/api/flag\nhttp://bar.org/bar'
        project.settings = settings
        self.session.add(project)
        self.session.commit()