diff --git a/gitea/gitea.py b/gitea/gitea.py index f709106..8bc98a1 100644 --- a/gitea/gitea.py +++ b/gitea/gitea.py @@ -21,9 +21,6 @@ class GiteaApiObject: self.id = id self.gitea = gitea - def __repr__(self): - return "GiteaApiObject: %i" % (self.id) - def __eq__(self, other): return other.id == self.id if isinstance(other, type(self)) else False @@ -42,9 +39,9 @@ class GiteaApiObject: def _request(cls, gitea, args): result = cls._get_gitea_api_object(gitea, args) api_object = cls.parse_request(gitea, result) - api_object = cls.parse_request(gitea, result) for key, value in args.items(): # hack: not all necessary request args in api result (e.g. repo name in issue) - setattr(api_object, key, value) + if not hasattr(api_object, key): + setattr(api_object, key, value) return api_object @classmethod @@ -70,7 +67,6 @@ class GiteaApiObject: setattr(api_object, i, v) - class Organization(GiteaApiObject): GET_API_OBJECT = """/orgs/{name}""" # @@ -88,7 +84,6 @@ class Organization(GiteaApiObject): def request(cls, gitea, name): return cls._request(gitea, {"name": name}) - # oldstuff def get_repositories(self): @@ -114,7 +109,7 @@ class Organization(GiteaApiObject): results = self.gitea.requests_get( Organization.ORG_TEAMS_REQUEST % self.username ) - return [Team(self, result["name"], initJson=result) for result in results] + return [Team.parse_request(self, result) for result in results] def get_members(self): """ Get all members of this Organization @@ -245,7 +240,8 @@ class Repository(GiteaApiObject): super(Repository, self).__init__(gitea, id=id) fields_to_parsers = { - "owner": lambda gitea, r: User.parse_request(gitea, r), + # dont know how to tell apart user and org as owner except form email being empty. + "owner": lambda gitea, r: Organization.parse_request(gitea,r) if r["email"] == "" else User.parse_request(gitea, r), "updated_at": lambda gitea, t: Util.convert_time(t) } @@ -262,7 +258,7 @@ class Repository(GiteaApiObject): results = self.gitea.requests_get( Repository.REPO_BRANCHES % (self.owner.username, self.name) ) - return [Branch(self, result["name"], result) for result in results] + return [Branch.parse_request(self.gitea, result) for result in results] def get_issues(self): """Get all Issues of this Repository. @@ -335,14 +331,17 @@ class Repository(GiteaApiObject): class Milestone(GiteaApiObject): - """Reperesents a Milestone in Gitea. - """ GET_API_OBJECT = """/repos/{owner}/{repo}/milestones/{number}""" # def __init__(self, gitea, id: int): super(Milestone, self).__init__(gitea, id=id) + fields_to_parsers = { + "closed_at": lambda gitea, t: Util.convert_time(t), + "due_on": lambda gitea, t: Util.convert_time(t) + } + @classmethod def request(cls, gitea, owner, repo, number): return cls._request(gitea, {"owner":owner, "repo":repo, "number":number}) @@ -396,119 +395,37 @@ class Issue(GiteaApiObject): ) -class Branch: - """ Represents a Branch in the Gitea-instance. +class Branch(GiteaApiObject): - Attr: - name: string - commit: Commit - """ + GET_API_OBJECT = """/repos/%s/%s/branches/%s""" # , , - REPO_BRANCH = """/repos/%s/%s/branches/%s""" # , , + def __init__(self, gitea, id: int): + super(Branch, self).__init__(gitea, id=id) - def __init__(self, repo: Repository, name: str, initJson: json = None): - """ Initializes a Branch. - - Args: - repo (Repository): The Repository of this Branch. - name (str): The name of this Branch. - initJson (dict): Optional, init information for Branch. - - Warning: - This does not create a Branch. does. - - Throws: - NotFoundException, if Branch could not be found. - """ - self.gitea = repo.gitea - self.__initialize_branch(repo, name, initJson) - - def __initialize_branch(self, repository, name, result): - """ Initializing a Branch. - - Args: - repository (Repository): The Repository of this Branch. - name (str): The name of this Branch. - result (dict): Optional, init information for Branch. - - Throws: - NotFoundException, if Branch could not be found. - """ - if not result: - result = self.gitea.requests_get( - Branch.REPO_BRANCH % (repository.owner.username, repository.name, name) - ) - logging.debug( - "Branch found: %s/%s/%s" - % (repository.owner.username, repository.name, name) - ) - for i, v in result.items(): - setattr(self, i, v) - self.repository = repository + @classmethod + def request(cls, gitea, owner, repo, ref): + return cls._request(gitea, {"owner":owner, "repo":repo, "ref":ref}) -class Team: - """ Represents a Team in the Gitea-instance. - """ +class Team(GiteaApiObject): - # GET_TEAM = """/orgs/%s/teams""" - GET_TEAM = """/teams/%s""" # + GET_API_OBJECT = """/teams/{id}""" # ADD_USER = """/teams/%s/members/%s""" # ADD_REPO = """/teams/%s/repos/%s/%s""" # TEAM_DELETE = """/teams/%s""" # GET_MEMBERS = """/teams/%s/members""" # GET_REPOS = """/teams/%s/repos""" # - def __init__(self, org: Organization, name: str, initJson: json = None): - """ Initializes Team. + def __init__(self, gitea, id: int): + super(Team, self).__init__(gitea, id=id) - Args: - org (Organization): Organization this team is part of. - name (str): Name of the Team. - initJson (dict): Optional, init information for Team. + fields_to_parsers = { + "organization": lambda gitea, o: Organization.parse_request(gitea, o) + } - Warning: - This does not create a Team. `gitea.create_team` does. - - Throws: - NotFoundException, if Team could not be found. - """ - self.gitea = org.gitea - self.__initialize_team(org, name, initJson) - - def __initialize_team(self, org, name, result): - """ Initializes Team. - - Args: - org (Organization): Organization this team is part of. - name (str): Name of the Team. - result (dict): Optional, init information for Team. - - Throws: - NotFoundException, if Team could not be found. - """ - if not result: - for team in org.get_teams(): - if team.name == name: - result = self.gitea.requests_get(Team.GET_TEAM % team.id) - logging.debug("Team found: %s/%s" % (org.username, name)) - if not result: - logging.warning("Failed to find Team: %s/%s" % (org.username, name)) - raise NotFoundException("Team could not be Found") - for i, v in result.items(): - setattr(self, i, v) - self.organization = org - - def __repr__(self): - """ Representation of a Team. Consisting of name and id. - """ - return "Team: %s/%s (%s)" % (self.organization.username, self.name, self.id) - - def __eq__(self, other): - if other is not None: - if isinstance(other, Team): - return other.id == self.id - return False + @classmethod + def request(cls, gitea, id): + return cls._request(gitea, {"id":id}) def add(self, toAdd): """ Adding User or Repository to Team. @@ -572,7 +489,6 @@ class Team: self.gitea.requests_delete(Team.TEAM_DELETE % self.id) - class Util: @staticmethod @@ -968,7 +884,7 @@ class Gitea: gitignores=None, license=None, readme="Default", - ) -> Repository: + ): """ Create a Repository. Args: @@ -1019,24 +935,8 @@ class Gitea: location="", website="", full_name="", - ) -> Organization: - """ Creates Organization. + ): - Args: - owner (User): The User that will own this Organization. - orgName (str): The name of the new Organization. - description (str): Short description of the Organization. - location (str): Optional, where the Organization is located. - website (str): Optional, a website of this Organization. - full_name (str): Optional, the full name of the Organization. - - Returns: Organization - The newly created Organization. - - Throws: - AlreadyExistsException, if this Organization already exists. - Exception, if something else went wrong. - """ assert isinstance(owner, User) result = self.requests_post( Gitea.CREATE_ORG % owner.username, @@ -1056,7 +956,7 @@ class Gitea: raise Exception( "Organization not created... (gitea: %s)" % result["message"] ) - return Organization(self, orgName, initJson=result) + return Organization.parse_request(self, result) def create_team( self, @@ -1073,7 +973,7 @@ class Gitea: "repo.releases", "repo.ext_wiki", ], - ) -> Team: + ): """ Creates a Team. Args: @@ -1097,4 +997,4 @@ class Gitea: logging.error("Team not created... (gitea: %s)" % result["message"]) logging.error(result["message"]) raise Exception("Team not created... (gitea: %s)" % result["message"]) - return Team(org, name, initJson=result) + return Team.parse_request(self, result) diff --git a/test_api.py b/test_api.py new file mode 100644 index 0000000..3fc77e3 --- /dev/null +++ b/test_api.py @@ -0,0 +1,122 @@ +import os + +import pytest +import uuid + +from .gitea import Gitea, User, Organization, Team, Repository, version +from .gitea import NotFoundException, AlreadyExistsException + +assert version >= "0.4.0" +gitea = None + +# put a ".token" file into your directory containg only the token for gitea +try: + gitea = Gitea("http://localhost:3000", open(".token", "r").read().strip()) + print("Gitea Version: " + gitea.get_version()) + print("API-Token belongs to user: " + gitea.get_user().username) +except: + assert ( + False + ), "Gitea could not load. \ + - Instance running at http://localhost:3000 \ + - Token at .token \ + ?" + +#make up some fresh names for the test run +test_org = "org_" + uuid.uuid4().hex[:8] +test_user = "user_" +uuid.uuid4().hex[:8] +test_team = "team_" +uuid.uuid4().hex[:8] # team names seem to have a rather low max lenght +test_repo = "repo_" +uuid.uuid4().hex[:8] + +def test_token_owner(): + assert gitea.get_user().username == "test", "Token user not 'test'." + +def test_gitea_version(): + assert gitea.get_version() == "1.8.0", "Version changed. Updated?" + +def test_fail_get_non_existent_user(): + with pytest.raises(NotFoundException) as e: + User.request(gitea, test_user) + +def test_fail_get_non_existent_org(): + with pytest.raises(NotFoundException) as e: + Organization.request(gitea, test_org) + +def test_fail_get_non_existent_repo(): + with pytest.raises(NotFoundException) as e: + Repository.request(gitea, test_user, test_repo) + +def test_create_user(): + email = test_user + "@example.org" + user = gitea.create_user(test_user, email, "abcdefg123") + user.update_mail() + assert user.username == test_user + assert user.login == test_user + assert user.email == email + assert not user.is_admin + +def test_create_org(): + user = gitea.get_user() + org = gitea.create_org(user, test_org, "some-desc", "loc") + assert org.get_members() == [user] + assert org.description == "some-desc" + assert org.username == test_org + assert org.location == "loc" + assert not org.website + assert not org.full_name + +def test_create_repo_userowned(): + org = User.request(gitea, test_user) + repo = gitea.create_repo(org, test_repo, "user owned repo") + assert repo.description == "user owned repo" + assert repo.owner == org + assert repo.name == test_repo + assert not repo.private + +def test_create_repo_orgowned(): + org = Organization.request(gitea, test_org) + repo = gitea.create_repo(org, test_repo, "descr") + assert repo.description == "descr" + assert repo.owner == org + assert repo.name == test_repo + assert not repo.private + +def test_create_team(): + org = Organization.request(gitea, test_org) + team = gitea.create_team(org, test_team, "descr") + assert team.name == test_team + assert team.description == "descr" + assert team.organization == org + +def test_delete_repo_userowned(): + org = User.request(gitea, test_user) + repo = Repository.request(gitea, org.username, test_repo) + repo.delete() + with pytest.raises(NotFoundException) as e: + Repository.request(gitea, test_user, test_repo) + +def test_delete_repo_orgowned(): + org = Organization.request(gitea, test_org) + repo = Repository.request(gitea, org.username, test_repo) + repo.delete() + with pytest.raises(NotFoundException) as e: + Repository.request(gitea, test_user, test_repo) + +def test_delete_team(): + org = Organization.request(gitea, test_org) + team = Team.request(org, test_team) + team.delete() + with pytest.raises(NotFoundException) as e: + Team(org, test_team) + +def test_delete_org(): + org = Organization.request(gitea, test_org) + org.delete() + with pytest.raises(NotFoundException) as e: + Organization.request(gitea, test_org) + +def test_delete_user(): + user = User.request(gitea, test_user) + user.delete() + with pytest.raises(NotFoundException) as e: + User.request(gitea, test_user) \ No newline at end of file diff --git a/tests.py b/tests.py deleted file mode 100644 index bf3c3a4..0000000 --- a/tests.py +++ /dev/null @@ -1,169 +0,0 @@ -import os - -from gitea import Gitea, User, Organization, Team, Repository, version -from gitea import NotFoundException, AlreadyExistsException - -assert version >= "0.4.0" - - -# Testing a localhost instance for API-functionality. -# - - -# testing includes: -# - reading in token -# - creation of organization -# - creation of repository -# - creation of team -# - creation of user -# - assigning team to repository -# - assigning user to team -# - deleting created user -# - deleting repository -# - deleting team -# - deleting organization - - -def expect_not_exist(fn, expect) -> bool: - try: - fn() - return False - except expect: - return True - - -gitea = None - -# put a ".token" file into your directory containg only the token for gitea -try: - gitea = Gitea("http://localhost:3000", open(".token", "r").read().strip()) - print("Gitea Version: " + gitea.get_version()) - print("API-Token belongs to user: " + gitea.get_user().username) -except: - assert ( - False - ), "Gitea could not load. \ - - Instance running at http://localhost:3000 \ - - Token at .token \ - ?" - - -def test_token(): - assert gitea.get_user().username == "test", "Token user not 'test'." - - -def test_version(): - assert gitea.get_version() == "1.8.0-rc2", "Version changed. Updated?" - - -def test_before_user(): - # This should not work currently - assert expect_not_exist( - lambda: User(gitea, "test-user"), (NotFoundException) - ), "User test-user should not exist" - - -def test_before_org(): - assert expect_not_exist( - lambda: Organization(gitea, "test-org"), (NotFoundException) - ), "Organization test-org should not exist" - - -def test_before_repo(): - assert expect_not_exist( - lambda: Repository(gitea, User(gitea, "test-user"), "test-repo"), - (NotFoundException), - ), "Repository test-repo should not exist" - - -def test_before_team(): - assert expect_not_exist( - lambda: Team(gitea, Organization(gitea, "test-org"), "test-team"), - (NotFoundException), - ), "Team test-team should not exist" - - -def test_create_user(): - user = gitea.create_user("test-user", "testmail@example.org", "pw1234") - user.update_mail() - assert user.username == "test-user" - assert user.login == "test-user" - assert user.email == "testmail@example.org" - assert not user.is_admin - - -def test_create_org(): - user = gitea.get_user() - org = gitea.create_org(user, "test-org", "some-desc", "loc") - assert org.get_members() == [user] - assert org.description == "some-desc" - assert org.username == "test-org" - assert org.location == "loc" - assert not org.website - assert not org.full_name - - -def test_create_repo(): - org = Organization(gitea, "test-org") - repo = gitea.create_repo(org, "test-repo", "descr") - assert repo.description == "descr" - assert repo.owner == org - assert repo.name == "test-repo" - assert not repo.private - - -def test_create_team(): - org = Organization(gitea, "test-org") - team = gitea.create_team(org, "test-team", "descr") - assert team.name == "test-team" - assert team.description == "descr" - assert team.organization == org - - -def test_full(): - user = User(gitea, "test-user") - user.update_mail() - org = Organization(gitea, "test-org") - team = Team(org, "test-team") - assert team.get_members() == [] - team.add(user) - assert team.get_members() == [user] - repo = Repository(gitea, org, "test-repo") - assert team.get_repos() == [] - team.add(repo) - assert team.get_repos() == [repo] - - -def test_delete_repo(): - org = Organization(gitea, "test-org") - repo = Repository(gitea, org, "test-repo") - repo.delete() - assert expect_not_exist( - lambda: Repository(gitea, User(gitea, "test-user"), "test-repo"), - (NotFoundException), - ), "Repository test-repo should not exist" - - -def test_delete_team(): - org = Organization(gitea, "test-org") - team = Team(org, "test-team") - team.delete() - assert expect_not_exist( - lambda: Team(org, "test-team"), (NotFoundException) - ), "Team test-team should not exist" - - -def test_delete_org(): - org = Organization(gitea, "test-org") - org.delete() - assert expect_not_exist( - lambda: Organization(gitea, "test-org"), (NotFoundException) - ), "Organization test-org should not exist" - - -def test_delete_user(): - user = User(gitea, "test-user") - user.delete() - assert expect_not_exist( - lambda: User(gitea, "test-user"), (NotFoundException) - ), "User test-user should not exist"