Пример #1
0
    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",
            }
        )
Пример #2
0
    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_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",
            },
        )
    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 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 setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskApiProjectBlockuserTests, self).setUp()

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

        item = pagure.lib.model.Token(
            id="aaabbbcccdddeee",
            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="aaabbbcccdddeee")

        project = pagure.lib.query.get_authorized_project(self.session, "test")
        self.assertEqual(project.block_users, [])
        self.blocked_users = []

        project = pagure.lib.query.get_authorized_project(
            self.session, "test2"
        )
        project.block_users = ["foo"]
        self.session.add(project)
        self.session.commit()
Пример #7
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.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",
            }
        )
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskApiProjectUpdateWatchTests, self).setUp()

        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.lib.query.get_authorized_project(self.session, "test")
        msg = pagure.lib.query.new_issue(
            session=self.session,
            repo=repo,
            title="Test issue #1",
            content="We should work on this",
            user="******",
            private=False,
        )
        self.session.commit()
        self.assertEqual(msg.title, "Test issue #1")

        # Create project-less token for user foo
        item = pagure.lib.model.Token(
            id="project-less-foo",
            user_id=1,
            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")
Пример #9
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."]
              }
            }
        )
Пример #10
0
    def test_api_view_group_authenticated(self):
        """
            Test the api_view_group method of the flask api with an
            authenticated user. The tested group has one member.
        """
        tests.create_tokens(self.session)

        headers = {"Authorization": "token aaabbbcccddd"}
        output = self.app.get("/api/0/group/some_group", headers=headers)
        self.assertEqual(output.status_code, 200)
        exp = {
            "display_name": "Some Group",
            "description": None,
            "creator": {
                "fullname": "PY C",
                "default_email": "*****@*****.**",
                "emails": ["*****@*****.**", "*****@*****.**"],
                "name": "pingou",
            },
            "members": ["pingou"],
            "date_created": "1492020239",
            "group_type": "user",
            "name": "some_group",
        }
        data = json.loads(output.get_data(as_text=True))
        data["date_created"] = "1492020239"
        self.assertDictEqual(data, exp)
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskApiGetPRFlagtests, self).setUp()

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

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

        # Create a pull-request
        repo = pagure.lib.query.get_authorized_project(self.session, "test")
        forked_repo = pagure.lib.query.get_authorized_project(
            self.session, "test"
        )
        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.session.commit()
        self.assertEqual(req.id, 1)
        self.assertEqual(req.title, "test pull-request")

        # Check flags before
        self.session.commit()
        request = pagure.lib.query.search_pull_requests(
            self.session, project_id=1, requestid=1
        )
        self.assertEqual(len(request.flags), 0)
Пример #12
0
    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")
Пример #13
0
    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 setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskApiForkUpdatetests, self).setUp()

        tests.create_projects(self.session)
        tests.add_content_git_repo(
            os.path.join(self.path, "repos", "test.git")
        )

        # Fork
        project = pagure.lib.query.get_authorized_project(self.session, "test")
        task = pagure.lib.query.fork_project(
            session=self.session, user="******", repo=project
        )
        self.session.commit()
        self.assertEqual(
            task.get(),
            {
                "endpoint": "ui_ns.view_repo",
                "repo": "test",
                "namespace": None,
                "username": "******",
            },
        )

        tests.add_readme_git_repo(
            os.path.join(self.path, "repos", "forks", "pingou", "test.git")
        )
        project = pagure.lib.query.get_authorized_project(self.session, "test")
        fork = pagure.lib.query.get_authorized_project(
            self.session, "test", user="******"
        )

        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

        req = pagure.lib.query.new_pull_request(
            session=self.session,
            repo_from=fork,
            branch_from="master",
            repo_to=project,
            branch_to="master",
            title="test pull-request",
            user="******",
        )
        self.session.commit()
        self.assertEqual(req.id, 1)
        self.assertEqual(req.title, "test pull-request")

        # Assert the PR is open
        self.session = pagure.lib.query.create_session(self.dbpath)
        project = pagure.lib.query.get_authorized_project(self.session, "test")
        self.assertEqual(len(project.requests), 1)
        self.assertEqual(project.requests[0].status, "Open")
        # Check how the PR renders in the API and the UI
        output = self.app.get("/api/0/test/pull-request/1")
        self.assertEqual(output.status_code, 200)
        output = self.app.get("/test/pull-request/1")
        self.assertEqual(output.status_code, 200)
Пример #15
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": "******"})
    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")
Пример #17
0
    def test_api_new_issue(self):
        """ Test the api_new_issue method of the flask api. """
        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(tests.HERE, "tickets"))
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

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

        # Valid token, wrong project
        output = self.app.post("/api/0/test2/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",
            },
        )

        # No input
        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"})

        data = {"title": "test issue"}

        # Invalid repo
        output = self.app.post("/api/0/foo/new_issue", data=data, headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(data, {"error": "Project not found", "error_code": "ENOPROJECT"})

        # Incomplete request
        output = self.app.post("/api/0/test/new_issue", data=data, 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"})

        data = {"title": "test issue", "issue_content": "This issue needs attention"}

        # Valid request
        output = self.app.post("/api/0/test/new_issue", data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(data, {"message": "Issue created"})
Пример #18
0
    def test_api_view_group_two_members_authenticated(self):
        """
            Test the api_view_group method of the flask api with an
            authenticated user. The tested group has two members.
        """
        user = pagure.lib.model.User(
            user="******",
            fullname="Matt Prahl",
            password="******",
            default_email="*****@*****.**",
        )
        self.session.add(user)
        self.session.commit()
        group = pagure.lib.query.search_groups(
            self.session, group_name="some_group"
        )
        result = pagure.lib.query.add_user_to_group(
            self.session, user.username, group, user.username, True
        )
        self.assertEqual(
            result, "User `mprahl` added to the group `some_group`."
        )
        self.session.commit()

        tests.create_tokens(self.session)

        headers = {"Authorization": "token aaabbbcccddd"}
        output = self.app.get("/api/0/group/some_group", headers=headers)
        self.assertEqual(output.status_code, 200)
        exp = {
            "display_name": "Some Group",
            "description": None,
            "creator": {
                "fullname": "PY C",
                "default_email": "*****@*****.**",
                "emails": ["*****@*****.**", "*****@*****.**"],
                "name": "pingou",
            },
            "members": ["pingou", "mprahl"],
            "date_created": "1492020239",
            "group_type": "user",
            "name": "some_group",
        }
        self.maxDiff = None
        data = json.loads(output.get_data(as_text=True))
        data["date_created"] = "1492020239"
        self.assertDictEqual(data, exp)
Пример #19
0
    def test_api_new_project_user_ns(self, p_gga):
        """ Test the api_new_project method of the flask api. """
        pagure.APP.config['USER_NAMESPACE'] = True
        p_gga.return_value = True

        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)

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

        # Create a project with the user namespace feature on
        data = {
            'name': 'testproject',
            'description': 'Just another small test project',
        }

        # Valid request
        output = self.app.post(
            '/api/0/new/', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Project "pingou/testproject" created'}
        )

        # Create a project with a namespace and the user namespace feature on
        pagure.APP.config['ALLOWED_PREFIX'] = ['testns']
        data = {
            'name': 'testproject2',
            'namespace': 'testns',
            'description': 'Just another small test project',
        }

        # Valid request
        output = self.app.post(
            '/api/0/new/', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Project "testns/testproject2" created'}
        )

        pagure.APP.config['USER_NAMESPACE'] = False
Пример #20
0
    def test_api_whoami_invalid_auth(self):
        """ Test the api_whoami function with an invalid token. """
        tests.create_projects(self.session)
        tests.create_tokens(self.session)

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

        output = self.app.post("/api/0/-/whoami", headers=headers)
        self.assertEqual(output.status_code, 401)
        data = json.loads(output.get_data(as_text=True))
        self.assertEqual(
            data,
            {
                "error": "Invalid or expired token. Please visit "
                "http://localhost.localdomain/settings#api-keys to get or "
                "renew your API token.",
                "error_code": "EINVALIDTOK",
                "errors": "Invalid token",
            },
        )
Пример #21
0
    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.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name,
                         data['error_code'])
        self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error'])

        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.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name,
                         data['error_code'])
        self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error'])
Пример #22
0
    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.get_data(as_text=True))
        self.assertEqual(
            pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"]
        )
        self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"])

        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.get_data(as_text=True))
        self.assertEqual(
            pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"]
        )
        self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"])
Пример #23
0
    def test_api_whoami_invalid_auth(self):
        """ Test the api_whoami function with an invalid token. """
        tests.create_projects(self.session)
        tests.create_tokens(self.session)

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

        output = self.app.post("/api/0/-/whoami", headers=headers)
        self.assertEqual(output.status_code, 401)
        data = json.loads(output.get_data(as_text=True))
        self.assertEqual(
            data,
            {
                "error":
                "Invalid or expired token. Please visit "
                "http://localhost.localdomain/settings#nav-api-tab to get or "
                "renew your API token.",
                "error_code":
                "EINVALIDTOK",
                "errors":
                "Invalid token",
            },
        )
Пример #24
0
    def test_rebase_api_api_logged_in_unknown_token(self):
        """ Test the rebase PR API endpoint with an invalid API token """

        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

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

        output = self.app.post(
            "/api/0/test/pull-request/1/rebase", headers=headers
        )
        self.assertEqual(output.status_code, 401)
        data = json.loads(output.get_data(as_text=True))
        self.assertEqual(
            data,
            {
                "error": "Invalid or expired token. Please visit "
                "http://localhost.localdomain/settings#nav-api-tab to get "
                "or renew your API token.",
                "error_code": "EINVALIDTOK",
                "errors": "Invalid token",
            },
        )
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        self.maxDiff = None
        super(PagureFlaskApiCustomFieldIssuetests, 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 normal issue
        repo = pagure.lib.query.get_authorized_project(self.session, "test")
        pagure.lib.query.new_issue(
            session=self.session,
            repo=repo,
            title="Test issue #1",
            content="We should work on this",
            user="******",
            private=False,
        )
        self.session.commit()
    def test_api_project_tags_new_existing_tag(self):
        """ Test the api_tags_new method of the flask api. """
        tests.create_projects(self.session)
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)
        # Add an issue and tag it so that we can list them
        item = pagure.lib.model.TagColored(tag="blue",
                                           tag_color="DeepBlueSky",
                                           project_id=1)
        self.session.add(item)
        self.session.commit()
        headers = {"Authorization": "token aaabbbcccddd"}
        output = self.app.get("/api/0/test/tags/")
        self.assertEqual(output.status_code, 200)
        expected_rv = {"tags": ["blue"], "total_tags": 1}
        data = json.loads(output.get_data(as_text=True))
        self.assertDictEqual(data, expected_rv)

        data = {"tag": "blue", "tag_color": "DeepBlueSky"}

        output = self.app.post("/api/0/test/tags/new",
                               headers=headers,
                               data=data)
        self.assertEqual(output.status_code, 400)
        expected_rv = {
            "error": "An error occurred at the database level and prevent "
            "the action from reaching completion",
            "error_code": "EDBERROR",
        }
        data = json.loads(output.get_data(as_text=True))
        self.assertDictEqual(data, expected_rv)

        output = self.app.get("/api/0/test/tags/")
        self.assertEqual(output.status_code, 200)
        expected_rv = {"tags": ["blue"], "total_tags": 1}
        data = json.loads(output.get_data(as_text=True))
        self.assertDictEqual(data, expected_rv)
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskApiIssueCreatetests, 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 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')
Пример #28
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",
            })
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        self.maxDiff = None
        super(PagureFlaskApiCustomFieldIssuetests, 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 normal issue
        repo = pagure.lib.get_authorized_project(self.session, 'test')
        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()
    def test_api_change_status_issue(self):
        """ Test the api_change_status_issue method of the flask api. """
        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(tests.HERE, 'tickets'))
        tests.create_tokens(self.session)
        tests.create_acls(self.session)
        tests.create_tokens_acl(self.session)

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

        # Invalid project
        output = self.app.post('/api/0/foo/issue/1/status', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Project not found",
              "error_code": "ENOPROJECT",
            }
        )

        # Valid token, wrong project
        output = self.app.post('/api/0/test2/issue/1/status', 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",
            }
        )

        # No input
        output = self.app.post('/api/0/test/issue/1/status', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Issue not found",
              "error_code": "ENOISSUE",
            }
        )

        # Create normal issue
        repo = pagure.lib.get_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 another project
        item = pagure.lib.model.Project(
            user_id=2,  # pingou
            name='foo',
            description='test project #3',
            hook_token='aaabbbdddeee',
        )
        self.session.add(item)
        self.session.commit()

        # Create a token for pingou for this project
        item = pagure.lib.model.Token(
            id='pingou_foo',
            user_id=1,
            project_id=3,
            expiration=datetime.datetime.utcnow() + datetime.timedelta(
                days=30)
        )
        self.session.add(item)
        self.session.commit()

        # Give `change_status_issue` to this token
        item = pagure.lib.model.TokenAcl(
            token_id='pingou_foo',
            acl_id=4,
        )
        self.session.add(item)
        self.session.commit()

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

        # Check status before
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(issue.status, 'Open')

        data = {
            'title': 'test issue',
        }

        # Incomplete request
        output = self.app.post(
            '/api/0/test/issue/1/status', data=data, 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",
            }
        )

        # No change
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(issue.status, 'Open')

        data = {
            'status': 'Open',
        }

        # Valid request but no change
        output = self.app.post(
            '/api/0/test/issue/1/status', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'No changes'}
        )

        # No change
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(issue.status, 'Open')

        data = {
            'status': 'Fixed',
        }

        # Valid request
        output = self.app.post(
            '/api/0/test/issue/1/status', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Successfully edited issue #1'}
        )

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

        # Un-authorized issue
        output = self.app.post(
            '/api/0/foo/issue/1/status', data=data, headers=headers)
        self.assertEqual(output.status_code, 403)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "You are not allowed to view this issue",
              "error_code": "EISSUENOTALLOWED",
            }
        )
