Close API client on exit

This commit is contained in:
Ivan Kravets
2023-07-31 19:09:32 +03:00
parent 30fad62d05
commit 527e7f16f6
38 changed files with 160 additions and 153 deletions

View File

@ -19,18 +19,18 @@ from platformio.account.client import AccountClient, AccountNotAuthorized
@click.command("destroy", short_help="Destroy account") @click.command("destroy", short_help="Destroy account")
def account_destroy_cmd(): def account_destroy_cmd():
client = AccountClient() with AccountClient() as client:
click.confirm( click.confirm(
"Are you sure you want to delete the %s user account?\n" "Are you sure you want to delete the %s user account?\n"
"Warning! All linked data will be permanently removed and can not be restored." "Warning! All linked data will be permanently removed and can not be restored."
% client.get_logged_username(), % client.get_logged_username(),
abort=True, abort=True,
) )
client.destroy_account() client.destroy_account()
try: try:
client.logout() client.logout()
except AccountNotAuthorized: except AccountNotAuthorized:
pass pass
click.secho( click.secho(
"User account has been destroyed.", "User account has been destroyed.",
fg="green", fg="green",

View File

@ -20,8 +20,8 @@ from platformio.account.client import AccountClient
@click.command("forgot", short_help="Forgot password") @click.command("forgot", short_help="Forgot password")
@click.option("--username", prompt="Username or email") @click.option("--username", prompt="Username or email")
def account_forgot_cmd(username): def account_forgot_cmd(username):
client = AccountClient() with AccountClient() as client:
client.forgot_password(username) client.forgot_password(username)
click.secho( click.secho(
"If this account is registered, we will send the " "If this account is registered, we will send the "
"further instructions to your email.", "further instructions to your email.",

View File

@ -21,6 +21,6 @@ from platformio.account.client import AccountClient
@click.option("-u", "--username", prompt="Username or email") @click.option("-u", "--username", prompt="Username or email")
@click.option("-p", "--password", prompt=True, hide_input=True) @click.option("-p", "--password", prompt=True, hide_input=True)
def account_login_cmd(username, password): def account_login_cmd(username, password):
client = AccountClient() with AccountClient() as client:
client.login(username, password) client.login(username, password)
click.secho("Successfully logged in!", fg="green") click.secho("Successfully logged in!", fg="green")

View File

@ -19,6 +19,6 @@ from platformio.account.client import AccountClient
@click.command("logout", short_help="Log out of PlatformIO Account") @click.command("logout", short_help="Log out of PlatformIO Account")
def account_logout_cmd(): def account_logout_cmd():
client = AccountClient() with AccountClient() as client:
client.logout() client.logout()
click.secho("Successfully logged out!", fg="green") click.secho("Successfully logged out!", fg="green")

View File

@ -21,6 +21,6 @@ from platformio.account.client import AccountClient
@click.option("--old-password", prompt=True, hide_input=True) @click.option("--old-password", prompt=True, hide_input=True)
@click.option("--new-password", prompt=True, hide_input=True, confirmation_prompt=True) @click.option("--new-password", prompt=True, hide_input=True, confirmation_prompt=True)
def account_password_cmd(old_password, new_password): def account_password_cmd(old_password, new_password):
client = AccountClient() with AccountClient() as client:
client.change_password(old_password, new_password) client.change_password(old_password, new_password)
click.secho("Password successfully changed!", fg="green") click.secho("Password successfully changed!", fg="green")

View File

@ -43,8 +43,8 @@ from platformio.account.validate import (
@click.option("--firstname", prompt=True) @click.option("--firstname", prompt=True)
@click.option("--lastname", prompt=True) @click.option("--lastname", prompt=True)
def account_register_cmd(username, email, password, firstname, lastname): def account_register_cmd(username, email, password, firstname, lastname):
client = AccountClient() with AccountClient() as client:
client.registration(username, email, password, firstname, lastname) client.registration(username, email, password, firstname, lastname)
click.secho( click.secho(
"An account has been successfully created. " "An account has been successfully created. "
"Please check your mail to activate your account and verify your email address.", "Please check your mail to activate your account and verify your email address.",

View File

@ -25,8 +25,8 @@ from platformio.account.client import AccountClient
@click.option("--offline", is_flag=True) @click.option("--offline", is_flag=True)
@click.option("--json-output", is_flag=True) @click.option("--json-output", is_flag=True)
def account_show_cmd(offline, json_output): def account_show_cmd(offline, json_output):
client = AccountClient() with AccountClient() as client:
info = client.get_account_info(offline) info = client.get_account_info(offline)
if json_output: if json_output:
click.echo(json.dumps(info)) click.echo(json.dumps(info))
return return

View File

@ -24,8 +24,8 @@ from platformio.account.client import AccountClient
@click.option("--regenerate", is_flag=True) @click.option("--regenerate", is_flag=True)
@click.option("--json-output", is_flag=True) @click.option("--json-output", is_flag=True)
def account_token_cmd(password, regenerate, json_output): def account_token_cmd(password, regenerate, json_output):
client = AccountClient() with AccountClient() as client:
auth_token = client.auth_token(password, regenerate) auth_token = client.auth_token(password, regenerate)
if json_output: if json_output:
click.echo(json.dumps({"status": "success", "result": auth_token})) click.echo(json.dumps({"status": "success", "result": auth_token}))
return return

View File

@ -25,8 +25,8 @@ from platformio.account.validate import validate_email, validate_username
@click.option("--firstname") @click.option("--firstname")
@click.option("--lastname") @click.option("--lastname")
def account_update_cmd(current_password, **kwargs): def account_update_cmd(current_password, **kwargs):
client = AccountClient() with AccountClient() as client:
profile = client.get_profile() profile = client.get_profile()
new_profile = profile.copy() new_profile = profile.copy()
if not any(kwargs.values()): if not any(kwargs.values()):
for field in profile: for field in profile:

View File

@ -25,8 +25,8 @@ from platformio.account.client import AccountClient
"username", "username",
) )
def org_add_cmd(orgname, username): def org_add_cmd(orgname, username):
client = AccountClient() with AccountClient() as client:
client.add_org_owner(orgname, username) client.add_org_owner(orgname, username)
return click.secho( return click.secho(
"The new owner `%s` has been successfully added to the `%s` organization." "The new owner `%s` has been successfully added to the `%s` organization."
% (username, orgname), % (username, orgname),

View File

@ -30,8 +30,8 @@ from platformio.account.validate import validate_email, validate_orgname
"--displayname", "--displayname",
) )
def org_create_cmd(orgname, email, displayname): def org_create_cmd(orgname, email, displayname):
client = AccountClient() with AccountClient() as client:
client.create_org(orgname, email, displayname) client.create_org(orgname, email, displayname)
return click.secho( return click.secho(
"The organization `%s` has been successfully created." % orgname, "The organization `%s` has been successfully created." % orgname,
fg="green", fg="green",

View File

@ -20,14 +20,14 @@ from platformio.account.client import AccountClient
@click.command("destroy", short_help="Destroy organization") @click.command("destroy", short_help="Destroy organization")
@click.argument("orgname") @click.argument("orgname")
def org_destroy_cmd(orgname): def org_destroy_cmd(orgname):
client = AccountClient() with AccountClient() as client:
click.confirm( click.confirm(
"Are you sure you want to delete the `%s` organization account?\n" "Are you sure you want to delete the `%s` organization account?\n"
"Warning! All linked data will be permanently removed and can not be restored." "Warning! All linked data will be permanently removed and can not be restored."
% orgname, % orgname,
abort=True, abort=True,
) )
client.destroy_org(orgname) client.destroy_org(orgname)
return click.secho( return click.secho(
"Organization `%s` has been destroyed." % orgname, "Organization `%s` has been destroyed." % orgname,
fg="green", fg="green",

View File

@ -23,8 +23,8 @@ from platformio.account.client import AccountClient
@click.command("list", short_help="List organizations and their members") @click.command("list", short_help="List organizations and their members")
@click.option("--json-output", is_flag=True) @click.option("--json-output", is_flag=True)
def org_list_cmd(json_output): def org_list_cmd(json_output):
client = AccountClient() with AccountClient() as client:
orgs = client.list_orgs() orgs = client.list_orgs()
if json_output: if json_output:
return click.echo(json.dumps(orgs)) return click.echo(json.dumps(orgs))
if not orgs: if not orgs:

View File

@ -25,8 +25,8 @@ from platformio.account.client import AccountClient
"username", "username",
) )
def org_remove_cmd(orgname, username): def org_remove_cmd(orgname, username):
client = AccountClient() with AccountClient() as client:
client.remove_org_owner(orgname, username) client.remove_org_owner(orgname, username)
return click.secho( return click.secho(
"The `%s` owner has been successfully removed from the `%s` organization." "The `%s` owner has been successfully removed from the `%s` organization."
% (username, orgname), % (username, orgname),

View File

@ -31,8 +31,8 @@ from platformio.account.validate import validate_email, validate_orgname
) )
@click.option("--displayname") @click.option("--displayname")
def org_update_cmd(cur_orgname, **kwargs): def org_update_cmd(cur_orgname, **kwargs):
client = AccountClient() with AccountClient() as client:
org = client.get_org(cur_orgname) org = client.get_org(cur_orgname)
new_org = { new_org = {
key: value if value is not None else org[key] for key, value in kwargs.items() key: value if value is not None else org[key] for key, value in kwargs.items()
} }

View File

@ -29,8 +29,8 @@ from platformio.account.validate import validate_orgname_teamname
) )
def team_add_cmd(orgname_teamname, username): def team_add_cmd(orgname_teamname, username):
orgname, teamname = orgname_teamname.split(":", 1) orgname, teamname = orgname_teamname.split(":", 1)
client = AccountClient() with AccountClient() as client:
client.add_team_member(orgname, teamname, username) client.add_team_member(orgname, teamname, username)
return click.secho( return click.secho(
"The new member %s has been successfully added to the %s team." "The new member %s has been successfully added to the %s team."
% (username, teamname), % (username, teamname),

View File

@ -29,8 +29,8 @@ from platformio.account.validate import validate_orgname_teamname
) )
def team_create_cmd(orgname_teamname, description): def team_create_cmd(orgname_teamname, description):
orgname, teamname = orgname_teamname.split(":", 1) orgname, teamname = orgname_teamname.split(":", 1)
client = AccountClient() with AccountClient() as client:
client.create_team(orgname, teamname, description) client.create_team(orgname, teamname, description)
return click.secho( return click.secho(
"The team %s has been successfully created." % teamname, "The team %s has been successfully created." % teamname,
fg="green", fg="green",

View File

@ -32,8 +32,8 @@ def team_destroy_cmd(orgname_teamname):
), ),
abort=True, abort=True,
) )
client = AccountClient() with AccountClient() as client:
client.destroy_team(orgname, teamname) client.destroy_team(orgname, teamname)
return click.secho( return click.secho(
"The team %s has been successfully destroyed." % teamname, "The team %s has been successfully destroyed." % teamname,
fg="green", fg="green",

View File

@ -24,19 +24,22 @@ from platformio.account.client import AccountClient
@click.argument("orgname", required=False) @click.argument("orgname", required=False)
@click.option("--json-output", is_flag=True) @click.option("--json-output", is_flag=True)
def team_list_cmd(orgname, json_output): def team_list_cmd(orgname, json_output):
client = AccountClient() with AccountClient() as client:
data = {} data = {}
if not orgname: if not orgname:
for item in client.list_orgs(): for item in client.list_orgs():
teams = client.list_teams(item.get("orgname")) teams = client.list_teams(item.get("orgname"))
data[item.get("orgname")] = teams data[item.get("orgname")] = teams
else: else:
teams = client.list_teams(orgname) teams = client.list_teams(orgname)
data[orgname] = teams data[orgname] = teams
if json_output: if json_output:
return click.echo(json.dumps(data[orgname] if orgname else data)) return click.echo(json.dumps(data[orgname] if orgname else data))
if not any(data.values()): if not any(data.values()):
return click.secho("You do not have any teams.", fg="yellow") return click.secho("You do not have any teams.", fg="yellow")
for org_name, teams in data.items(): for org_name, teams in data.items():
for team in teams: for team in teams:
click.echo() click.echo()

View File

@ -27,8 +27,8 @@ from platformio.account.validate import validate_orgname_teamname
@click.argument("username") @click.argument("username")
def team_remove_cmd(orgname_teamname, username): def team_remove_cmd(orgname_teamname, username):
orgname, teamname = orgname_teamname.split(":", 1) orgname, teamname = orgname_teamname.split(":", 1)
client = AccountClient() with AccountClient() as client:
client.remove_team_member(orgname, teamname, username) client.remove_team_member(orgname, teamname, username)
return click.secho( return click.secho(
"The %s member has been successfully removed from the %s team." "The %s member has been successfully removed from the %s team."
% (username, teamname), % (username, teamname),

View File

@ -34,8 +34,8 @@ from platformio.account.validate import validate_orgname_teamname, validate_team
) )
def team_update_cmd(orgname_teamname, **kwargs): def team_update_cmd(orgname_teamname, **kwargs):
orgname, teamname = orgname_teamname.split(":", 1) orgname, teamname = orgname_teamname.split(":", 1)
client = AccountClient() with AccountClient() as client:
team = client.get_team(orgname, teamname) team = client.get_team(orgname, teamname)
new_team = { new_team = {
key: value if value is not None else team[key] for key, value in kwargs.items() key: value if value is not None else team[key] for key, value in kwargs.items()
} }

View File

@ -21,4 +21,5 @@ class AccountRPC(BaseRPCHandler):
@staticmethod @staticmethod
def call_client(method, *args, **kwargs): def call_client(method, *args, **kwargs):
return getattr(AccountClient(), method)(*args, **kwargs) with AccountClient() as client:
return getattr(client, method)(*args, **kwargs)

View File

@ -29,8 +29,6 @@ from platformio.http import HTTPSession, ensure_internet_on
class OSRPC(BaseRPCHandler): class OSRPC(BaseRPCHandler):
NAMESPACE = "os" NAMESPACE = "os"
_http_session = None
@classmethod @classmethod
def fetch_content(cls, url, data=None, headers=None, cache_valid=None): def fetch_content(cls, url, data=None, headers=None, cache_valid=None):
if not headers: if not headers:
@ -44,27 +42,25 @@ class OSRPC(BaseRPCHandler):
cache_key = ContentCache.key_from_args(url, data) if cache_valid else None cache_key = ContentCache.key_from_args(url, data) if cache_valid else None
with ContentCache() as cc: with ContentCache() as cc:
if cache_key: if cache_key:
result = cc.get(cache_key) content = cc.get(cache_key)
if result is not None: if content is not None:
return result return content
# check internet before and resolve issue with 60 seconds timeout # check internet before and resolve issue with 60 seconds timeout
ensure_internet_on(raise_exception=True) ensure_internet_on(raise_exception=True)
if not cls._http_session: with HTTPSession() as session:
cls._http_session = HTTPSession() if data:
response = session.post(url, data=data, headers=headers)
else:
response = session.get(url, headers=headers)
if data: response.raise_for_status()
r = cls._http_session.post(url, data=data, headers=headers) content = response.text
else: if cache_valid:
r = cls._http_session.get(url, headers=headers) with ContentCache() as cc:
cc.set(cache_key, content, cache_valid)
r.raise_for_status() return content
result = r.text
if cache_valid:
with ContentCache() as cc:
cc.set(cache_key, result, cache_valid)
return result
@classmethod @classmethod
def request_content(cls, uri, data=None, headers=None, cache_valid=None): def request_content(cls, uri, data=None, headers=None, cache_valid=None):

View File

@ -21,4 +21,5 @@ class RegistryRPC(BaseRPCHandler):
@staticmethod @staticmethod
def call_client(method, *args, **kwargs): def call_client(method, *args, **kwargs):
return getattr(RegistryClient(), method)(*args, **kwargs) with RegistryClient() as client:
return getattr(client, method)(*args, **kwargs)

View File

@ -87,7 +87,8 @@ def package_publish_cmd( # pylint: disable=too-many-arguments, too-many-locals
): ):
click.secho("Preparing a package...", fg="cyan") click.secho("Preparing a package...", fg="cyan")
no_interactive = no_interactive or non_interactive no_interactive = no_interactive or non_interactive
owner = owner or AccountClient().get_logged_username() with AccountClient() as client:
owner = owner or client.get_logged_username()
do_not_pack = ( do_not_pack = (
not os.path.isdir(package) not os.path.isdir(package)
and isinstance(FileUnpacker.new_archiver(package), TARArchiver) and isinstance(FileUnpacker.new_archiver(package), TARArchiver)
@ -145,9 +146,10 @@ def package_publish_cmd( # pylint: disable=too-many-arguments, too-many-locals
fg="yellow", fg="yellow",
) )
click.echo("Publishing...") click.echo("Publishing...")
response = RegistryClient().publish_package( with RegistryClient() as client:
owner, typex, archive_path, released_at, private, notify response = client.publish_package(
) owner, typex, archive_path, released_at, private, notify
)
if not do_not_pack: if not do_not_pack:
os.remove(archive_path) os.remove(archive_path)
click.secho(response.get("message"), fg="green") click.secho(response.get("message"), fg="green")

View File

@ -29,8 +29,8 @@ from platformio.registry.client import RegistryClient
type=click.Choice(["relevance", "popularity", "trending", "added", "updated"]), type=click.Choice(["relevance", "popularity", "trending", "added", "updated"]),
) )
def package_search_cmd(query, page, sort): def package_search_cmd(query, page, sort):
client = RegistryClient() with RegistryClient() as client:
result = client.list_packages(query, page=page, sort=sort) result = client.list_packages(query, page=page, sort=sort)
if not result["total"]: if not result["total"]:
click.secho("Nothing has been found by your request", fg="yellow") click.secho("Nothing has been found by your request", fg="yellow")
click.echo( click.echo(

View File

@ -124,31 +124,31 @@ def package_show_cmd(spec, pkg_type):
def fetch_package_data(spec, pkg_type=None): def fetch_package_data(spec, pkg_type=None):
assert isinstance(spec, PackageSpec) assert isinstance(spec, PackageSpec)
client = RegistryClient() with RegistryClient() as client:
if pkg_type and spec.owner and spec.name: if pkg_type and spec.owner and spec.name:
return client.get_package(
pkg_type, spec.owner, spec.name, version=spec.requirements
)
qualifiers = {}
if spec.id:
qualifiers["ids"] = str(spec.id)
if spec.name:
qualifiers["names"] = spec.name.lower()
if pkg_type:
qualifiers["types"] = pkg_type
if spec.owner:
qualifiers["owners"] = spec.owner.lower()
packages = client.list_packages(qualifiers=qualifiers)["items"]
if not packages:
return None
if len(packages) > 1:
PackageManagerRegistryMixin.print_multi_package_issue(
click.echo, packages, spec
)
return None
return client.get_package( return client.get_package(
pkg_type, spec.owner, spec.name, version=spec.requirements packages[0]["type"],
packages[0]["owner"]["username"],
packages[0]["name"],
version=spec.requirements,
) )
qualifiers = {}
if spec.id:
qualifiers["ids"] = str(spec.id)
if spec.name:
qualifiers["names"] = spec.name.lower()
if pkg_type:
qualifiers["types"] = pkg_type
if spec.owner:
qualifiers["owners"] = spec.owner.lower()
packages = client.list_packages(qualifiers=qualifiers)["items"]
if not packages:
return None
if len(packages) > 1:
PackageManagerRegistryMixin.print_multi_package_issue(
click.echo, packages, spec
)
return None
return client.get_package(
packages[0]["type"],
packages[0]["owner"]["username"],
packages[0]["name"],
version=spec.requirements,
)

View File

@ -36,11 +36,14 @@ from platformio.registry.client import RegistryClient
) )
def package_unpublish_cmd(package, type, undo): # pylint: disable=redefined-builtin def package_unpublish_cmd(package, type, undo): # pylint: disable=redefined-builtin
spec = PackageSpec(package) spec = PackageSpec(package)
response = RegistryClient().unpublish_package( with AccountClient() as client:
owner=spec.owner or AccountClient().get_logged_username(), owner = spec.owner or client.get_logged_username()
type=type, with RegistryClient() as client:
name=spec.name, response = client.unpublish_package(
version=str(spec.requirements), owner=owner,
undo=undo, type=type,
) name=spec.name,
click.secho(response.get("message"), fg="green") version=str(spec.requirements),
undo=undo,
)
click.secho(response.get("message"), fg="green")

View File

@ -31,8 +31,8 @@ from platformio.registry.client import RegistryClient
) )
@click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg") @click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg")
def access_grant_cmd(level, client, urn, urn_type): # pylint: disable=unused-argument def access_grant_cmd(level, client, urn, urn_type): # pylint: disable=unused-argument
reg_client = RegistryClient() with RegistryClient() as reg_client:
reg_client.grant_access_for_resource(urn=urn, client=client, level=level) reg_client.grant_access_for_resource(urn=urn, client=client, level=level)
return click.secho( return click.secho(
"Access for resource %s has been granted for %s" % (urn, client), "Access for resource %s has been granted for %s" % (urn, client),
fg="green", fg="green",

View File

@ -25,8 +25,8 @@ from platformio.registry.client import RegistryClient
@click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg") @click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg")
@click.option("--json-output", is_flag=True) @click.option("--json-output", is_flag=True)
def access_list_cmd(owner, urn_type, json_output): # pylint: disable=unused-argument def access_list_cmd(owner, urn_type, json_output): # pylint: disable=unused-argument
reg_client = RegistryClient() with RegistryClient() as client:
resources = reg_client.list_resources(owner=owner) resources = client.list_resources(owner=owner)
if json_output: if json_output:
return click.echo(json.dumps(resources)) return click.echo(json.dumps(resources))
if not resources: if not resources:

View File

@ -25,8 +25,8 @@ from platformio.registry.client import RegistryClient
) )
@click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg") @click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg")
def access_private_cmd(urn, urn_type): # pylint: disable=unused-argument def access_private_cmd(urn, urn_type): # pylint: disable=unused-argument
client = RegistryClient() with RegistryClient() as client:
client.update_resource(urn=urn, private=1) client.update_resource(urn=urn, private=1)
return click.secho( return click.secho(
"The resource %s has been successfully updated." % urn, "The resource %s has been successfully updated." % urn,
fg="green", fg="green",

View File

@ -25,8 +25,8 @@ from platformio.registry.client import RegistryClient
) )
@click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg") @click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg")
def access_public_cmd(urn, urn_type): # pylint: disable=unused-argument def access_public_cmd(urn, urn_type): # pylint: disable=unused-argument
client = RegistryClient() with RegistryClient() as client:
client.update_resource(urn=urn, private=0) client.update_resource(urn=urn, private=0)
return click.secho( return click.secho(
"The resource %s has been successfully updated." % urn, "The resource %s has been successfully updated." % urn,
fg="green", fg="green",

View File

@ -30,8 +30,8 @@ from platformio.registry.client import RegistryClient
) )
@click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg") @click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg")
def access_revoke_cmd(client, urn, urn_type): # pylint: disable=unused-argument def access_revoke_cmd(client, urn, urn_type): # pylint: disable=unused-argument
reg_client = RegistryClient() with RegistryClient() as reg_client:
reg_client.revoke_access_from_resource(urn=urn, client=client) reg_client.revoke_access_from_resource(urn=urn, client=client)
return click.secho( return click.secho(
"Access for resource %s has been revoked for %s" % (urn, client), "Access for resource %s has been revoked for %s" % (urn, client),
fg="green", fg="green",

View File

@ -34,7 +34,8 @@ class RegistryClient(HTTPClient):
] ]
) )
try: try:
info = AccountClient().get_account_info() or {} with AccountClient() as client:
info = client.get_account_info() or {}
for item in info.get("packages", []): for item in info.get("packages", []):
if set(item.keys()) & private_permissions: if set(item.keys()) & private_permissions:
return True return True

