<commit_before>"""
pyapi-gitlab tests
"""

import unittest
import gitlab
import os
import time
import random
import string
try:
    from Crypto.PublicKey import RSA
    ssh_test = True
except ImportError:
    ssh_test = False

user = os.environ.get('gitlab_user', 'root')
password = os.environ.get('gitlab_password', '<PASSWORD>')
host = os.environ.get('gitlab_host', 'http://localhost:8080')


class GitlabTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.git = gitlab.Gitlab(host=host)
        cls.git.login(user=user, password=password)
        name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
        cls.project = cls.git.createproject(name=name, visibility_level="private",
                                            import_url="https://github.com/Itxaka/pyapi-gitlab.git")
        # wait a bit for the project to be fully imported
        time.sleep(30)
        cls.project_id = cls.project['id']
        cls.user_id = cls.git.currentuser()['id']

    @classmethod
    def tearDownClass(cls):
        cls.git.deleteproject(cls.project_id)

    def test_user(self):
        assert isinstance(self.git.createuser(name="test", username="test",
                                              password="<PASSWORD>", email="<EMAIL>",
                                              skype="this", linkedin="that"), dict)
        # get all users
        assert isinstance(self.git.getusers(), list)  # compatible with 2.6
        assert isinstance(self.git.currentuser(), dict)
        user = self.git.getusers(search="test")[0]
        self.assertTrue(self.git.deleteuser(user["id"]))
        # check can_create_user
        user = self.git.createuser("random", "random", "random1234", "<EMAIL>",
                                   can_create_group="false")
        self.assertFalse(self.git.getuser(user['id'])['can_create_group'])
        self.git.deleteuser(user['id'])
        user = self.git.createuser("random", "random", "random1234", "<EMAIL>",
                                   can_create_group="true")
        self.assertTrue(self.git.getuser(user['id'])['can_create_group'])
        assert isinstance(self.git.edituser(user['id'], can_create_group="false"), dict)
        # Check that indeed the user details were changed
        self.assertFalse(self.git.getuser(user['id'])['can_create_group'])
        self.git.deleteuser(user['id'])
        # get X pages
        assert isinstance(self.git.getusers(page=2), list)  # compatible with 2.6
        assert isinstance(self.git.getusers(per_page=4), list)  # compatible with 2.6
        self.assertEqual(self.git.getusers(page=800), list(""))  # check against empty list
        self.assertTrue(self.git.getusers(per_page=43))  # check against false

    def test_project(self):
        # test project
        assert isinstance(self.git.getprojects(), list)
        assert isinstance(self.git.getprojects(page=5), list)
        assert isinstance(self.git.getprojects(per_page=7), list)
        assert isinstance(self.git.getproject(self.project_id), dict)
        self.assertFalse(self.git.getproject("wrong"))

        # test events
        assert isinstance(self.git.getprojectevents(self.project_id), list)
        assert isinstance(self.git.getprojectevents(self.project_id, page=3), list)
        assert isinstance(self.git.getprojectevents(self.project_id, per_page=4), list)

        # add-remove project members
        self.assertTrue(self.git.addprojectmember(id_=self.project_id, user_id=self.user_id, access_level="reporter", sudo=1))
        assert isinstance(self.git.listprojectmembers(id_=self.project_id), list)
        self.assertTrue(self.git.editprojectmember(id_=self.project_id, user_id=self.user_id, access_level="master", sudo=1))
        self.assertTrue(self.git.deleteprojectmember(id_=self.project_id, user_id=1))

        # Hooks testing
        self.assertTrue(self.git.addprojecthook(self.project_id, "http://web.com"))
        assert isinstance(self.git.getprojecthooks(self.project_id), list)
        assert isinstance(self.git.getprojecthook(self.project_id,
                                                  self.git.getprojecthooks(self.project_id)[0]['id']), dict)
        self.assertTrue(self.git.editprojecthook(self.project_id,
                                                 self.git.getprojecthooks(self.project_id)[0]['id'], "http://another.com"))
        self.assertTrue(self.git.deleteprojecthook(self.project_id,
                                                   self.git.getprojecthooks(self.project_id)[0]['id']))

    def test_branch(self):
        sha1 = self.git.listrepositorycommits(project_id=self.project_id)[0]["id"]
        assert isinstance(self.git.createbranch(id_=self.project_id, branch="deleteme", ref=sha1), dict)
        self.assertTrue(self.git.deletebranch(id_=self.project_id, branch="deleteme"))
        assert isinstance(self.git.listbranches(id_=self.project_id), list)
        assert isinstance(self.git.listbranch(id_=self.project_id, branch="develop"), dict)
        self.assertTrue(self.git.protectbranch(id_=self.project_id, branch="develop"))
        self.assertTrue(self.git.unprotectbranch(id_=self.project_id, branch="develop"))

    def test_sshkeys(self):
        assert isinstance(self.git.getsshkeys(), list)
        self.assertEquals(len(self.git.getsshkeys()), 0)
        # not working due a bug? in pycrypto: https://github.com/dlitz/pycrypto/issues/99
        """
        if ssh_test:
            name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
            rsa_key = RSA.generate(1024)
            print(str(rsa_key.publickey().exportKey()))
            print(str(rsa_key.publickey().exportKey(format="OpenSSH")))
            self.assertTrue(self.git.addsshkey(title=name, key=str(rsa_key.publickey().exportKey())))
            self.assertGreater(self.git.getsshkeys(), 0)
            print(self.git.getsshkeys())
            key = self.git.getsshkeys()[0]
            self.git.deletesshkey(key["id"])"""

    def test_snippets(self):
        assert isinstance(self.git.createsnippet(self.project_id, "test", "test", "codeee"), dict)
        assert isinstance(self.git.getsnippets(self.project_id), list)
        snippet = self.git.getsnippets(self.project_id)[0]
        assert isinstance(self.git.getsnippet(self.project_id, snippet["id"]), dict)
        self.assertTrue(self.git.deletesnippet(self.project_id, snippet["id"]))

    def test_repositories(self):
        assert isinstance(self.git.getrepositories(self.project_id), list)
        assert isinstance(self.git.getrepositorybranch(self.project_id, "develop"), dict)
        assert isinstance(self.git.protectrepositorybranch(self.project_id, "develop"), dict)
        assert isinstance(self.git.unprotectrepositorybranch(self.project_id, "develop"), dict)
        assert isinstance(self.git.listrepositorytags(self.project_id), list)
        assert isinstance(self.git.listrepositorycommits(self.project_id), list)
        assert isinstance(self.git.listrepositorycommits(self.project_id, page=1), list)
        assert isinstance(self.git.listrepositorycommits(self.project_id, per_page=7), list)
        commit = self.git.listrepositorycommits(self.project_id)[0]
        assert isinstance(self.git.listrepositorycommit(self.project_id, commit["id"]), dict)
        assert isinstance(self.git.listrepositorycommitdiff(self.project_id, commit["id"]), list)
        assert isinstance(self.git.listrepositorytree(self.project_id), list)
        assert isinstance(self.git.listrepositorytree(self.project_id, path="docs"), list)
        assert isinstance(self.git.listrepositorytree(self.project_id, ref_name="develop"), list)
        assert isinstance(str(self.git.getrawblob(self.project_id, commit['id'], "setup.py")), str)

    def test_search(self):
        self.assertGreater(len(self.git.searchproject(self.project['name'])), 0)
        assert isinstance(self.git.searchproject(self.project['name']), list)

    def test_filearchive(self):
        # test it works
        self.assertTrue(self.git.getfilearchive(self.project_id, self.project["name"] + ".tar.gz"))
        # test for failure<commit_msg>add a test for compare_branches_tags_commits<commit_after>"""