Пример #31
0
def insert_data(session, username, user_email):
    pagure.APP.config['EMAIL_SEND'] = False
    pagure.APP.config['TESTING'] = True

    ######################################
    # tags
    item = pagure.lib.model.Tag(tag='tag1', )
    session.add(item)
    session.commit()

    ######################################
    # Users
    # Create a couple of users
    item = pagure.lib.model.User(
        user='******',
        fullname='PY C',
        password='******',
        default_email='*****@*****.**',
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.User(
        user='******',
        fullname='foo bar',
        password='******',
        default_email='*****@*****.**',
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.User(
        user=username,
        fullname=username,
        password='******',
        default_email=user_email,
    )
    session.add(item)
    session.commit()

    ######################################
    # pagure_group
    item = pagure.lib.model.PagureGroup(
        group_name='admin',
        user_id=1,
        display_name='admin',
        description='Admin Group',
    )
    session.add(item)
    session.commit()

    # Add a couple of groups so that we can list them
    item = pagure.lib.model.PagureGroup(
        group_name='group',
        group_type='user',
        user_id=1,  # pingou
        display_name='group group',
        description='this is a group group',
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.PagureGroup(
        group_name='rel-eng',
        group_type='user',
        user_id=1,  # pingou
        display_name='Release Engineering',
        description='The group of release engineers',
    )
    session.add(item)
    session.commit()
    ######################################
    # projects

    import shutil
    # delete folder from local instance to start from a clean slate
    if os.path.exists(pagure.APP.config['GIT_FOLDER']):
        shutil.rmtree(pagure.APP.config['GIT_FOLDER'])

    tests.create_projects(session)
    tests.create_projects_git(pagure.APP.config['GIT_FOLDER'], bare=True)
    tests.add_content_git_repo(
        os.path.join(pagure.APP.config['GIT_FOLDER'], 'test.git'))
    tests.add_readme_git_repo(
        os.path.join(pagure.APP.config['GIT_FOLDER'], 'test.git'))

    # Add some content to the git repo
    tests.add_content_git_repo(
        os.path.join(pagure.APP.config['GIT_FOLDER'], 'forks', 'pingou',
                     'test.git'))
    tests.add_readme_git_repo(
        os.path.join(pagure.APP.config['GIT_FOLDER'], 'forks', 'pingou',
                     'test.git'))
    tests.add_commit_git_repo(os.path.join(pagure.APP.config['GIT_FOLDER'],
                                           'forks', 'pingou', 'test.git'),
                              ncommits=10)

    ######################################
    # user_emails
    item = pagure.lib.model.UserEmail(user_id=1, email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=1, email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=2, email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=3, email=user_email)
    session.add(item)

    session.commit()

    ######################################
    # user_emails_pending
    user = pagure.lib.search_user(session, username='******')
    email_pend = pagure.lib.model.UserEmailPending(
        user_id=user.id,
        email='[email protected]',
        token='abcdef',
    )
    session.add(email_pend)
    session.commit()

    ######################################
    # issues
    # Add an issue and tag it so that we can list them
    item = pagure.lib.model.Issue(
        id=1,
        uid='foobar',
        project_id=1,
        title='Problem with jenkins build',
        content='For some reason the tests fail at line:24',
        user_id=1,  # pingou
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.Issue(
        id=2,
        uid='foobar2',
        project_id=1,
        title='Unit tests failing',
        content='Need to fix code for the unit tests to '
        'pass so jenkins build can complete.',
        user_id=1,  # pingou
    )
    session.add(item)
    session.commit()

    user = pagure.lib.search_user(session, username=username)
    item = pagure.lib.model.Issue(
        id=3,
        uid='foobar3',
        project_id=1,
        title='Segfault during execution',
        content='Index out of bounds for variable i?',
        user_id=user.id,  # current user
    )
    session.add(item)
    session.commit()

    ######################################
    # pagure_user_group
    group = pagure.lib.search_groups(session,
                                     pattern=None,
                                     group_name="rel-eng",
                                     group_type=None)
    user = pagure.lib.search_user(session, username='******')
    item = pagure.lib.model.PagureUserGroup(user_id=user.id, group_id=group.id)
    session.add(item)
    session.commit()

    user = pagure.lib.search_user(session, username=username)
    group = pagure.lib.search_groups(session,
                                     pattern=None,
                                     group_name="admin",
                                     group_type=None)

    item = pagure.lib.model.PagureUserGroup(user_id=user.id, group_id=group.id)
    session.add(item)
    session.commit()

    user = pagure.lib.search_user(session, username='******')
    group = pagure.lib.search_groups(session,
                                     pattern=None,
                                     group_name="group",
                                     group_type=None)

    item = pagure.lib.model.PagureUserGroup(user_id=user.id, group_id=group.id)
    session.add(item)
    session.commit()

    ######################################
    # projects_groups
    group = pagure.lib.search_groups(session,
                                     pattern=None,
                                     group_name="rel-eng",
                                     group_type=None)
    repo = pagure.get_authorized_project(session, 'test')
    item = pagure.lib.model.ProjectGroup(project_id=repo.id, group_id=group.id)
    session.add(item)
    session.commit()

    group = pagure.lib.search_groups(session,
                                     pattern=None,
                                     group_name="admin",
                                     group_type=None)
    repo = pagure.get_authorized_project(session, 'test2')
    item = pagure.lib.model.ProjectGroup(project_id=repo.id, group_id=group.id)
    session.add(item)
    session.commit()

    ######################################
    # pull_requests
    repo = pagure.get_authorized_project(session, 'test')
    forked_repo = pagure.get_authorized_project(session, 'test')
    req = pagure.lib.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from='master',
        repo_to=repo,
        branch_to='master',
        title='Fixing code for unittest',
        user=username,
        requestfolder=None,
    )
    session.commit()

    ######################################
    # tokens
    tests.create_tokens(session)

    ######################################
    # user_projects
    user = pagure.lib.search_user(session, username='******')
    repo = pagure.get_authorized_project(session, 'test')
    item = pagure.lib.model.ProjectUser(project_id=repo.id, user_id=user.id)
    session.add(item)
    session.commit()

    user = pagure.lib.search_user(session, username=username)
    repo = pagure.get_authorized_project(session, 'test2')
    item = pagure.lib.model.ProjectUser(project_id=repo.id, user_id=user.id)
    session.add(item)
    session.commit()

    ######################################
    # issue_comments
    item = pagure.lib.model.IssueComment(
        user_id=1,
        issue_uid='foobar',
        comment='We may need to adjust the unittests instead of the code.',
    )
    session.add(item)
    session.commit()

    ######################################
    # issue_to_issue
    repo = pagure.get_authorized_project(session, 'test')
    all_issues = pagure.lib.search_issues(session, repo)
    pagure.lib.add_issue_dependency(session, all_issues[0], all_issues[1],
                                    'pingou', pagure.APP.config['GIT_FOLDER'])

    ######################################
    # pull_request_comments
    user = pagure.lib.search_user(session, username='******')
    # only 1 pull request available atm
    pr = pagure.lib.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestComment(
        pull_request_uid=pr.uid,
        user_id=user.id,
        comment="+1 for me. Btw, could you rebase before you merge?",
        notification=0)
    session.add(item)
    session.commit()

    ######################################
    # pull_request_flags
    user = pagure.lib.search_user(session, username='******')
    # only 1 pull request available atm
    pr = pagure.lib.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestFlag(uid="random_pr_flag_uid",
                                            pull_request_uid=pr.uid,
                                            user_id=user.id,
                                            username=user.user,
                                            percent=80,
                                            comment="Jenkins build passes",
                                            url=str(pr.id))
    session.add(item)
    session.commit()

    ######################################
    # tags_issues
    repo = pagure.get_authorized_project(session, 'test')
    issues = pagure.lib.search_issues(session, repo)
    item = pagure.lib.model.TagIssue(
        issue_uid=issues[0].uid,
        tag='Blocker',
    )
    session.add(item)
    session.commit()

    ######################################
    # tokens_acls
    tests.create_tokens_acl(session)

    ######################################
    # Fork a project
    # delete fork data
    fork_proj_location = "forks/foo/test.git"
    try:
        shutil.rmtree(
            os.path.join(pagure.APP.config['GIT_FOLDER'], fork_proj_location))
    except:
        print('git folder already deleted')

    try:
        shutil.rmtree(
            os.path.join(pagure.APP.config['DOCS_FOLDER'], fork_proj_location))
    except:
        print('docs folder already deleted')

    try:
        shutil.rmtree(
            os.path.join(pagure.APP.config['TICKETS_FOLDER'],
                         fork_proj_location))
    except:
        print('tickets folder already deleted')

    try:
        shutil.rmtree(
            os.path.join(pagure.APP.config['REQUESTS_FOLDER'],
                         fork_proj_location))
    except:
        print('requests folder already deleted')

    repo = pagure.get_authorized_project(session, 'test')
    result = pagure.lib.fork_project(session, 'foo', repo,
                                     pagure.APP.config['GIT_FOLDER'],
                                     pagure.APP.config['DOCS_FOLDER'],
                                     pagure.APP.config['TICKETS_FOLDER'],
                                     pagure.APP.config['REQUESTS_FOLDER'])
    if result == 'Repo "test" cloned to "foo/test"':
        session.commit()
Пример #32
0
    def test_api_new_issue(self):
        """ Test the api_new_issue method of the flask api. """
        tests.create_projects(self.session)
        tests.create_projects_git(
            os.path.join(tests.HERE, 'tickets'), bare=True)
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

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

        # Valid token, wrong project
        output = self.app.post('/api/0/test2/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",
            }
        )

        # No input
        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",
            }
        )

        data = {
            'title': 'test issue',
        }

        # Invalid repo
        output = self.app.post(
            '/api/0/foo/new_issue', data=data, headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Project not found",
              "error_code": "ENOPROJECT",
            }
        )

        # Incomplete request
        output = self.app.post(
            '/api/0/test/new_issue', data=data, 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",
            }
        )

        data = {
            'title': 'test issue',
            'issue_content': 'This issue needs attention',
        }

        # Valid request
        output = self.app.post(
            '/api/0/test/new_issue', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Issue created'}
        )
    def test_api_pull_request_add_comment(self, mockemail):
        """ Test the api_pull_request_add_comment method of the flask api. """
        mockemail.return_value = True

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

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

        # Invalid project
        output = self.app.post('/api/0/foo/pull-request/1/comment',
                               headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(data, {
            "error": "Project not found",
            "error_code": "ENOPROJECT",
        })

        # Valid token, wrong project
        output = self.app.post('/api/0/test2/pull-request/1/comment',
                               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",
            }
        )

        # No input
        output = self.app.post('/api/0/test/pull-request/1/comment',
                               headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(data, {
            "error": "Pull-Request not found",
            "error_code": "ENOREQ",
        })

        # Create a pull-request
        repo = pagure.lib.get_project(self.session, 'test')
        forked_repo = pagure.lib.get_project(self.session, 'test')
        req = pagure.lib.new_pull_request(
            session=self.session,
            repo_from=forked_repo,
            branch_from='master',
            repo_to=repo,
            branch_to='master',
            title='test pull-request',
            user='******',
            requestfolder=None,
        )
        self.session.commit()
        self.assertEqual(req.id, 1)
        self.assertEqual(req.title, 'test pull-request')

        # Check comments before
        request = pagure.lib.search_pull_requests(self.session,
                                                  project_id=1,
                                                  requestid=1)
        self.assertEqual(len(request.comments), 0)

        data = {
            'title': 'test issue',
        }

        # Incomplete request
        output = self.app.post('/api/0/test/pull-request/1/comment',
                               data=data,
                               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",
            })

        # No change
        request = pagure.lib.search_pull_requests(self.session,
                                                  project_id=1,
                                                  requestid=1)
        self.assertEqual(len(request.comments), 0)

        data = {
            'comment': 'This is a very interesting question',
        }

        # Valid request
        output = self.app.post('/api/0/test/pull-request/1/comment',
                               data=data,
                               headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(data, {'message': 'Comment added'})

        # One comment added
        request = pagure.lib.search_pull_requests(self.session,
                                                  project_id=1,
                                                  requestid=1)
        self.assertEqual(len(request.comments), 1)
    def test_api_pull_request_merge(self, mpr, send_email):
        """ Test the api_pull_request_merge method of the flask api. """
        mpr.return_value = 'Changes merged!'
        send_email.return_value = True

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

        # Create the pull-request to close
        repo = pagure.lib.get_project(self.session, 'test')
        forked_repo = pagure.lib.get_project(self.session, 'test')
        req = pagure.lib.new_pull_request(
            session=self.session,
            repo_from=forked_repo,
            branch_from='master',
            repo_to=repo,
            branch_to='master',
            title='test pull-request',
            user='******',
            requestfolder=None,
        )
        self.session.commit()
        self.assertEqual(req.id, 1)
        self.assertEqual(req.title, 'test pull-request')

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

        # Invalid project
        output = self.app.post('/api/0/foo/pull-request/1/merge',
                               headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(data, {
            "error": "Project not found",
            "error_code": "ENOPROJECT",
        })

        # Valid token, wrong project
        output = self.app.post('/api/0/test2/pull-request/1/merge',
                               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",
            }
        )

        # Invalid PR
        output = self.app.post('/api/0/test/pull-request/2/merge',
                               headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(data, {
            'error': 'Pull-Request not found',
            'error_code': "ENOREQ"
        })

        # Create a token for foo for this project
        item = pagure.lib.model.Token(id='foobar_token',
                                      user_id=2,
                                      project_id=1,
                                      expiration=datetime.datetime.utcnow() +
                                      datetime.timedelta(days=30))
        self.session.add(item)
        self.session.commit()
        item = pagure.lib.model.TokenAcl(
            token_id='foobar_token',
            acl_id=3,
        )
        self.session.add(item)
        self.session.commit()

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

        # User not admin
        output = self.app.post('/api/0/test/pull-request/1/merge',
                               headers=headers)
        self.assertEqual(output.status_code, 403)
        data = json.loads(output.data)
        self.assertDictEqual(
            data, {
                'error': 'You are not allowed to merge/close pull-request '
                'for this project',
                'error_code': "ENOPRCLOSE",
            })

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

        # Merge PR
        output = self.app.post('/api/0/test/pull-request/1/merge',
                               headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(data, {"message": "Changes merged!"})
Пример #35
0
    def test_api_view_group_w_projects_and_acl(self):
        """
            Test the api_view_group method with project info and restricted
            to the admin ACL
        """
        tests.create_tokens(self.session)

        headers = {'Authorization': 'token aaabbbcccddd'}
        output = self.app.get('/api/0/group/some_group?projects=1',
                              headers=headers)
        self.assertEqual(output.status_code, 200)
        exp = {
            "display_name":
            "Some Group",
            "description":
            None,
            "creator": {
                "fullname": "PY C",
                "default_email": "*****@*****.**",
                "emails": ["*****@*****.**", "*****@*****.**"],
                "name": "pingou"
            },
            "members": ["pingou"],
            "date_created":
            "1492020239",
            "group_type":
            "user",
            "name":
            "some_group",
            "projects": [{
                "access_groups": {
                    "admin": ["some_group"],
                    "commit": [],
                    "ticket": []
                },
                "access_users": {
                    "admin": [],
                    "commit": [],
                    "owner": ["pingou"],
                    "ticket": []
                },
                "close_status":
                ["Invalid", "Insufficient data", "Fixed", "Duplicate"],
                "custom_keys": [],
                "date_created":
                "1492020239",
                "date_modified":
                "1492020239",
                "description":
                "test project #2",
                "fullname":
                "test2",
                "id":
                2,
                "milestones": {},
                "name":
                "test2",
                "namespace":
                None,
                "parent":
                None,
                "priorities": {},
                "settings": {
                    "Enforce_signed-off_commits_in_pull-request": False,
                    "Minimum_score_to_merge_pull-request": -1,
                    "Only_assignee_can_merge_pull-request": False,
                    "Web-hooks": None,
                    "always_merge": False,
                    "fedmsg_notifications": True,
                    "issue_tracker": True,
                    "issues_default_to_private": False,
                    "project_documentation": False,
                    "pull_request_access_only": False,
                    "pull_requests": True
                },
                "tags": [],
                "url_path":
                "test2",
                "user": {
                    "fullname": "PY C",
                    "name": "pingou"
                }
            }]
        }
        data = json.loads(output.data)
        data['date_created'] = '1492020239'
        projects = []
        for p in data['projects']:
            p['date_created'] = '1492020239'
            p['date_modified'] = '1492020239'
            projects.append(p)
        data['projects'] = projects
        self.assertDictEqual(data, exp)

        output2 = self.app.get('/api/0/group/some_group?projects=1&acl=admin',
                               headers=headers)
        self.assertEqual(output.data.split('\n'), output2.data.split('\n'))
    def test_api_fork_project(self, p_gga):
        """ Test the api_fork_project method of the flask api. """
        p_gga.return_value = True

        tests.create_projects(self.session)
        for folder in ['docs', 'tickets', 'requests', 'repos']:
            tests.create_projects_git(os.path.join(self.path, folder),
                                      bare=True)
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

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

        # Invalid token
        output = self.app.post('/api/0/fork', headers=headers)
        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'}

        # No input
        output = self.app.post('/api/0/fork', 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",
            })

        data = {
            'name': 'test',
        }

        # Incomplete request
        output = self.app.post('/api/0/fork', data=data, 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",
            })

        data = {
            'repo': 'test',
        }

        # Valid request
        output = self.app.post('/api/0/fork/', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data, {"message": "Repo \"test\" cloned to \"pingou/test\""})

        data = {
            'repo': 'test',
        }

        # project already forked
        output = self.app.post('/api/0/fork/', data=data, headers=headers)
        self.assertEqual(output.status_code, 400)
        data = json.loads(output.data)
        self.assertDictEqual(
            data, {
                "error": "Repo \"forks/pingou/test\" already exists",
                "error_code": "ENOCODE"
            })

        data = {
            'repo': 'test',
            'username': '******',
        }

        # Fork already exists
        output = self.app.post('/api/0/fork/', data=data, headers=headers)
        self.assertEqual(output.status_code, 400)
        data = json.loads(output.data)
        self.assertDictEqual(
            data, {
                "error": "Repo \"forks/pingou/test\" already exists",
                "error_code": "ENOCODE"
            })

        data = {
            'repo': 'test',
            'namespace': 'pingou',
        }

        # Repo does not exists
        output = self.app.post('/api/0/fork/', data=data, headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(data, {
            "error": "Project not found",
            "error_code": "ENOPROJECT"
        })
    def test_api_new_project(self, p_gga):
        """ Test the api_new_project method of the flask api. """
        p_gga.return_value = True

        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)

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

        # Invalid token
        output = self.app.post('/api/0/new', headers=headers)
        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'}

        # No input
        output = self.app.post('/api/0/new', 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",
            })

        data = {
            'name': 'test',
        }

        # Incomplete request
        output = self.app.post('/api/0/new', data=data, 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",
            })

        data = {
            'name': 'test',
            'description': 'Just a small test project',
        }

        # Valid request but repo already exists
        output = self.app.post('/api/0/new/', data=data, headers=headers)
        self.assertEqual(output.status_code, 400)
        data = json.loads(output.data)
        self.assertDictEqual(
            data, {
                "error": "The tickets repo \"test.git\" already exists",
                "error_code": "ENOCODE"
            })

        data = {
            'name': 'test_42',
            'description': 'Just another small test project',
        }

        # Valid request
        output = self.app.post('/api/0/new/', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(data, {'message': 'Project "test_42" created'})
    def test_api_pull_request_add_comment(self, mockemail):
        """ Test the api_pull_request_add_comment method of the flask api. """
        mockemail.return_value = True

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

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

        # Invalid project
        output = self.app.post(
            '/api/0/foo/pull-request/1/comment', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Project not found",
              "error_code": "ENOPROJECT",
            }
        )

        # Valid token, wrong project
        output = self.app.post(
            '/api/0/test2/pull-request/1/comment', 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",
            }
        )

        # No input
        output = self.app.post(
            '/api/0/test/pull-request/1/comment', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Pull-Request not found",
              "error_code": "ENOREQ",
            }
        )

        # Create a pull-request
        repo = pagure.lib.get_project(self.session, 'test')
        forked_repo = pagure.lib.get_project(self.session, 'test')
        req = pagure.lib.new_pull_request(
            session=self.session,
            repo_from=forked_repo,
            branch_from='master',
            repo_to=repo,
            branch_to='master',
            title='test pull-request',
            user='******',
            requestfolder=None,
        )
        self.session.commit()
        self.assertEqual(req.id, 1)
        self.assertEqual(req.title, 'test pull-request')

        # Check comments before
        request = pagure.lib.search_pull_requests(
            self.session, project_id=1, requestid=1)
        self.assertEqual(len(request.comments), 0)

        data = {
            'title': 'test issue',
        }

        # Incomplete request
        output = self.app.post(
            '/api/0/test/pull-request/1/comment', data=data, 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",
            }
        )

        # No change
        request = pagure.lib.search_pull_requests(
            self.session, project_id=1, requestid=1)
        self.assertEqual(len(request.comments), 0)

        data = {
            'comment': 'This is a very interesting question',
        }

        # Valid request
        output = self.app.post(
            '/api/0/test/pull-request/1/comment', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Comment added'}
        )

        # One comment added
        request = pagure.lib.search_pull_requests(
            self.session, project_id=1, requestid=1)
        self.assertEqual(len(request.comments), 1)
