Skip to content

Commit

Permalink
annofabapi.resources.build関数の修正 (#622)
Browse files Browse the repository at this point in the history
* build関数でValueErrorのメッセージを入れる

* テストコードを追加

* CredentialsNotFoundError エラーの作成
  • Loading branch information
yuji38kwmt authored Jan 16, 2024
1 parent 24336bf commit b83b54d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 19 deletions.
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
32 changes: 16 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 @@ -63,18 +63,13 @@ def build(
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 +82,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 +115,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

0 comments on commit b83b54d

Please sign in to comment.