pyapi-gitlab tests
"""

import unittest
import gitlab
import os
import time
import random
import string
try:
    from Crypto.PublicKey import RSA
    ssh_test = True
except ImportError:
    ssh_test = False

user = os.environ.get('gitlab_user', 'root')
password = os.environ.get('gitlab_password', '<PASSWORD>')
host = os.environ.get('gitlab_host', 'http://localhost:8080')


class GitlabTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.git = gitlab.Gitlab(host=host)
        cls.git.login(user=user, password=password)
        name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
        cls.project = cls.git.createproject(name=name, visibility_level="private",
                                            import_url="https://github.com/Itxaka/pyapi-gitlab.git")
        # wait a bit for the project to be fully imported
        time.sleep(30)
        cls.project_id = cls.project['id']
        cls.user_id = cls.git.currentuser()['id']

    @classmethod
    def tearDownClass(cls):
        cls.git.deleteproject(cls.project_id)

    def test_user(self):
        assert isinstance(self.git.createuser(name="test", username="test",
                                              password="<PASSWORD>", email="<EMAIL>",
                                              skype="this", linkedin="that"), dict)
        # get all users
        assert isinstance(self.git.getusers(), list)  # compatible with 2.6
        assert isinstance(self.git.currentuser(), dict)
        user = self.git.getusers(search="test")[0]
        self.assertTrue(self.git.deleteuser(user["id"]))
        # check can_create_user
        user = self.git.createuser("random", "random", "random1234", "<EMAIL>",
                                   can_create_group="false")
        self.assertFalse(self.git.getuser(user['id'])['can_create_group'])
        self.git.deleteuser(user['id'])
        user = self.git.createuser("random", "random", "random1234", "<EMAIL>",
                                   can_create_group="true")
        self.assertTrue(self.git.getuser(user['id'])['can_create_group'])
        assert isinstance(self.git.edituser(user['id'], can_create_group="false"), dict)
        # Check that indeed the user details were changed
        self.assertFalse(self.git.getuser(user['id'])['can_create_group'])
        self.git.deleteuser(user['id'])
        # get X pages
        assert isinstance(self.git.getusers(page=2), list)  # compatible with 2.6
        assert isinstance(self.git.getusers(per_page=4), list)  # compatible with 2.6
        self.assertEqual(self.git.getusers(page=800), list(""))  # check against empty list
        self.assertTrue(self.git.getusers(per_page=43))  # check against false

    def test_project(self):
        # test project
        assert isinstance(self.git.getprojects(), list)
        assert isinstance(self.git.getprojects(page=5), list)
        assert isinstance(self.git.getprojects(per_page=7), list)
        assert isinstance(self.git.getproject(self.project_id), dict)
        self.assertFalse(self.git.getproject("wrong"))

        # test events
        assert isinstance(self.git.getprojectevents(self.project_id), list)
        assert isinstance(self.git.getprojectevents(self.project_id, page=3), list)
        assert isinstance(self.git.getprojectevents(self.project_id, per_page=4), list)

        # add-remove project members
        self.assertTrue(self.git.addprojectmember(id_=self.project_id, user_id=self.user_id, access_level="reporter", sudo=1))
        assert isinstance(self.git.listprojectmembers(id_=self.project_id), list)
        self.assertTrue(self.git.editprojectmember(id_=self.project_id, user_id=self.user_id, access_level="master", sudo=1))
        self.assertTrue(self.git.deleteprojectmember(id_=self.project_id, user_id=1))

        # Hooks testing
        self.assertTrue(self.git.addprojecthook(self.project_id, "http://web.com"))
        assert isinstance(self.git.getprojecthooks(self.project_id), list)
        assert isinstance(self.git.getprojecthook(self.project_id,
                                                  self.git.getprojecthooks(self.project_id)[0]['id']), dict)
        self.assertTrue(self.git.editprojecthook(self.project_id,
                                                 self.git.getprojecthooks(self.project_id)[0]['id'], "http://another.com"))
        self.assertTrue(self.git.deleteprojecthook(self.project_id,
                                                   self.git.getprojecthooks(self.project_id)[0]['id']))

    def test_branch(self):
        sha1 = self.git.listrepositorycommits(project_id=self.project_id)[0]["id"]
        assert isinstance(self.git.createbranch(id_=self.project_id, branch="deleteme", ref=sha1), dict)
        self.assertTrue(self.git.deletebranch(id_=self.project_id, branch="deleteme"))
        assert isinstance(self.git.listbranches(id_=self.project_id), list)
        assert isinstance(self.git.listbranch(id_=self.project_id, branch="develop"), dict)
        self.assertTrue(self.git.protectbranch(id_=self.project_id, branch="develop"))
        self.assertTrue(self.git.unprotectbranch(id_=self.project_id, branch="develop"))

    def test_sshkeys(self):
        assert isinstance(self.git.getsshkeys(), list)
        self.assertEquals(len(self.git.getsshkeys()), 0)
        # not working due a bug? in pycrypto: https://github.com/dlitz/pycrypto/issues/99
        """
        if ssh_test:
            name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
            rsa_key = RSA.generate(1024)
            print(str(rsa_key.publickey().exportKey()))
            print(str(rsa_key.publickey().exportKey(format="OpenSSH")))
            self.assertTrue(self.git.addsshkey(title=name, key=str(rsa_key.publickey().exportKey())))
            self.assertGreater(self.git.getsshkeys(), 0)
            print(self.git.getsshkeys())
            key = self.git.getsshkeys()[0]
            self.git.deletesshkey(key["id"])"""

    def test_snippets(self):
        assert isinstance(self.git.createsnippet(self.project_id, "test", "test", "codeee"), dict)
        assert isinstance(self.git.getsnippets(self.project_id), list)
        snippet = self.git.getsnippets(self.project_id)[0]
        assert isinstance(self.git.getsnippet(self.project_id, snippet["id"]), dict)
        self.assertTrue(self.git.deletesnippet(self.project_id, snippet["id"]))

    def test_repositories(self):
        assert isinstance(self.git.getrepositories(self.project_id), list)
        assert isinstance(self.git.getrepositorybranch(self.project_id, "develop"), dict)
        assert isinstance(self.git.protectrepositorybranch(self.project_id, "develop"), dict)
        assert isinstance(self.git.unprotectrepositorybranch(self.project_id, "develop"), dict)
        assert isinstance(self.git.listrepositorytags(self.project_id), list)
        assert isinstance(self.git.listrepositorycommits(self.project_id), list)
        assert isinstance(self.git.listrepositorycommits(self.project_id, page=1), list)
        assert isinstance(self.git.listrepositorycommits(self.project_id, per_page=7), list)
        commit = self.git.listrepositorycommits(self.project_id)[0]
        assert isinstance(self.git.listrepositorycommit(self.project_id, commit["id"]), dict)
        assert isinstance(self.git.listrepositorycommitdiff(self.project_id, commit["id"]), list)
        assert isinstance(self.git.listrepositorytree(self.project_id), list)
        assert isinstance(self.git.listrepositorytree(self.project_id, path="docs"), list)
        assert isinstance(self.git.listrepositorytree(self.project_id, ref_name="develop"), list)
        assert isinstance(str(self.git.getrawblob(self.project_id, commit['id'], "setup.py")), str)
        commit = self.git.listrepositorycommits(self.project_id)
        assert isinstance(self.git.compare_branches_tags_commits(self.project_id,
                                                                 from_id=commit[1]["id"],
                                                                 to_id=commit[0]["id"]), dict)


    def test_search(self):
        self.assertGreater(len(self.git.searchproject(self.project['name'])), 0)
        assert isinstance(self.git.searchproject(self.project['name']), list)

    def test_filearchive(self):
        # test it works
        self.assertTrue(self.git.getfilearchive(self.project_id, self.project["name"] + ".tar.gz"))
        # test for failure
{'fraction_non_alphanumeric': 0.13277810826888756, 'fraction_numerical': 0.006900654372397383, 'mean_word_length': 3.142681123706259, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1059100', 'n_tokens_mistral': 5017, 'n_tokens_neox': 4937, 'n_words': 744}