Пример #39
0
    def setUp(self):
        """ Set up the environnment, ran before every tests. """
        super(PagureFlaskApiIssueChangeStatustests, 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')

        # Create project-less token for user pingou
        item = pagure.lib.model.Token(
            id='project-less-pingou',
            user_id=1,
            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-pingou')
Пример #40
0
def insert_data(session, username, user_email):
    pagure.APP.config['EMAIL_SEND'] = False
    pagure.APP.config['TESTING'] = True

    ######################################
    # tags
    item = pagure.lib.model.Tag(
        tag='tag1',
    )
    session.add(item)
    session.commit()

    ######################################
    # Users
    # Create a couple of users
    item = pagure.lib.model.User(
        user='******',
        fullname='PY C',
        password='******',
        default_email='*****@*****.**',
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.User(
        user='******',
        fullname='foo bar',
        password='******',
        default_email='*****@*****.**',
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.User(
        user=username,
        fullname=username,
        password='******',
        default_email=user_email,
    )
    session.add(item)
    session.commit()

    ######################################
    # pagure_group
    item = pagure.lib.model.PagureGroup(
        group_name='admin',
        user_id=1,
    )
    session.add(item)
    session.commit()

    # Add a couple of groups so that we can list them
    item = pagure.lib.model.PagureGroup(
        group_name='group',
        group_type='user',
        user_id=1,  # pingou
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.PagureGroup(
        group_name='rel-eng',
        group_type='user',
        user_id=1,  # pingou
    )
    session.add(item)
    session.commit()
    ######################################
    # projects

    import shutil
    # delete folder from local instance to start from a clean slate
    if os.path.exists(pagure.APP.config['GIT_FOLDER']):
        shutil.rmtree(pagure.APP.config['GIT_FOLDER'])

    tests.create_projects(session)
    tests.create_projects_git(pagure.APP.config['GIT_FOLDER'], bare=True)
    tests.add_content_git_repo(
        os.path.join(pagure.APP.config['GIT_FOLDER'], 'test.git'))
    tests.add_readme_git_repo(
        os.path.join(pagure.APP.config['GIT_FOLDER'], 'test.git'))

    # Add some content to the git repo
    tests.add_content_git_repo(
        os.path.join(pagure.APP.config['GIT_FOLDER'], 'forks', 'pingou',
                     'test.git'))
    tests.add_readme_git_repo(
        os.path.join(pagure.APP.config['GIT_FOLDER'], 'forks', 'pingou',
                     'test.git'))
    tests.add_commit_git_repo(
        os.path.join(pagure.APP.config['GIT_FOLDER'], 'forks', 'pingou',
                     'test.git'), ncommits=10)

    ######################################
    # user_emails
    item = pagure.lib.model.UserEmail(
        user_id=1,
        email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(
        user_id=1,
        email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(
        user_id=2,
        email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(
        user_id=3,
        email=user_email)
    session.add(item)

    session.commit()

    ######################################
    # user_emails_pending
    user = pagure.lib.search_user(session, username='******')
    email_pend = pagure.lib.model.UserEmailPending(
        user_id=user.id,
        email='[email protected]',
        token='abcdef',
    )
    session.add(email_pend)
    session.commit()

    ######################################
    # issues
    # Add an issue and tag it so that we can list them
    item = pagure.lib.model.Issue(
        id=1,
        uid='foobar',
        project_id=1,
        title='Problem with jenkins build',
        content='For some reason the tests fail at line:24',
        user_id=1,  # pingou
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.Issue(
        id=2,
        uid='foobar2',
        project_id=1,
        title='Unit tests failing',
        content='Need to fix code for the unit tests to '
                'pass so jenkins build can complete.',
        user_id=1,  # pingou
    )
    session.add(item)
    session.commit()

    user = pagure.lib.search_user(session, username=username)
    item = pagure.lib.model.Issue(
        id=3,
        uid='foobar3',
        project_id=1,
        title='Segfault during execution',
        content='Index out of bounds for variable i?',
        user_id=user.id,  # current user
    )
    session.add(item)
    session.commit()

    ######################################
    # pagure_user_group
    group = pagure.lib.search_groups(session, pattern=None,
                                     group_name="rel-eng", group_type=None)
    user = pagure.lib.search_user(session, username='******')
    item = pagure.lib.model.PagureUserGroup(
        user_id=user.id,
        group_id=group.id
    )
    session.add(item)
    session.commit()

    user = pagure.lib.search_user(session, username=username)
    group = pagure.lib.search_groups(session, pattern=None,
                                     group_name="admin", group_type=None)

    item = pagure.lib.model.PagureUserGroup(
        user_id=user.id,
        group_id=group.id
    )
    session.add(item)
    session.commit()

    user = pagure.lib.search_user(session, username='******')
    group = pagure.lib.search_groups(session, pattern=None,
                                     group_name="group", group_type=None)

    item = pagure.lib.model.PagureUserGroup(
        user_id=user.id,
        group_id=group.id
    )
    session.add(item)
    session.commit()

    ######################################
    # projects_groups
    group = pagure.lib.search_groups(session, pattern=None,
                                     group_name="rel-eng", group_type=None)
    repo = pagure.lib.get_project(session, 'test')
    item = pagure.lib.model.ProjectGroup(
        project_id=repo.id,
        group_id=group.id
    )
    session.add(item)
    session.commit()

    group = pagure.lib.search_groups(session, pattern=None,
                                     group_name="admin", group_type=None)
    repo = pagure.lib.get_project(session, 'test2')
    item = pagure.lib.model.ProjectGroup(
        project_id=repo.id,
        group_id=group.id
    )
    session.add(item)
    session.commit()

    ######################################
    # pull_requests
    repo = pagure.lib.get_project(session, 'test')
    forked_repo = pagure.lib.get_project(session, 'test')
    req = pagure.lib.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from='master',
        repo_to=repo,
        branch_to='master',
        title='Fixing code for unittest',
        user=username,
        requestfolder=None,
    )
    session.commit()

    ######################################
    # tokens
    tests.create_tokens(session)

    ######################################
    # user_projects
    user = pagure.lib.search_user(session, username='******')
    repo = pagure.lib.get_project(session, 'test')
    item = pagure.lib.model.ProjectUser(
        project_id=repo.id,
        user_id=user.id
    )
    session.add(item)
    session.commit()

    user = pagure.lib.search_user(session, username=username)
    repo = pagure.lib.get_project(session, 'test2')
    item = pagure.lib.model.ProjectUser(
        project_id=repo.id,
        user_id=user.id
    )
    session.add(item)
    session.commit()

    ######################################
    # issue_comments
    item = pagure.lib.model.IssueComment(
        user_id=1,
        issue_uid='foobar',
        comment='We may need to adjust the unittests instead of the code.',
    )
    session.add(item)
    session.commit()

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

    all_issues = pagure.lib.search_issues(session, repo)
    pagure.lib.add_issue_dependency(session, all_issues[0],
                                    all_issues[1], 'pingou',
                                    pagure.APP.config['GIT_FOLDER'])

    ######################################
    # pull_request_comments
    user = pagure.lib.search_user(session, username='******')
    # only 1 pull request available atm
    pr = pagure.lib.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestComment(
        pull_request_uid=pr.uid,
        user_id=user.id,
        comment="+1 for me. Btw, could you rebase before you merge?",
        notification=0
    )
    session.add(item)
    session.commit()

    ######################################
    # pull_request_flags
    user = pagure.lib.search_user(session, username='******')
    # only 1 pull request available atm
    pr = pagure.lib.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestFlag(
        uid="random_pr_flag_uid",
        pull_request_uid=pr.uid,
        user_id=user.id,
        username=user.user,
        percent=80,
        comment="Jenkins build passes",
        url=str(pr.id)
    )
    session.add(item)
    session.commit()

    ######################################
    # tags_issues
    repo = pagure.lib.get_project(session, 'test')
    issues = pagure.lib.search_issues(session, repo)
    item = pagure.lib.model.TagIssue(
        issue_uid=issues[0].uid,
        tag='Blocker',
    )
    session.add(item)
    session.commit()

    ######################################
    # tokens_acls
    tests.create_tokens_acl(session)

    ######################################
    # Fork a project
    # delete fork data
    fork_proj_location = "forks/foo/test.git"
    try:
        shutil.rmtree(os.path.join(pagure.APP.config['GIT_FOLDER'],
                                   fork_proj_location))
    except:
        print('git folder already deleted')

    try:
        shutil.rmtree(os.path.join(pagure.APP.config['DOCS_FOLDER'],
                                   fork_proj_location))
    except:
        print('docs folder already deleted')

    try:
        shutil.rmtree(os.path.join(pagure.APP.config['TICKETS_FOLDER'],
                                   fork_proj_location))
    except:
        print('tickets folder already deleted')

    try:
        shutil.rmtree(os.path.join(pagure.APP.config['REQUESTS_FOLDER'],
                                   fork_proj_location))
    except:
        print('requests folder already deleted')

    repo = pagure.lib.get_project(session, 'test')
    result = pagure.lib.fork_project(session, 'foo', repo,
                                     pagure.APP.config['GIT_FOLDER'],
                                     pagure.APP.config['DOCS_FOLDER'],
                                     pagure.APP.config['TICKETS_FOLDER'],
                                     pagure.APP.config['REQUESTS_FOLDER'])
    if result == 'Repo "test" cloned to "foo/test"':
        session.commit()
    def test_api_pull_request_add_flag(self, mockemail):
        """ Test the api_pull_request_add_flag method of the flask api. """
        mockemail.return_value = True

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

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

        # Invalid project
        output = self.app.post(
            '/api/0/foo/pull-request/1/flag', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Project not found",
              "error_code": "ENOPROJECT",
            }
        )

        # Valid token, wrong project
        output = self.app.post(
            '/api/0/test2/pull-request/1/flag', 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",
            }
        )

        # No input
        output = self.app.post(
            '/api/0/test/pull-request/1/flag', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Pull-Request not found",
              "error_code": "ENOREQ",
            }
        )

        # Create a pull-request
        repo = pagure.lib.get_project(self.session, 'test')
        forked_repo = pagure.lib.get_project(self.session, 'test')
        req = pagure.lib.new_pull_request(
            session=self.session,
            repo_from=forked_repo,
            branch_from='master',
            repo_to=repo,
            branch_to='master',
            title='test pull-request',
            user='******',
            requestfolder=None,
        )
        self.session.commit()
        self.assertEqual(req.id, 1)
        self.assertEqual(req.title, 'test pull-request')

        # Check comments before
        request = pagure.lib.search_pull_requests(
            self.session, project_id=1, requestid=1)
        self.assertEqual(len(request.flags), 0)

        data = {
            'username': '******',
            'percent': 100,
            'url': 'http://jenkins.cloud.fedoraproject.org/',
            'uid': 'jenkins_build_pagure_100+seed',
        }

        # Incomplete request
        output = self.app.post(
            '/api/0/test/pull-request/1/flag', data=data, 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",
            }
        )

        # No change
        request = pagure.lib.search_pull_requests(
            self.session, project_id=1, requestid=1)
        self.assertEqual(len(request.flags), 0)

        data = {
            'username': '******',
            'percent': 0,
            'comment': 'Tests failed',
            'url': 'http://jenkins.cloud.fedoraproject.org/',
            'uid': 'jenkins_build_pagure_100+seed',
        }

        # Valid request
        output = self.app.post(
            '/api/0/test/pull-request/1/flag', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Flag added'}
        )

        # One flag added
        request = pagure.lib.search_pull_requests(
            self.session, project_id=1, requestid=1)
        self.assertEqual(len(request.flags), 1)
        self.assertEqual(request.flags[0].comment, 'Tests failed')
        self.assertEqual(request.flags[0].percent, 0)

        # Update flag
        data = {
            'username': '******',
            'percent': 100,
            'comment': 'Tests passed',
            'url': 'http://jenkins.cloud.fedoraproject.org/',
            'uid': 'jenkins_build_pagure_100+seed',
        }

        output = self.app.post(
            '/api/0/test/pull-request/1/flag', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Flag updated'}
        )

        # One flag added
        request = pagure.lib.search_pull_requests(
            self.session, project_id=1, requestid=1)
        self.assertEqual(len(request.flags), 1)
        self.assertEqual(request.flags[0].comment, 'Tests passed')
        self.assertEqual(request.flags[0].percent, 100)
    def test_api_comment_issue(self, p_send_email, p_ugt):
        """ Test the api_comment_issue method of the flask api. """
        p_send_email.return_value = True
        p_ugt.return_value = True

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

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

        # Invalid project
        output = self.app.post('/api/0/foo/issue/1/comment', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Project not found",
              "error_code": "ENOPROJECT",
            }
        )

        # Valid token, wrong project
        output = self.app.post('/api/0/test2/issue/1/comment', 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",
            }
        )

        # No input
        output = self.app.post('/api/0/test/issue/1/comment', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Issue not found",
              "error_code": "ENOISSUE",
            }
        )

        # Create normal issue
        repo = pagure.lib.get_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,
            issue_uid='aaabbbccc#1',
        )
        self.session.commit()
        self.assertEqual(msg.title, 'Test issue #1')

        # Check comments before
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(len(issue.comments), 0)

        data = {
            'title': 'test issue',
        }

        # Incomplete request
        output = self.app.post(
            '/api/0/test/issue/1/comment', data=data, 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",
            }
        )

        # No change
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(issue.status, 'Open')

        data = {
            'comment': 'This is a very interesting question',
        }

        # Valid request
        output = self.app.post(
            '/api/0/test/issue/1/comment', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Comment added'}
        )

        # One comment added
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(len(issue.comments), 1)

        # Create another project
        item = pagure.lib.model.Project(
            user_id=2,  # foo
            name='foo',
            description='test project #3',
            hook_token='aaabbbdddeee',
        )
        self.session.add(item)
        self.session.commit()

        # Create a token for pingou for this project
        item = pagure.lib.model.Token(
            id='pingou_foo',
            user_id=1,
            project_id=3,
            expiration=datetime.datetime.utcnow() + datetime.timedelta(
                days=30)
        )
        self.session.add(item)
        self.session.commit()

        # Give `change_status_issue` to this token
        item = pagure.lib.model.TokenAcl(
            token_id='pingou_foo',
            acl_id=5,
        )
        self.session.add(item)
        self.session.commit()

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

        # Check before
        repo = pagure.lib.get_project(self.session, 'foo')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(len(issue.comments), 0)

        data = {
            'comment': 'This is a very interesting question',
        }
        headers = {'Authorization': 'token pingou_foo'}

        # Valid request but un-authorized
        output = self.app.post(
            '/api/0/foo/issue/1/comment', data=data, headers=headers)
        self.assertEqual(output.status_code, 403)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "You are not allowed to view this issue",
              "error_code": "EISSUENOTALLOWED",
            }
        )

        # No comment added
        repo = pagure.lib.get_project(self.session, 'foo')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(len(issue.comments), 0)

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

        data = {
            'comment': 'This is a very interesting question',
        }
        headers = {'Authorization': 'token foo_token2'}

        # Valid request and authorized
        output = self.app.post(
            '/api/0/foo/issue/1/comment', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Comment added'}
        )
    def test_api_pull_request_views(self, send_email):
        """ Test the api_pull_request_views method of the flask api. """
        send_email.return_value = True

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

        # Create a pull-request
        repo = pagure.lib.get_project(self.session, 'test')
        forked_repo = pagure.lib.get_project(self.session, 'test')
        req = pagure.lib.new_pull_request(
            session=self.session,
            repo_from=forked_repo,
            branch_from='master',
            repo_to=repo,
            branch_to='master',
            title='test pull-request',
            user='******',
            requestfolder=None,
        )
        self.session.commit()
        self.assertEqual(req.id, 1)
        self.assertEqual(req.title, 'test pull-request')

        # Invalid repo
        output = self.app.get('/api/0/foo/pull-requests')
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Project not found",
              "error_code": "ENOPROJECT",
            }
        )

        # List pull-requests
        output = self.app.get('/api/0/test/pull-requests')
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        data['requests'][0]['date_created'] = '1431414800'
        data['requests'][0]['updated_on'] = '1431414800'
        data['requests'][0]['project']['date_created'] = '1431414800'
        data['requests'][0]['repo_from']['date_created'] = '1431414800'
        data['requests'][0]['uid'] = '1431414800'
        self.assertDictEqual(
            data,
            {
              "args": {
                "assignee": None,
                "author": None,
                "status": True
              },
              "total_requests": 1,
              "requests": [
                {
                  "assignee": None,
                  "branch": "master",
                  "branch_from": "master",
                  "closed_at": None,
                  "closed_by": None,
                  "comments": [],
                  "commit_start": None,
                  "commit_stop": None,
                  "date_created": "1431414800",
                  "id": 1,
                  "initial_comment": None,
                  "project": {
                    "date_created": "1431414800",
                    "description": "test project #1",
                    "id": 1,
                    "name": "test",
                    "parent": None,
                    "priorities": {},
                    "tags": [],
                    "user": {
                      "fullname": "PY C",
                      "name": "pingou"
                    }
                  },
                  "remote_git": None,
                  "repo_from": {
                    "date_created": "1431414800",
                    "description": "test project #1",
                    "id": 1,
                    "name": "test",
                    "parent": None,
                    "priorities": {},
                    "tags": [],
                    "user": {
                      "fullname": "PY C",
                      "name": "pingou"
                    }
                  },
                  "status": 'Open',
                  "title": "test pull-request",
                  "uid": "1431414800",
                  "updated_on": "1431414800",
                  "user": {
                    "fullname": "PY C",
                    "name": "pingou"
                  }
                }
              ]
            }
        )

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

        # Access Pull-Request authenticated
        output = self.app.get('/api/0/test/pull-requests', headers=headers)
        self.assertEqual(output.status_code, 200)
        data2 = json.loads(output.data)
        data2['requests'][0]['date_created'] = '1431414800'
        data2['requests'][0]['updated_on'] = '1431414800'
        data2['requests'][0]['project']['date_created'] = '1431414800'
        data2['requests'][0]['repo_from']['date_created'] = '1431414800'
        data2['requests'][0]['uid'] = '1431414800'
        self.assertDictEqual(data, data2)
