Skip to content

Commit 7490ddf

Browse files
authored
Unit test for token usage (#107)
1 parent ba41e4b commit 7490ddf

14 files changed

+371
-129
lines changed

.github/workflows/tests.yml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,23 @@ jobs:
5151

5252
- name: Show out.csv
5353
run: cat out.csv
54+
55+
token-usage-unit_test:
56+
57+
runs-on: ubuntu-latest
58+
steps:
59+
- uses: actions/checkout@v4
60+
61+
- name: Cache pip
62+
uses: actions/cache@v3
63+
with:
64+
path: ~/.cache/pip
65+
key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}
66+
restore-keys: |
67+
${{ runner.os }}-pip-
68+
69+
- name: Install dependencies
70+
run: pip install -r requirements.txt
71+
72+
- name: Run test
73+
run: python3 test_token_usage.py --tt1 ${{ secrets.TEST_TOKEN_GITHUB }} --tt2 ${{ secrets.SECOND_TEST_TOKEN_GITHUB }} --repo moevm/github_repo_commitment_calc --out out.csv

ForgejoRepoAPI.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,20 @@
44
import isodate
55
from pyforgejo import PyforgejoApi
66

7-
from interface_wrapper import (Branch, Comment, Commit, Contributor, Invite,
8-
IRepositoryAPI, Issue, PullRequest, Repository,
9-
User, WikiPage, logging)
7+
from interface_wrapper import (
8+
Branch,
9+
Comment,
10+
Commit,
11+
Contributor,
12+
Invite,
13+
IRepositoryAPI,
14+
Issue,
15+
PullRequest,
16+
Repository,
17+
User,
18+
WikiPage,
19+
logging,
20+
)
1021

1122

1223
class ForgejoRepoAPI(IRepositoryAPI):

GitHubRepoAPI.py

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,37 @@
1-
from interface_wrapper import (Branch, Comment, Commit, Contributor, Invite,
2-
IRepositoryAPI, Issue, PullRequest, Repository,
3-
User, WikiPage, logging)
1+
from interface_wrapper import (
2+
Branch,
3+
Comment,
4+
Commit,
5+
Contributor,
6+
Invite,
7+
IRepositoryAPI,
8+
Issue,
9+
PullRequest,
10+
Repository,
11+
User,
12+
WikiPage,
13+
logging,
14+
)
15+
16+
from github import Github, GithubException
417

518

619
class GitHubRepoAPI(IRepositoryAPI):
20+
def __init__(self, client: Github):
21+
self.client = self._client_validation(client)
722

8-
def __init__(self, client):
9-
self.client = client
23+
@staticmethod
24+
def _client_validation(client: Github) -> Github:
25+
try:
26+
client.get_user().login
27+
except GithubException as err:
28+
logging.error(f'Github: Connect: error {err.data}')
29+
logging.error(
30+
'Github: Connect: user could not be authenticated please try again.'
31+
)
32+
exit(1)
33+
else:
34+
return client
1035