View File

@ -37,7 +37,8 @@ class RemoteClientFactory(pb.PBClientFactory, protocol.ReconnectingClientFactory
auth_token = None auth_token = None
try: try:
auth_token = AccountClient().fetch_authentication_token() with AccountClient() as client:
auth_token = client.fetch_authentication_token()
except Exception as exc: # pylint:disable=broad-except except Exception as exc: # pylint:disable=broad-except
d = defer.Deferred() d = defer.Deferred()
d.addErrback(self.clientAuthorizationFailed) d.addErrback(self.clientAuthorizationFailed)

View File

@ -19,11 +19,11 @@ import os
import random import random
import pytest import pytest
import requests
from platformio.account.cli import cli as cmd_account from platformio.account.cli import cli as cmd_account
from platformio.account.org.cli import cli as cmd_org from platformio.account.org.cli import cli as cmd_org
from platformio.account.team.cli import cli as cmd_team from platformio.account.team.cli import cli as cmd_team
from platformio.http import HTTPSession
pytestmark = pytest.mark.skipif( pytestmark = pytest.mark.skipif(
not all( not all(
@ -60,12 +60,11 @@ def verify_account(email_contents):
.split("This link will expire within 12 hours.")[0] .split("This link will expire within 12 hours.")[0]
.strip() .strip()
) )
with requests.Session() as session: with HTTPSession() as session:
result = session.get(link).text result = session.get(link).text
link = result.split('<a href="')[1].split('"', 1)[0] link = result.split('<a href="')[1].split('"', 1)[0]
link = link.replace("&amp;", "&") link = link.replace("&amp;", "&")
session.get(link) session.get(link)
session.close()
def test_account_register( def test_account_register(

View File

@ -143,8 +143,8 @@ def get_pkg_latest_version():
if not isinstance(spec, PackageSpec): if not isinstance(spec, PackageSpec):
spec = PackageSpec(spec) spec = PackageSpec(spec)
pkg_type = pkg_type or PackageType.LIBRARY pkg_type = pkg_type or PackageType.LIBRARY
client = RegistryClient() with RegistryClient() as client:
pkg = client.get_package(pkg_type, spec.owner, spec.name) pkg = client.get_package(pkg_type, spec.owner, spec.name)
return pkg["version"]["name"] return pkg["version"]["name"]
return wrap return wrap

View File

@ -15,7 +15,6 @@
# pylint: disable=unused-argument # pylint: disable=unused-argument
import pytest import pytest
import requests
from platformio import __check_internet_hosts__, http, proc from platformio import __check_internet_hosts__, http, proc
from platformio.registry.client import RegistryClient from platformio.registry.client import RegistryClient
@ -30,19 +29,20 @@ def test_platformio_cli():
def test_ping_internet_ips(): def test_ping_internet_ips():
for host in __check_internet_hosts__: for host in __check_internet_hosts__:
requests.get("http://%s" % host, allow_redirects=False, timeout=2) with http.HTTPSession(follow_redirects=False, timeout=2) as session:
session.get("http://%s" % host)
def test_api_internet_offline(without_internet, isolated_pio_core): def test_api_internet_offline(without_internet, isolated_pio_core):
regclient = RegistryClient() with RegistryClient() as client:
with pytest.raises(http.InternetConnectionError): with pytest.raises(http.InternetConnectionError):
regclient.fetch_json_data("get", "/v3/search") client.fetch_json_data("get", "/v3/search")
def test_api_cache(monkeypatch, isolated_pio_core): def test_api_cache(monkeypatch, isolated_pio_core):
regclient = RegistryClient() with RegistryClient() as client:
api_kwargs = {"method": "get", "path": "/v3/search", "x_cache_valid": "10s"} api_kwargs = {"method": "get", "path": "/v3/search", "x_cache_valid": "10s"}
result = regclient.fetch_json_data(**api_kwargs) result = client.fetch_json_data(**api_kwargs)
assert result and "total" in result assert result and "total" in result
monkeypatch.setattr(http, "_internet_on", lambda: False) monkeypatch.setattr(http, "_internet_on", lambda: False)
assert regclient.fetch_json_data(**api_kwargs) == result assert client.fetch_json_data(**api_kwargs) == result