Пример #44
0
    def test_api_comment_issue(self, p_send_email, p_ugt):
        """ Test the api_comment_issue method of the flask api. """
        p_send_email.return_value = True
        p_ugt.return_value = True

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

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

        # Invalid project
        output = self.app.post('/api/0/foo/issue/1/comment', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Project not found",
              "error_code": "ENOPROJECT",
            }
        )

        # Valid token, wrong project
        output = self.app.post('/api/0/test2/issue/1/comment', 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",
            }
        )

        # No input
        output = self.app.post('/api/0/test/issue/1/comment', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Issue not found",
              "error_code": "ENOISSUE",
            }
        )

        # Create normal issue
        repo = pagure.lib.get_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,
            issue_uid='aaabbbccc#1',
        )
        self.session.commit()
        self.assertEqual(msg.title, 'Test issue #1')

        # Check comments before
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(len(issue.comments), 0)

        data = {
            'title': 'test issue',
        }

        # Incomplete request
        output = self.app.post(
            '/api/0/test/issue/1/comment', data=data, 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",
            }
        )

        # No change
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(issue.status, 'Open')

        data = {
            'comment': 'This is a very interesting question',
        }

        # Valid request
        output = self.app.post(
            '/api/0/test/issue/1/comment', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Comment added'}
        )

        # One comment added
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(len(issue.comments), 1)

        # Create another project
        item = pagure.lib.model.Project(
            user_id=2,  # foo
            name='foo',
            description='test project #3',
            hook_token='aaabbbdddeee',
        )
        self.session.add(item)
        self.session.commit()

        # Create a token for pingou for this project
        item = pagure.lib.model.Token(
            id='pingou_foo',
            user_id=1,
            project_id=3,
            expiration=datetime.datetime.utcnow() + datetime.timedelta(
                days=30)
        )
        self.session.add(item)
        self.session.commit()

        # Give `issue_change_status` to this token when `issue_comment`
        # is required
        item = pagure.lib.model.TokenAcl(
            token_id='pingou_foo',
            acl_id=2,
        )
        self.session.add(item)
        self.session.commit()

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

        # Check before
        repo = pagure.lib.get_project(self.session, 'foo')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(len(issue.comments), 0)

        data = {
            'comment': 'This is a very interesting question',
        }
        headers = {'Authorization': 'token pingou_foo'}

        # Valid request but un-authorized
        output = self.app.post(
            '/api/0/foo/issue/1/comment', data=data, 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"
            }
        )

        # No comment added
        repo = pagure.lib.get_project(self.session, 'foo')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(len(issue.comments), 0)

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

        data = {
            'comment': 'This is a very interesting question',
        }
        headers = {'Authorization': 'token foo_token2'}

        # Valid request and authorized
        output = self.app.post(
            '/api/0/foo/issue/1/comment', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Comment added'}
        )