1136
def get_user_data(self, user) -> User:
1237
return User(

commits_parser.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from dataclasses import asdict, dataclass
22
from time import sleep
3+
from typing import Generator
4+
from datetime import datetime
35

46
import pytz
57

@@ -62,12 +64,17 @@ def log_repository_commits(
6264

6365

6466
def log_commits(
65-
client: IRepositoryAPI, working_repos, csv_name, start, finish, branch, fork_flag
67+
binded_repos: Generator[tuple[IRepositoryAPI, Repository, str], None, None],
68+
csv_name: str,
69+
start: datetime,
70+
finish: datetime,
71+
branch: str,
72+
fork_flag: bool,
6673
):
6774
info = asdict(CommitData())
6875
logger.log_to_csv(csv_name, list(info.keys()))
6976

70-
for repo, token in working_repos:
77+
for client, repo, token in binded_repos:
7178
try:
7279
logger.log_title(repo.name)
7380
log_repository_commits(client, repo, csv_name, start, finish, branch)

contributors_parser.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,12 +80,14 @@ def get_contributors_stats(client: IRepositoryAPI, repository: Repository) -> di
8080

8181

8282
def log_contributors(
83-
client: IRepositoryAPI, working_repos: Generator, csv_name: str, fork_flag: bool
83+
binded_repos: Generator[tuple[IRepositoryAPI, Repository, str], None, None],
84+
csv_name: str,
85+
fork_flag: bool,
8486
):
8587
info = asdict(ContributorData())
8688
logger.log_to_csv(csv_name, list(info.keys()))
8789

88-
for repo, token in working_repos:
90+
for client, repo, token in binded_repos:
8991
try:
9092
logger.log_title(repo.name)
9193
log_repository_contributors(client, repo, csv_name)

git_logger.py

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,22 +16,40 @@ def get_tokens_from_file(tokens_path: str) -> list[str]:
1616
return tokens
1717

1818

19-
class GitClients:
19+
def get_repos_from_file(repos_path: str) -> list[str]:
20+
with open(repos_path, 'r') as file:
21+
list_repos = [x for x in file.read().split('\n') if x]
22+
23+
return list_repos
24+
25+
26+
class Clients:
2027
def __init__(self, source: str, tokens: list[str], base_url: str | None = None):
21-
self.clients = self._init_clients(source, tokens, base_url)
22-
self.cur_client = None
28+
# Возможно это можно переписать покрасивее
29+
if source == 'github':
30+
self.clients = self._init_clients(source, tokens, base_url)
31+
elif base_url == 'forgejo':
32+
self.client = RepositoryFactory.create_api(source, tokens[0], base_url)
33+
self.token = tokens[0]
34+
else:
35+
print(f"Unavailable source {source}, use [ 'github' | 'forgejo' ] instead")
36+
37+
self.source = source
2338

2439
def _init_clients(
2540
self, source: str, tokens: list[str], base_url: str | None
2641
) -> list[dict]:
2742
clients = [
28-
{"client": login(source, token, base_url), "token": token}
43+
{
44+
"client": RepositoryFactory.create_api(source, token, base_url),
45+
"token": token,
46+
}
2947
for token in tokens
3048
]
3149

3250
return clients
3351

34-
def get_next_client(self) -> IRepositoryAPI:
52+
def _get_next_git_client(self) -> tuple[IRepositoryAPI, str]:
3553
client = None
3654
max_remaining_limit = -1
3755

@@ -51,24 +69,29 @@ def get_next_client(self) -> IRepositoryAPI:
5169
if client is None:
5270
raise Exception("No git clients available")
5371

54-
self.cur_client = client
55-
return client
72+
return client['client'], client['token']
5673

74+
def _get_next_forgejo_client(self) -> tuple[IRepositoryAPI, str]:
75+
return self.client, self.token
5776

58-
def get_next_repo(clients: GitClients, repositories):
59-
with open(repositories, 'r') as file:
60-
list_repos = [x for x in file.read().split('\n') if x]
61-
print(list_repos)
62-
for repo_name in list_repos:
77+
def get_next_client(self) -> tuple[IRepositoryAPI, str]:
78+
if self.source == 'github':
79+
return self._get_next_git_client()
80+
elif self.source == 'forgejo':
81+
return self._get_next_forgejo_client
82+
83+
84+
def get_next_binded_repo(clients: Clients, repositories: list[str]):
85+
for repo_name in repositories:
6386
try:
64-
cur_client = clients.get_next_client()
65-
repo = cur_client['client'].get_repository(repo_name)
87+
client, token = clients.get_next_client()
88+
repo = client.get_repository(repo_name)
6689
except Exception as err:
6790
print(f'get_next_repo(): error {err}')
6891
print(f'get_next_repo(): failed to load repository "{repo_name}"')
6992
exit(1)
7093
else:
71-
yield repo, cur_client['token']
94+
yield client, repo, token
7295

7396

7497
def get_assignee_story(git_object):

interface_wrapper.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from dataclasses import dataclass
44
from datetime import datetime
55

6-
from github import Github
6+
from github import Github, Auth
77
from pyforgejo import PyforgejoApi
88

99
# Настройка логирования
@@ -182,7 +182,7 @@ def create_api(
182182
from GitHubRepoAPI import GitHubRepoAPI
183183

184184
if source == 'github':
185-
return GitHubRepoAPI(Github(token))
185+
return GitHubRepoAPI(Github(auth=Auth.Token(token)))
186186
elif source == 'forgejo':
187187
if not isinstance(base_url, str):
188188
raise ValueError(

invites_parser.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from dataclasses import asdict, dataclass
22
from time import sleep
3+
from typing import Generator
34

45
from constants import TIMEDELTA
56
from interface_wrapper import IRepositoryAPI, Repository
@@ -31,11 +32,14 @@ def log_repository_invitations(
3132
sleep(TIMEDELTA)
3233

3334

34-
def log_invitations(client: IRepositoryAPI, working_repos, csv_name: str):
35+
def log_invitations(
36+
binded_repos: Generator[tuple[IRepositoryAPI, Repository, str], None, None],
37+
csv_name: str,
38+
):
3539
info = asdict(InviteData())
3640
logger.log_to_csv(csv_name, list(info.keys()))
3741

38-
for repo, token in working_repos:
42+
for client, repo, token in binded_repos:
3943
logger.log_title(repo.name)
4044
try:
4145
log_repository_invitations(client, repo, csv_name)

issues_parser.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import json
22
from dataclasses import asdict, dataclass
33
from time import sleep
4+
from typing import Generator
5+
from datetime import datetime
46

57
import pytz
68
import requests
@@ -187,12 +189,16 @@ def log_issue_and_comments(csv_name, issue_data: IssueData, comments):
187189

188190

189191
def log_issues(
190-
client: IRepositoryAPI, working_repo, csv_name, token, start, finish, fork_flag
192+
binded_repos: Generator[tuple[IRepositoryAPI, Repository, str], None, None],
193+
csv_name: str,
194+
start: datetime,
195+
finish: datetime,
196+
fork_flag: bool,
191197
):
192198
info = asdict(IssueDataWithComment())
193199
logger.log_to_csv(csv_name, list(info.keys()))
194200

195-
for repo, token in working_repo:
201+
for client, repo, token in binded_repos:
196202
try:
197203
logger.log_title(repo.name)
198204
log_repository_issues(client, repo, csv_name, token, start, finish)

0 commit comments

Comments
 (0)