Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify build2 #623

Merged
merged 4 commits into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions annofabapi/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ class AnnofabApiException(Exception):
"""


class CredentialsNotFoundError(AnnofabApiException):
"""
Annofabの認証情報が見つからないときのエラー
"""


class AnnotationOuterFileNotFoundError(AnnofabApiException):
"""
アノテーション情報の外部ファイル(塗りつぶしの画像ファイルなど)が、存在しない場合のエラー
Expand Down
35 changes: 19 additions & 16 deletions annofabapi/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from annofabapi import AnnofabApi, AnnofabApi2, Wrapper
from annofabapi.api import DEFAULT_ENDPOINT_URL
from annofabapi.exceptions import AnnofabApiException
from annofabapi.exceptions import CredentialsNotFoundError

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -56,25 +56,23 @@ def build(
Returns:
AnnofabApi, Wrapperのインスタンスを保持するインスタンス

Raises:
CredentialsNotFoundError: `.netrc`ファイルまたは環境変数にAnnofabの認証情報がなかった

"""
if login_user_id is not None and login_password is not None:
return Resource(login_user_id, login_password, endpoint_url=endpoint_url)

elif login_user_id is None and login_password is None:
try:
return build_from_env(endpoint_url)
except AnnofabApiException:
pass

try:
return build_from_netrc(endpoint_url)
except AnnofabApiException:
pass

raise AnnofabApiException("環境変数または`.netrc`ファイルにAnnofab認証情報はありませんでした。")

except CredentialsNotFoundError:
try:
return build_from_netrc(endpoint_url)
except CredentialsNotFoundError as e:
raise CredentialsNotFoundError("環境変数または`.netrc`ファイルにAnnofab認証情報はありませんでした。") from e
else:
raise ValueError()
raise ValueError("引数`login_user_id`か`login_password`のどちらか一方がNoneです。両方Noneでないか、両方Noneである必要があります。")


def build_from_netrc(endpoint_url: str = DEFAULT_ENDPOINT_URL) -> Resource:
Expand All @@ -87,22 +85,25 @@ def build_from_netrc(endpoint_url: str = DEFAULT_ENDPOINT_URL) -> Resource:
Returns:
annofabapi.Resourceインスタンス

Raises:
CredentialsNotFoundError: `.netrc`ファイルにAnnofabの認証情報がなかった

"""
try:
netrc_hosts = netrc.netrc().hosts
except FileNotFoundError as e:
raise AnnofabApiException(e) from e
raise CredentialsNotFoundError("`.netrc`ファイルは見つかりません。") from e

annofab_hostname = (urlparse(endpoint_url)).hostname

if annofab_hostname not in netrc_hosts:
raise AnnofabApiException(f"The `.netrc` file does not contain the machine name '{annofab_hostname}'")
raise CredentialsNotFoundError(f"The `.netrc` file does not contain the machine name '{annofab_hostname}'")

host = netrc_hosts[annofab_hostname]
login_user_id = host[0]
login_password = host[2]
if login_user_id is None or login_password is None:
raise AnnofabApiException("User ID or password in the .netrc file are None.")
raise CredentialsNotFoundError("User ID or password in the .netrc file are None.")

return Resource(login_user_id, login_password, endpoint_url=endpoint_url)

Expand All @@ -117,10 +118,12 @@ def build_from_env(endpoint_url: str = DEFAULT_ENDPOINT_URL) -> Resource:
Returns:
annofabapi.Resourceインスタンス

Raises:
CredentialsNotFoundError: 環境変数にAnnofabの認証情報がなかった
"""
login_user_id = os.environ.get("ANNOFAB_USER_ID")
login_password = os.environ.get("ANNOFAB_PASSWORD")
if login_user_id is None or login_password is None:
raise AnnofabApiException("`ANNOFAB_USER_ID` or `ANNOFAB_PASSWORD` environment variable are empty.")
raise CredentialsNotFoundError("`ANNOFAB_USER_ID` or `ANNOFAB_PASSWORD` environment variable are empty.")

return Resource(login_user_id, login_password, endpoint_url=endpoint_url)
14 changes: 11 additions & 3 deletions tests/test_local_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ def test_raise_ValueError(self):
with pytest.raises(ValueError):
annofabapi.AnnofabApi("test_user", "")

def test_build_from_env_raise_AnnofabApiException(self):
with pytest.raises(annofabapi.exceptions.AnnofabApiException):
def test_build_from_env_raise_CredentialsNotFoundError(self):
with pytest.raises(annofabapi.exceptions.CredentialsNotFoundError):
os.environ.pop("ANNOFAB_USER_ID", None)
os.environ.pop("ANNOFAB_PASSWORD", None)
build_from_env()
Expand All @@ -33,9 +33,17 @@ def test_build_from_env(self):
assert isinstance(build_from_env(), annofabapi.Resource)

def test_build(self):
assert isinstance(build(login_user_id="FOO", login_password="BAR"), annofabapi.Resource)

with pytest.raises(ValueError):
build(login_user_id="FOO", login_password=None)

with pytest.raises(ValueError):
build(login_user_id=None, login_password="BAR")

os.environ["ANNOFAB_USER_ID"] = "FOO"
os.environ["ANNOFAB_PASSWORD"] = "BAR"
assert isinstance(build(), annofabapi.Resource)
assert isinstance(build(login_user_id=None, login_password=None), annofabapi.Resource)

def test_build_with_endpoint(self):
user_id = "test_user"
Expand Down