Пример #45
0
    def test_api_view_user_activity_stats(self, mockemail):
        """ Test the api_view_user_activity_stats method of the flask user
        api. """
        mockemail.return_value = True

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

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

        # Create a pull-request
        repo = pagure.lib._get_project(self.session, 'test')
        forked_repo = pagure.lib._get_project(self.session, 'test')
        req = pagure.lib.new_pull_request(
            session=self.session,
            repo_from=forked_repo,
            branch_from='master',
            repo_to=repo,
            branch_to='master',
            title='test pull-request',
            user='******',
            requestfolder=None,
        )
        self.session.commit()
        self.assertEqual(req.id, 1)
        self.assertEqual(req.title, 'test pull-request')

        # Check comments before
        request = pagure.lib.search_pull_requests(self.session,
                                                  project_id=1,
                                                  requestid=1)
        self.assertEqual(len(request.comments), 0)

        data = {
            'comment': 'This is a very interesting question',
        }

        # Valid request
        output = self.app.post('/api/0/test/pull-request/1/comment',
                               data=data,
                               headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(data, {'message': 'Comment added'})

        # One comment added
        request = pagure.lib.search_pull_requests(self.session,
                                                  project_id=1,
                                                  requestid=1)
        self.assertEqual(len(request.comments), 1)

        # Close PR
        output = self.app.post('/api/0/test/pull-request/1/close',
                               headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(data, {"message": "Pull-request closed!"})

        # PR closed
        request = pagure.lib.search_pull_requests(self.session,
                                                  project_id=1,
                                                  requestid=1)
        self.assertEqual(request.status, 'Closed')

        # Finally retrieve the user's logs
        output = self.app.get('/api/0/user/pingou/activity/stats')
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        date = datetime.datetime.utcnow().date().strftime('%Y-%m-%d')
        self.assertDictEqual(data, {date: 4})
Пример #46
0
def insert_data(session, username, user_email):
    _config["EMAIL_SEND"] = False
    _config["TESTING"] = True

    ######################################
    # tags
    item = pagure.lib.model.Tag(tag="tag1")
    session.add(item)
    session.commit()

    ######################################
    # Users
    # Create a couple of users
    pingou = item = pagure.lib.model.User(
        user="******",
        fullname="PY C",
        password=generate_hashed_value("testing123"),
        token=None,
        default_email="*****@*****.**",
    )
    session.add(item)
    session.commit()
    print(
        "User created: {} <{}>, {}".format(
            item.user, item.default_email, "testing123"
        )
    )

    foo = item = pagure.lib.model.User(
        user="******",
        fullname="foo bar",
        password=generate_hashed_value("testing123"),
        token=None,
        default_email="*****@*****.**",
    )
    session.add(item)
    session.commit()
    print(
        "User created: {} <{}>, {}".format(
            item.user, item.default_email, "testing123"
        )
    )

    you = item = pagure.lib.model.User(
        user=username,
        fullname=username,
        password=generate_hashed_value("testing123"),
        token=None,
        default_email=user_email,
    )
    session.add(item)
    session.commit()
    print(
        "User created: {} <{}>, {}".format(
            item.user, item.default_email, "testing123"
        )
    )

    ######################################
    # pagure_group
    item = pagure.lib.model.PagureGroup(
        group_name="admin",
        group_type="admin",
        user_id=pingou.id,
        display_name="admin",
        description="Admin Group",
    )
    session.add(item)
    session.commit()
    print('Created "admin" group. Pingou is a member.')

    # Add a couple of groups so that we can list them
    item = pagure.lib.model.PagureGroup(
        group_name="group",
        group_type="user",
        user_id=pingou.id,
        display_name="group group",
        description="this is a group group",
    )
    session.add(item)
    session.commit()
    print('Created "group" group. Pingou is a member.')

    item = pagure.lib.model.PagureGroup(
        group_name="rel-eng",
        group_type="user",
        user_id=pingou.id,
        display_name="Release Engineering",
        description="The group of release engineers",
    )
    session.add(item)
    session.commit()
    print('Created "rel-eng" group. Pingou is a member.')
    ######################################
    # projects

    import shutil

    # delete folder from local instance to start from a clean slate
    if os.path.exists(_config["GIT_FOLDER"]):
        shutil.rmtree(_config["GIT_FOLDER"])

    # Create projects
    item = project1 = pagure.lib.model.Project(
        user_id=pingou.id,
        name="test",
        is_fork=False,
        parent_id=None,
        description="test project #1",
        hook_token="aaabbbccc",
    )
    item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
    session.add(item)
    session.flush()
    tests.create_locks(session, item)

    item = project2 = pagure.lib.model.Project(
        user_id=pingou.id,
        name="test2",
        is_fork=False,
        parent_id=None,
        description="test project #2",
        hook_token="aaabbbddd",
    )
    item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
    session.add(item)

    item = project3 = pagure.lib.model.Project(
        user_id=pingou.id,
        name="test3",
        is_fork=False,
        parent_id=None,
        description="namespaced test project",
        hook_token="aaabbbeee",
        namespace="somenamespace",
    )
    item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"]
    session.add(item)

    session.commit()

    tests.create_projects_git(_config["GIT_FOLDER"], bare=True)
    add_content_git_repo(os.path.join(_config["GIT_FOLDER"], "test.git"))
    tests.add_readme_git_repo(os.path.join(_config["GIT_FOLDER"], "test.git"))

    # Add some content to the git repo
    add_content_git_repo(
        os.path.join(_config["GIT_FOLDER"], "forks", "pingou", "test.git")
    )
    tests.add_readme_git_repo(
        os.path.join(_config["GIT_FOLDER"], "forks", "pingou", "test.git")
    )
    tests.add_commit_git_repo(
        os.path.join(_config["GIT_FOLDER"], "forks", "pingou", "test.git"),
        ncommits=10,
    )

    ######################################
    # user_emails
    item = pagure.lib.model.UserEmail(
        user_id=pingou.id, email="*****@*****.**"
    )
    session.add(item)

    item = pagure.lib.model.UserEmail(
        user_id=pingou.id, email="*****@*****.**"
    )
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=foo.id, email="*****@*****.**")
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=you.id, email=user_email)
    session.add(item)

    session.commit()

    ######################################
    # user_emails_pending
    email_pend = pagure.lib.model.UserEmailPending(
        user_id=pingou.id, email="[email protected]", token="abcdef"
    )
    session.add(email_pend)
    session.commit()

    ######################################
    # issues
    # Add an issue and tag it so that we can list them
    item = pagure.lib.model.Issue(
        id=1001,
        uid="foobar",
        project_id=project1.id,
        title="Problem with jenkins build",
        content="For some reason the tests fail at line:24",
        user_id=pingou.id,
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.Issue(
        id=1002,
        uid="foobar2",
        project_id=project1.id,
        title="Unit tests failing",
        content="Need to fix code for the unit tests to "
        "pass so jenkins build can complete.",
        user_id=pingou.id,
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.Issue(
        id=1003,
        uid="foobar3",
        project_id=project1.id,
        title="Segfault during execution",
        content="Index out of bounds for variable i?",
        user_id=you.id,
    )
    session.add(item)
    session.commit()

    ######################################
    # pagure_user_group
    group = pagure.lib.query.search_groups(
        session, pattern=None, group_name="rel-eng", group_type=None
    )
    item = pagure.lib.model.PagureUserGroup(
        user_id=pingou.id, group_id=group.id
    )
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(
        session, pattern=None, group_name="admin", group_type=None
    )

    item = pagure.lib.model.PagureUserGroup(user_id=you.id, group_id=group.id)
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(
        session, pattern=None, group_name="group", group_type=None
    )

    item = pagure.lib.model.PagureUserGroup(user_id=foo.id, group_id=group.id)
    session.add(item)
    session.commit()

    ######################################
    # projects_groups
    group = pagure.lib.query.search_groups(
        session, pattern=None, group_name="rel-eng", group_type=None
    )
    repo = pagure.lib.query.get_authorized_project(session, "test")
    item = pagure.lib.model.ProjectGroup(
        project_id=repo.id, group_id=group.id, access="commit"
    )
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(
        session, pattern=None, group_name="admin", group_type=None
    )
    repo = pagure.lib.query.get_authorized_project(session, "test2")
    item = pagure.lib.model.ProjectGroup(
        project_id=repo.id, group_id=group.id, access="admin"
    )
    session.add(item)
    session.commit()

    ######################################
    # pull_requests
    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="Fixing code for unittest",
        user=username,
        status="Open",
    )
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="add very nice README",
        user=username,
        status="Open",
    )
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="Add README",
        user=username,
        status="Closed",
    )
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="Fix some containers",
        user=username,
        status="Merged",
    )
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="Fix pull request statuses",
        user=username,
        status="Closed",
    )
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test")
    forked_repo = pagure.lib.query.get_authorized_project(session, "test")
    req = pagure.lib.query.new_pull_request(
        session=session,
        repo_from=forked_repo,
        branch_from="master",
        repo_to=repo,
        branch_to="master",
        title="Fixing UI of issue",
        user=username,
        status="Merged",
    )
    session.commit()

    #####################################
    # tokens
    tests.create_tokens(session, user_id=pingou.id, project_id=project1.id)

    ######################################
    # user_projects
    repo = pagure.lib.query.get_authorized_project(session, "test")
    item = pagure.lib.model.ProjectUser(
        project_id=repo.id, user_id=foo.id, access="commit"
    )
    session.add(item)
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, "test2")
    item = pagure.lib.model.ProjectUser(
        project_id=repo.id, user_id=you.id, access="commit"
    )
    session.add(item)
    session.commit()

    ######################################
    # issue_comments
    item = pagure.lib.model.IssueComment(
        user_id=pingou.id,
        issue_uid="foobar",
        comment="We may need to adjust the unittests instead of the code.",
    )
    session.add(item)
    session.commit()

    ######################################
    # issue_to_issue
    repo = pagure.lib.query.get_authorized_project(session, "test")
    all_issues = pagure.lib.query.search_issues(session, repo)
    pagure.lib.query.add_issue_dependency(
        session, all_issues[0], all_issues[1], "pingou"
    )

    ######################################
    # pull_request_comments
    user = pagure.lib.query.search_user(session, username="******")
    # only 1 pull request available atm
    pr = pagure.lib.query.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestComment(
        pull_request_uid=pr.uid,
        user_id=user.id,
        comment="+1 for me. Btw, could you rebase before you merge?",
        notification=0,
    )
    session.add(item)
    session.commit()

    ######################################
    # pull_request_flags
    # only 1 pull request available atm
    pr = pagure.lib.query.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestFlag(
        uid="random_pr_flag_uid",
        pull_request_uid=pr.uid,
        user_id=pingou.id,
        username=pingou.user,
        percent=80,
        comment="Jenkins build passes",
        url=str(pr.id),
        status="success",
    )
    session.add(item)
    session.commit()

    pr = pagure.lib.query.get_pull_request_of_user(session, "foo")[1]
    item = pagure.lib.model.PullRequestFlag(
        uid="oink oink uid",
        pull_request_uid=pr.uid,
        user_id=pingou.id,
        username=pingou.user,
        percent=80,
        comment="Jenkins does not pass",
        url=str(pr.id),
        status="failure",
    )
    session.add(item)
    session.commit()

    ######################################
    # pull_request_assignee
    pr = pagure.lib.query.search_pull_requests(session, requestid="1006")
    pr.assignee_id = pingou.id
    session.commit()

    pr = pagure.lib.query.search_pull_requests(session, requestid="1007")
    pr.assignee_id = you.id
    session.commit()

    pr = pagure.lib.query.search_pull_requests(session, requestid="1004")
    pr.assignee_id = foo.id
    session.commit()

    ######################################
    # tags_issues
    repo = pagure.lib.query.get_authorized_project(session, "test")
    issues = pagure.lib.query.search_issues(session, repo)
    item = pagure.lib.model.TagIssue(issue_uid=issues[0].uid, tag="tag1")
    session.add(item)
    session.commit()

    ######################################
    # tokens_acls
    tests.create_tokens_acl(session)

    ######################################
    # Fork a project
    # delete fork data
    fork_proj_location = "forks/foo/test.git"
    try:
        shutil.rmtree(os.path.join(_config["GIT_FOLDER"], fork_proj_location))
    except:
        print("git folder already deleted")

    try:
        shutil.rmtree(os.path.join(_config["DOCS_FOLDER"], fork_proj_location))
    except:
        print("docs folder already deleted")

    try:
        shutil.rmtree(
            os.path.join(_config["TICKETS_FOLDER"], fork_proj_location)
        )
    except:
        print("tickets folder already deleted")

    try:
        shutil.rmtree(
            os.path.join(_config["REQUESTS_FOLDER"], fork_proj_location)
        )
    except:
        print("requests folder already deleted")

    repo = pagure.lib.query.get_authorized_project(session, "test")
    result = pagure.lib.query.fork_project(session, "foo", repo)
    if result == 'Repo "test" cloned to "foo/test"':
        session.commit()
    def test_api_pull_request_views(self, send_email):
        """ Test the api_pull_request_views method of the flask api. """
        send_email.return_value = True

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

        # Create a pull-request
        repo = pagure.lib.get_project(self.session, 'test')
        forked_repo = pagure.lib.get_project(self.session, 'test')
        req = pagure.lib.new_pull_request(
            session=self.session,
            repo_from=forked_repo,
            branch_from='master',
            repo_to=repo,
            branch_to='master',
            title='test pull-request',
            user='******',
            requestfolder=None,
        )
        self.session.commit()
        self.assertEqual(req.id, 1)
        self.assertEqual(req.title, 'test pull-request')

        # Invalid repo
        output = self.app.get('/api/0/foo/pull-requests')
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(data, {
            "error": "Project not found",
            "error_code": "ENOPROJECT",
        })

        # List pull-requests
        output = self.app.get('/api/0/test/pull-requests')
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        data['requests'][0]['date_created'] = '1431414800'
        data['requests'][0]['updated_on'] = '1431414800'
        data['requests'][0]['project']['date_created'] = '1431414800'
        data['requests'][0]['repo_from']['date_created'] = '1431414800'
        data['requests'][0]['uid'] = '1431414800'
        self.assertDictEqual(
            data, {
                "args": {
                    "assignee": None,
                    "author": None,
                    "status": True
                },
                "total_requests":
                1,
                "requests": [{
                    "assignee": None,
                    "branch": "master",
                    "branch_from": "master",
                    "closed_at": None,
                    "closed_by": None,
                    "comments": [],
                    "commit_start": None,
                    "commit_stop": None,
                    "date_created": "1431414800",
                    "id": 1,
                    "initial_comment": None,
                    "project": {
                        "date_created": "1431414800",
                        "description": "test project #1",
                        "id": 1,
                        "name": "test",
                        "parent": None,
                        "tags": [],
                        "user": {
                            "fullname": "PY C",
                            "name": "pingou"
                        }
                    },
                    "remote_git": None,
                    "repo_from": {
                        "date_created": "1431414800",
                        "description": "test project #1",
                        "id": 1,
                        "name": "test",
                        "parent": None,
                        "tags": [],
                        "user": {
                            "fullname": "PY C",
                            "name": "pingou"
                        }
                    },
                    "status": 'Open',
                    "title": "test pull-request",
                    "uid": "1431414800",
                    "updated_on": "1431414800",
                    "user": {
                        "fullname": "PY C",
                        "name": "pingou"
                    }
                }]
            })

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

        # Access Pull-Request authenticated
        output = self.app.get('/api/0/test/pull-requests', headers=headers)
        self.assertEqual(output.status_code, 200)
        data2 = json.loads(output.data)
        data2['requests'][0]['date_created'] = '1431414800'
        data2['requests'][0]['updated_on'] = '1431414800'
        data2['requests'][0]['project']['date_created'] = '1431414800'
        data2['requests'][0]['repo_from']['date_created'] = '1431414800'
        data2['requests'][0]['uid'] = '1431414800'
        self.assertDictEqual(data, data2)
    def test_api_view_group_w_projects_and_acl(self):
        """
            Test the api_view_group method with project info and restricted
            to the admin ACL
        """
        tests.create_tokens(self.session)

        headers = {'Authorization': 'token aaabbbcccddd'}
        output = self.app.get('/api/0/group/some_group?projects=1',
                              headers=headers)
        self.assertEqual(output.status_code, 200)
        exp = {
            "display_name":
            "Some Group",
            "description":
            None,
            "creator": {
                "fullname": "PY C",
                "default_email": "*****@*****.**",
                "emails": ["*****@*****.**", "*****@*****.**"],
                "name": "pingou"
            },
            "members": ["pingou"],
            "date_created":
            "1492020239",
            "group_type":
            "user",
            "name":
            "some_group",
            "projects": [{
                "access_groups": {
                    "admin": ["some_group"],
                    "commit": [],
                    "ticket": []
                },
                "access_users": {
                    "admin": [],
                    "commit": [],
                    "owner": ["pingou"],
                    "ticket": []
                },
                "close_status":
                ["Invalid", "Insufficient data", "Fixed", "Duplicate"],
                "custom_keys": [],
                "date_created":
                "1492020239",
                "date_modified":
                "1492020239",
                "description":
                "test project #2",
                "fullname":
                "test2",
                "id":
                2,
                "milestones": {},
                "name":
                "test2",
                "namespace":
                None,
                "parent":
                None,
                "priorities": {},
                "tags": [],
                "url_path":
                "test2",
                "user": {
                    "fullname": "PY C",
                    "name": "pingou"
                }
            }]
        }
        data = json.loads(output.get_data(as_text=True))
        data['date_created'] = '1492020239'
        projects = []
        for p in data['projects']:
            p['date_created'] = '1492020239'
            p['date_modified'] = '1492020239'
            projects.append(p)
        data['projects'] = projects
        self.assertDictEqual(data, exp)

        output2 = self.app.get('/api/0/group/some_group?projects=1&acl=admin',
                               headers=headers)
        self.assertListEqual(
            output.get_data(as_text=True).split('\n'),
            output2.get_data(as_text=True).split('\n'))
    def test_api_pull_request_add_flag(self, mockemail):
        """ Test the api_pull_request_add_flag method of the flask api. """
        mockemail.return_value = True

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

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

        # Invalid project
        output = self.app.post('/api/0/foo/pull-request/1/flag',
                               headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(data, {
            "error": "Project not found",
            "error_code": "ENOPROJECT",
        })

        # Valid token, wrong project
        output = self.app.post('/api/0/test2/pull-request/1/flag',
                               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",
            }
        )

        # No input
        output = self.app.post('/api/0/test/pull-request/1/flag',
                               headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(data, {
            "error": "Pull-Request not found",
            "error_code": "ENOREQ",
        })

        # Create a pull-request
        repo = pagure.lib.get_project(self.session, 'test')
        forked_repo = pagure.lib.get_project(self.session, 'test')
        req = pagure.lib.new_pull_request(
            session=self.session,
            repo_from=forked_repo,
            branch_from='master',
            repo_to=repo,
            branch_to='master',
            title='test pull-request',
            user='******',
            requestfolder=None,
        )
        self.session.commit()
        self.assertEqual(req.id, 1)
        self.assertEqual(req.title, 'test pull-request')

        # Check comments before
        request = pagure.lib.search_pull_requests(self.session,
                                                  project_id=1,
                                                  requestid=1)
        self.assertEqual(len(request.flags), 0)

        data = {
            'username': '******',
            'percent': 100,
            'url': 'http://jenkins.cloud.fedoraproject.org/',
            'uid': 'jenkins_build_pagure_100+seed',
        }

        # Incomplete request
        output = self.app.post('/api/0/test/pull-request/1/flag',
                               data=data,
                               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",
            })

        # No change
        request = pagure.lib.search_pull_requests(self.session,
                                                  project_id=1,
                                                  requestid=1)
        self.assertEqual(len(request.flags), 0)

        data = {
            'username': '******',
            'percent': 0,
            'comment': 'Tests failed',
            'url': 'http://jenkins.cloud.fedoraproject.org/',
            'uid': 'jenkins_build_pagure_100+seed',
        }

        # Valid request
        output = self.app.post('/api/0/test/pull-request/1/flag',
                               data=data,
                               headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(data, {'message': 'Flag added'})

        # One flag added
        request = pagure.lib.search_pull_requests(self.session,
                                                  project_id=1,
                                                  requestid=1)
        self.assertEqual(len(request.flags), 1)
        self.assertEqual(request.flags[0].comment, 'Tests failed')
        self.assertEqual(request.flags[0].percent, 0)

        # Update flag
        data = {
            'username': '******',
            'percent': 100,
            'comment': 'Tests passed',
            'url': 'http://jenkins.cloud.fedoraproject.org/',
            'uid': 'jenkins_build_pagure_100+seed',
        }

        output = self.app.post('/api/0/test/pull-request/1/flag',
                               data=data,
                               headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(data, {'message': 'Flag updated'})

        # One flag added
        request = pagure.lib.search_pull_requests(self.session,
                                                  project_id=1,
                                                  requestid=1)
        self.assertEqual(len(request.flags), 1)
        self.assertEqual(request.flags[0].comment, 'Tests passed')
        self.assertEqual(request.flags[0].percent, 100)
Пример #50
0
def insert_data(session, username, user_email):
    _config['EMAIL_SEND'] = False
    _config['TESTING'] = True

    # Populate with default statuses
    create_default_status(session)
    print('Default statuses populated')

    ######################################
    # tags
    item = pagure.lib.model.Tag(tag='tag1', )
    session.add(item)
    session.commit()

    ######################################
    # Users
    # Create a couple of users
    pingou = item = pagure.lib.model.User(
        user='******',
        fullname='PY C',
        password=generate_hashed_value(u'testing123'),
        token=None,
        default_email='*****@*****.**',
    )
    session.add(item)
    session.commit()
    print("User created: {} <{}>, {}".format(item.user, item.default_email,
                                             'testing123'))

    foo = item = pagure.lib.model.User(
        user='******',
        fullname='foo bar',
        password=generate_hashed_value(u'testing123'),
        token=None,
        default_email='*****@*****.**',
    )
    session.add(item)
    session.commit()
    print("User created: {} <{}>, {}".format(item.user, item.default_email,
                                             'testing123'))

    you = item = pagure.lib.model.User(
        user=username,
        fullname=username,
        password=generate_hashed_value(u'testing123'),
        token=None,
        default_email=user_email,
    )
    session.add(item)
    session.commit()
    print("User created: {} <{}>, {}".format(item.user, item.default_email,
                                             'testing123'))

    ######################################
    # pagure_group
    item = pagure.lib.model.PagureGroup(
        group_name='admin',
        group_type='admin',
        user_id=pingou.id,
        display_name='admin',
        description='Admin Group',
    )
    session.add(item)
    session.commit()
    print('Created "admin" group. Pingou is a member.')

    # Add a couple of groups so that we can list them
    item = pagure.lib.model.PagureGroup(
        group_name='group',
        group_type='user',
        user_id=pingou.id,
        display_name='group group',
        description='this is a group group',
    )
    session.add(item)
    session.commit()
    print('Created "group" group. Pingou is a member.')

    item = pagure.lib.model.PagureGroup(
        group_name='rel-eng',
        group_type='user',
        user_id=pingou.id,
        display_name='Release Engineering',
        description='The group of release engineers',
    )
    session.add(item)
    session.commit()
    print('Created "rel-eng" group. Pingou is a member.')
    ######################################
    # projects

    import shutil
    # delete folder from local instance to start from a clean slate
    if os.path.exists(_config['GIT_FOLDER']):
        shutil.rmtree(_config['GIT_FOLDER'])

    # Create projects
    item = project1 = pagure.lib.model.Project(
        user_id=pingou.id,
        name='test',
        is_fork=False,
        parent_id=None,
        description='test project #1',
        hook_token='aaabbbccc',
    )
    item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate']
    session.add(item)
    session.flush()
    tests.create_locks(session, item)

    item = project2 = pagure.lib.model.Project(
        user_id=pingou.id,
        name='test2',
        is_fork=False,
        parent_id=None,
        description='test project #2',
        hook_token='aaabbbddd',
    )
    item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate']
    session.add(item)

    item = project3 = pagure.lib.model.Project(
        user_id=pingou.id,
        name='test3',
        is_fork=False,
        parent_id=None,
        description='namespaced test project',
        hook_token='aaabbbeee',
        namespace='somenamespace',
    )
    item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate']
    session.add(item)

    session.commit()

    tests.create_projects_git(_config['GIT_FOLDER'], bare=True)
    add_content_git_repo(os.path.join(_config['GIT_FOLDER'], 'test.git'))
    tests.add_readme_git_repo(os.path.join(_config['GIT_FOLDER'], 'test.git'))

    # Add some content to the git repo
    add_content_git_repo(
        os.path.join(_config['GIT_FOLDER'], 'forks', 'pingou', 'test.git'))
    tests.add_readme_git_repo(
        os.path.join(_config['GIT_FOLDER'], 'forks', 'pingou', 'test.git'))
    tests.add_commit_git_repo(os.path.join(_config['GIT_FOLDER'], 'forks',
                                           'pingou', 'test.git'),
                              ncommits=10)

    ######################################
    # user_emails
    item = pagure.lib.model.UserEmail(user_id=pingou.id,
                                      email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=pingou.id,
                                      email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=foo.id, email='*****@*****.**')
    session.add(item)

    item = pagure.lib.model.UserEmail(user_id=you.id, email=user_email)
    session.add(item)

    session.commit()

    ######################################
    # user_emails_pending
    email_pend = pagure.lib.model.UserEmailPending(
        user_id=pingou.id,
        email='[email protected]',
        token='abcdef',
    )
    session.add(email_pend)
    session.commit()

    ######################################
    # issues
    # Add an issue and tag it so that we can list them
    item = pagure.lib.model.Issue(
        id=1001,
        uid='foobar',
        project_id=project1.id,
        title='Problem with jenkins build',
        content='For some reason the tests fail at line:24',
        user_id=pingou.id,
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.Issue(
        id=1002,
        uid='foobar2',
        project_id=project1.id,
        title='Unit tests failing',
        content='Need to fix code for the unit tests to '
        'pass so jenkins build can complete.',
        user_id=pingou.id,
    )
    session.add(item)
    session.commit()

    item = pagure.lib.model.Issue(
        id=1003,
        uid='foobar3',
        project_id=project1.id,
        title='Segfault during execution',
        content='Index out of bounds for variable i?',
        user_id=you.id,
    )
    session.add(item)
    session.commit()

    ######################################
    # pagure_user_group
    group = pagure.lib.query.search_groups(session,
                                           pattern=None,
                                           group_name="rel-eng",
                                           group_type=None)
    item = pagure.lib.model.PagureUserGroup(user_id=pingou.id,
                                            group_id=group.id)
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(session,
                                           pattern=None,
                                           group_name="admin",
                                           group_type=None)

    item = pagure.lib.model.PagureUserGroup(user_id=you.id, group_id=group.id)
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(session,
                                           pattern=None,
                                           group_name="group",
                                           group_type=None)

    item = pagure.lib.model.PagureUserGroup(user_id=foo.id, group_id=group.id)
    session.add(item)
    session.commit()

    ######################################
    # projects_groups
    group = pagure.lib.query.search_groups(session,
                                           pattern=None,
                                           group_name="rel-eng",
                                           group_type=None)
    repo = pagure.lib.query.get_authorized_project(session, 'test')
    item = pagure.lib.model.ProjectGroup(project_id=repo.id,
                                         group_id=group.id,
                                         access="commit")
    session.add(item)
    session.commit()

    group = pagure.lib.query.search_groups(session,
                                           pattern=None,
                                           group_name="admin",
                                           group_type=None)
    repo = pagure.lib.query.get_authorized_project(session, 'test2')
    item = pagure.lib.model.ProjectGroup(project_id=repo.id,
                                         group_id=group.id,
                                         access="admin")
    session.add(item)
    session.commit()

    ######################################
    # pull_requests
    repo = pagure.lib.query.get_authorized_project(session, 'test')
    forked_repo = pagure.lib.query.get_authorized_project(session, 'test')
    req = pagure.lib.query.new_pull_request(session=session,
                                            repo_from=forked_repo,
                                            branch_from='master',
                                            repo_to=repo,
                                            branch_to='master',
                                            title='Fixing code for unittest',
                                            user=username)
    session.commit()

    ######################################
    # tokens
    tests.create_tokens(session, user_id=pingou.id, project_id=project1.id)

    ######################################
    # user_projects
    repo = pagure.lib.query.get_authorized_project(session, 'test')
    item = pagure.lib.model.ProjectUser(project_id=repo.id,
                                        user_id=foo.id,
                                        access="commit")
    session.add(item)
    session.commit()

    repo = pagure.lib.query.get_authorized_project(session, 'test2')
    item = pagure.lib.model.ProjectUser(project_id=repo.id,
                                        user_id=you.id,
                                        access="commit")
    session.add(item)
    session.commit()

    ######################################
    # issue_comments
    item = pagure.lib.model.IssueComment(
        user_id=pingou.id,
        issue_uid='foobar',
        comment='We may need to adjust the unittests instead of the code.',
    )
    session.add(item)
    session.commit()

    ######################################
    # issue_to_issue
    repo = pagure.lib.query.get_authorized_project(session, 'test')
    all_issues = pagure.lib.query.search_issues(session, repo)
    pagure.lib.query.add_issue_dependency(session, all_issues[0],
                                          all_issues[1], 'pingou')

    ######################################
    # pull_request_comments
    user = pagure.lib.query.search_user(session, username='******')
    # only 1 pull request available atm
    pr = pagure.lib.query.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestComment(
        pull_request_uid=pr.uid,
        user_id=user.id,
        comment="+1 for me. Btw, could you rebase before you merge?",
        notification=0)
    session.add(item)
    session.commit()

    ######################################
    # pull_request_flags
    # only 1 pull request available atm
    pr = pagure.lib.query.get_pull_request_of_user(session, "pingou")[0]
    item = pagure.lib.model.PullRequestFlag(uid="random_pr_flag_uid",
                                            pull_request_uid=pr.uid,
                                            user_id=pingou.id,
                                            username=pingou.user,
                                            percent=80,
                                            comment="Jenkins build passes",
                                            url=str(pr.id),
                                            status="Open")
    session.add(item)
    session.commit()

    ######################################
    # tags_issues
    repo = pagure.lib.query.get_authorized_project(session, 'test')
    issues = pagure.lib.query.search_issues(session, repo)
    item = pagure.lib.model.TagIssue(
        issue_uid=issues[0].uid,
        tag='tag1',
    )
    session.add(item)
    session.commit()

    ######################################
    # tokens_acls
    tests.create_tokens_acl(session)

    ######################################
    # Fork a project
    # delete fork data
    fork_proj_location = "forks/foo/test.git"
    try:
        shutil.rmtree(os.path.join(_config['GIT_FOLDER'], fork_proj_location))
    except:
        print('git folder already deleted')

    try:
        shutil.rmtree(os.path.join(_config['DOCS_FOLDER'], fork_proj_location))
    except:
        print('docs folder already deleted')

    try:
        shutil.rmtree(
            os.path.join(_config['TICKETS_FOLDER'], fork_proj_location))
    except:
        print('tickets folder already deleted')

    try:
        shutil.rmtree(
            os.path.join(_config['REQUESTS_FOLDER'], fork_proj_location))
    except:
        print('requests folder already deleted')

    repo = pagure.lib.query.get_authorized_project(session, 'test')
    result = pagure.lib.query.fork_project(session, 'foo', repo)
    if result == 'Repo "test" cloned to "foo/test"':
        session.commit()
Пример #51
0
    def test_api_change_status_issue(self):
        """ Test the api_change_status_issue method of the flask api. """
        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(tests.HERE, 'tickets'))
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

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

        # Invalid project
        output = self.app.post('/api/0/foo/issue/1/status', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Project not found",
              "error_code": "ENOPROJECT",
            }
        )

        # Valid token, wrong project
        output = self.app.post('/api/0/test2/issue/1/status', 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",
            }
        )

        # No input
        output = self.app.post('/api/0/test/issue/1/status', headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {
              "error": "Issue not found",
              "error_code": "ENOISSUE",
            }
        )

        # Create normal issue
        repo = pagure.lib.get_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 another project
        item = pagure.lib.model.Project(
            user_id=2,  # pingou
            name='foo',
            description='test project #3',
            hook_token='aaabbbdddeee',
        )
        self.session.add(item)
        self.session.commit()

        # Create a token for pingou for this project
        item = pagure.lib.model.Token(
            id='pingou_foo',
            user_id=1,
            project_id=3,
            expiration=datetime.datetime.utcnow() + datetime.timedelta(
                days=30)
        )
        self.session.add(item)
        self.session.commit()

        # Give `change_status_issue` to this token
        item = pagure.lib.model.TokenAcl(
            token_id='pingou_foo',
            acl_id=6,
        )
        self.session.add(item)
        self.session.commit()

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

        # Check status before
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(issue.status, 'Open')

        data = {
            'title': 'test issue',
        }

        # Incomplete request
        output = self.app.post(
            '/api/0/test/issue/1/status', data=data, 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",
            }
        )

        # No change
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(issue.status, 'Open')

        data = {
            'status': 'Open',
        }

        # Valid request but no change
        output = self.app.post(
            '/api/0/test/issue/1/status', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'No changes'}
        )

        # No change
        repo = pagure.lib.get_project(self.session, 'test')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(issue.status, 'Open')

        data = {
            'status': 'Fixed',
        }

        # Valid request
        output = self.app.post(
            '/api/0/test/issue/1/status', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data,
            {'message': 'Successfully edited issue #1'}
        )

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

        # Un-authorized issue
        output = self.app.post(
            '/api/0/foo/issue/1/status', data=data, 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"
            }
        )
Пример #52
0
    def test_api_fork_project(self, p_gga):
        """ Test the api_fork_project method of the flask api. """
        p_gga.return_value = True

        tests.create_projects(self.session)
        for folder in ['docs', 'tickets', 'requests', 'repos']:
            tests.create_projects_git(os.path.join(tests.HERE, folder),
                                      bare=True)
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

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

        # Invalid token
        output = self.app.post('/api/0/fork', 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"
            }
        )

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

        # No input
        output = self.app.post('/api/0/fork', 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",
            })

        data = {
            'name': 'test',
        }

        # Incomplete request
        output = self.app.post('/api/0/fork', data=data, 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",
            })

        data = {
            'repo': 'test',
        }

        # Valid request
        output = self.app.post('/api/0/fork/', data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(
            data, {"message": "Repo \"test\" cloned to \"pingou/test\""})

        data = {
            'repo': 'test',
        }

        # project already forked
        output = self.app.post('/api/0/fork/', data=data, headers=headers)
        self.assertEqual(output.status_code, 400)
        data = json.loads(output.data)
        self.assertDictEqual(
            data, {
                "error": "Repo \"forks/pingou/test\" already exists",
                "error_code": "ENOCODE"
            })

        data = {
            'repo': 'test',
            'username': '******',
        }

        # Fork already exists
        output = self.app.post('/api/0/fork/', data=data, headers=headers)
        self.assertEqual(output.status_code, 400)
        data = json.loads(output.data)
        self.assertDictEqual(
            data, {
                "error": "Repo \"forks/pingou/test\" already exists",
                "error_code": "ENOCODE"
            })
Пример #53
0
    def test_api_change_status_issue(self):
        """ Test the api_change_status_issue method of the flask api. """
        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(tests.HERE, "tickets"))
        tests.create_tokens(self.session)
        tests.create_tokens_acl(self.session)

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

        # Invalid project
        output = self.app.post("/api/0/foo/issue/1/status", headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(data, {"error": "Project not found", "error_code": "ENOPROJECT"})

        # Valid token, wrong project
        output = self.app.post("/api/0/test2/issue/1/status", 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",
            },
        )

        # No input
        output = self.app.post("/api/0/test/issue/1/status", headers=headers)
        self.assertEqual(output.status_code, 404)
        data = json.loads(output.data)
        self.assertDictEqual(data, {"error": "Issue not found", "error_code": "ENOISSUE"})

        # Create normal issue
        repo = pagure.lib.get_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 another project
        item = pagure.lib.model.Project(
            user_id=2, name="foo", description="test project #3", hook_token="aaabbbdddeee"  # pingou
        )
        self.session.add(item)
        self.session.commit()

        # Create a token for pingou for this project
        item = pagure.lib.model.Token(
            id="pingou_foo",
            user_id=1,
            project_id=3,
            expiration=datetime.datetime.utcnow() + datetime.timedelta(days=30),
        )
        self.session.add(item)
        self.session.commit()

        # Give `change_status_issue` to this token
        item = pagure.lib.model.TokenAcl(token_id="pingou_foo", acl_id=6)
        self.session.add(item)
        self.session.commit()

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

        # Check status before
        repo = pagure.lib.get_project(self.session, "test")
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(issue.status, "Open")

        data = {"title": "test issue"}

        # Incomplete request
        output = self.app.post("/api/0/test/issue/1/status", data=data, 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"})

        # No change
        repo = pagure.lib.get_project(self.session, "test")
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(issue.status, "Open")

        data = {"status": "Open"}

        # Valid request but no change
        output = self.app.post("/api/0/test/issue/1/status", data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(data, {"message": "No changes"})

        # No change
        repo = pagure.lib.get_project(self.session, "test")
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        self.assertEqual(issue.status, "Open")

        data = {"status": "Fixed"}

        # Valid request
        output = self.app.post("/api/0/test/issue/1/status", data=data, headers=headers)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.data)
        self.assertDictEqual(data, {"message": "Successfully edited issue #1"})

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

        # Un-authorized issue
        output = self.app.post("/api/0/foo/issue/1/status", data=data, headers=headers)
        self.assertEqual(output.status_code, 403)
        data = json.loads(output.data)
        self.assertDictEqual(
            data, {"error": "You are not allowed to view this issue", "error_code": "EISSUENOTALLOWED"}
        )
    def test_api_project_tag_delete_with_assigned_issue_and_pr(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)

        # Add a tag
        item = pagure.lib.model.TagColored(tag="blue",
                                           tag_color="DeepBlueSky",
                                           project_id=1)
        self.session.add(item)
        self.session.commit()

        # Add a tagged issue
        item = pagure.lib.model.Issue(
            id=1,
            uid="foobar",
            project_id=1,
            title="issue",
            content="a bug report",
            user_id=1,  # pingou
        )
        self.session.add(item)
        self.session.commit()
        item = pagure.lib.model.TagIssueColored(issue_uid="foobar", tag_id=1)
        self.session.add(item)
        self.session.commit()

        # Add a tagged pull request
        item = pagure.lib.model.PullRequest(
            id=1,
            uid="barfoo",
            project_id=1,
            branch="master",
            branch_from="master",
            title="pull request",
            allow_rebase=False,
            user_id=1,  # pingou
        )
        self.session.add(item)
        self.session.commit()
        item = pagure.lib.model.TagPullRequest(request_uid="barfoo", tag_id=1)
        self.session.add(item)
        self.session.commit()

        output = self.app.get("/api/0/test/tags/")
        self.assertEqual(output.status_code, 200)
        expected_rv = {"tags": ["blue"], "total_tags": 1}
        data = json.loads(output.get_data(as_text=True))
        self.assertDictEqual(data, expected_rv)

        headers = {"Authorization": "token aaabbbcccddd"}
        output = self.app.delete("/api/0/test/tag/blue", headers=headers)
        self.assertEqual(output.status_code, 200)
        expected_rv = {"message": "Tag: blue has been deleted"}
        data = json.loads(output.get_data(as_text=True))
        self.assertDictEqual(data, expected_rv)

        output = self.app.get("/api/0/test/tags/")
        self.assertEqual(output.status_code, 200)
        expected_rv = {"tags": [], "total_tags": 0}
        data = json.loads(output.get_data(as_text=True))
        self.assertDictEqual(data, expected_rv)