Skip to content

Commit

Permalink
dev(hansbug): remove some old usage for python3.5/3.6
Browse files Browse the repository at this point in the history
  • Loading branch information
HansBug committed May 7, 2023
1 parent a7db980 commit f92ec96
Show file tree
Hide file tree
Showing 13 changed files with 49 additions and 65 deletions.
5 changes: 2 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ RANGE_DIR ?= .
RANGE_TEST_DIR := ${TEST_DIR}/${RANGE_DIR}
RANGE_SRC_DIR := ${SRC_DIR}/${RANGE_DIR}

CI_DEFAULT_RERUN := 5
LOCAL_DEFAULT_RERUN := 3
CI_DEFAULT_RERUN := 3
LOCAL_DEFAULT_RERUN := 0
DEFAULT_RERUN ?= $(if ${CI},${CI_DEFAULT_RERUN},${LOCAL_DEFAULT_RERUN})
ACTUAL_RERUN := $(if ${RERUN},${RERUN},${DEFAULT_RERUN})

Expand All @@ -39,7 +39,6 @@ unittest:
$(shell for type in ${COV_TYPES}; do echo "--cov-report=$$type"; done) \
--cov="${RANGE_SRC_DIR}" \
$(if ${MIN_COVERAGE},--cov-fail-under=${MIN_COVERAGE},) \
--durations=10 \
$(if ${CI}${ACTUAL_RERUN},--reruns ${ACTUAL_RERUN} --reruns-delay ${ACTUAL_RERUN_DELAY},) \
$(if ${ACTUAL_TIMEOUT},--timeout=${ACTUAL_TIMEOUT},)

Expand Down
6 changes: 3 additions & 3 deletions plantumlcli/entry/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ def _check_plantuml(name: str, success, plantuml: Union[_Tp, Exception],
success, plantuml = False, e

if success:
click.secho('{name} plantuml detected.'.format(name=name.capitalize()), fg='green')
click.secho(f'{name.capitalize()} plantuml detected.', fg='green')

click.echo(_version)
if callback:
callback(plantuml, _duration)
else:
click.secho('{name} plantuml not detected or has problem.'.format(name=name.capitalize()), fg='red')
click.echo('Error : {error}'.format(error=repr(plantuml)))
click.secho(f'{name.capitalize()} plantuml not detected or has problem.', fg='red')
click.echo(f'Error : {plantuml!r}')

return success
10 changes: 4 additions & 6 deletions plantumlcli/entry/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ def print_version(ctx: Context, param: Option, value: bool) -> None:
"""
if not value or ctx.resilient_parsing:
return
click.echo('{title}, version {version}.'.format(title=__TITLE__.capitalize(), version=__VERSION__))
click.echo('Developed by {author}, {email}.'.format(author=__AUTHOR__, email=__AUTHOR_EMAIL__))
click.echo(f'{__TITLE__.capitalize()}, version {__VERSION__}.')
click.echo(f'Developed by {__AUTHOR__}, {__AUTHOR_EMAIL__}.')
ctx.exit()


Expand All @@ -70,11 +70,9 @@ def validate_concurrency(ctx: Context, param: Option, value: int):
help='Path of java executable file (will load from environment when not given).',
show_default='java from ${PATH}')
@click.option('-p', '--plantuml', envvar=PLANTUML_JAR_ENV, type=str, default=None,
help='Path of plantuml jar file (will load from ${{{env}}} when not given).'.format(
env=PLANTUML_JAR_ENV))
help=f'Path of plantuml jar file (will load from ${{{PLANTUML_JAR_ENV}}} when not given).')
@click.option('-r', '--remote-host', envvar=PLANTUML_HOST_ENV, type=str, default=OFFICIAL_PLANTUML_HOST,
help='Remote host of the online plantuml editor (will load from ${{{env}}} when not given).'.format(
env=PLANTUML_HOST_ENV),
help=f'Remote host of the online plantuml editor (will load from ${{{PLANTUML_HOST_ENV}}} when not given).',
show_default=True)
@click.option('-L', '--use-local', is_flag=True, help='Use local plantuml only.')
@click.option('-R', '--use-remote', is_flag=True, help='Use remote plantuml only.')
Expand Down
16 changes: 7 additions & 9 deletions plantumlcli/entry/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,12 @@ def _print_text(src: str, ret: Tuple[bool, Union[str, LocalPlantumlExecuteError]
_success, _data = ret

if _success:
click.secho('{source}: '.format(source=src), fg='green')
click.secho(f'{src}: ', fg='green')
click.echo(_data)
else:
nonlocal _error_count
if isinstance(_data, LocalPlantumlExecuteError):
click.secho('{source}: [error with exitcode {code}]'.format(source=src, code=_data.exitcode), fg='red')
click.secho(f'{src}: [error with exitcode {_data.exitcode}]', fg='red')
click.secho(_data.stderr, fg='red')
else:
if hasattr(_data, 'response'):
Expand All @@ -94,10 +94,9 @@ def _print_text(src: str, ret: Tuple[bool, Union[str, LocalPlantumlExecuteError]
response, code = None, None

if code:
click.secho('{source}: [{cls} {code}]'.format(
source=src, cls=type(_data).__name__, code=code), fg='red')
click.secho(f'{src}: [{type(_data).__name__} {code}]', fg='red')
else:
click.secho('{source}: [{cls}]'.format(source=src, cls=type(_data).__name__), fg='red')
click.secho(f'{src}: [{type(_data).__name__}]', fg='red')

click.secho(str(_data), fg='red')
if response is not None and code and response.content:
Expand All @@ -116,7 +115,7 @@ def _print_text(src: str, ret: Tuple[bool, Union[str, LocalPlantumlExecuteError]
if _error_count > 0:
raise _click_exception_with_exit_code(
name='TextGraphError',
message='{count} error(s) found when generating text graph.'.format(count=_error_count),
message=f'{_error_count} error(s) found when generating text graph.',
exitcode=-2,
)

Expand All @@ -125,16 +124,15 @@ def process_plantuml(plantuml: Plantuml, sources: Tuple[str],
outputs: Tuple[str], output_dir: Optional[str],
type_: PlantumlResourceType, concurrency: int):
if outputs and len(outputs) != len(sources):
raise ValueError('Amount of output file(s) should be {expect}, but {actual} found.'
.format(expect=len(sources), actual=len(outputs)))
raise ValueError(f'Amount of output file(s) should be {len(sources)}, but {len(outputs)} found.')

def _output_filename(index: int):
if outputs:
name = outputs[index]
else:
_, _filename = os.path.split(sources[index])
_name, _ = os.path.splitext(_filename)
name = '{name}.{ext}'.format(name=_name, ext=type_.name.lower())
name = f'{_name}.{type_.name.lower()}'
return os.path.join(output_dir or os.curdir, name)

def _process_code(index: int):
Expand Down
5 changes: 3 additions & 2 deletions plantumlcli/entry/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@


def _additional_info_for_local(plantuml: LocalPlantuml, duration: float):
click.echo('Java executable : {path}'.format(path=os.path.abspath(plantuml.java)))
click.echo('Plantuml jar : {path}'.format(path=os.path.abspath(plantuml.plantuml)))
_ = duration
click.echo(f'Java executable : {os.path.abspath(plantuml.java)}')
click.echo(f'Plantuml jar : {os.path.abspath(plantuml.plantuml)}')


def _check_local_plantuml(success, plantuml: Union[LocalPlantuml, Exception]) -> bool:
Expand Down
4 changes: 2 additions & 2 deletions plantumlcli/entry/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@


def _additional_info_for_remote(plantuml: RemotePlantuml, duration: float):
click.echo('Remote host : {host}'.format(host=plantuml.host))
click.echo('Connection time : {time}s'.format(time='%.3f' % (duration,)))
click.echo(f'Remote host : {plantuml.host}')
click.echo(f'Connection time : {"%.3f" % (duration,)}s')


def _check_remote_plantuml(success: bool, plantuml: Union[RemotePlantuml, Exception]) -> bool:
Expand Down
15 changes: 5 additions & 10 deletions plantumlcli/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,14 @@ def load(cls, data: Union[int, str, 'PlantumlResourceType']) -> 'PlantumlResourc
if data in cls.__members__.values():
return cls.__members__[dict(zip(cls.__members__.values(), cls.__members__.keys()))[data]]
else:
raise ValueError('Value {value} not found for enum {cls}.'.format(value=repr(data), cls=cls.__name__))
raise ValueError(f'Value {data!r} not found for enum {cls.__name__}.')
elif isinstance(data, str):
if data.upper() in cls.__members__.keys():
return cls.__members__[data.upper()]
else:
raise KeyError('Key {key} not found for enum {cls}.'.format(key=repr(data), cls=cls.__name__))
raise KeyError(f'Key {data!r} not found for enum {cls.__name__}.')
else:
raise TypeError('Data should be an int, str or {cls}, but {actual} found.'.format(
cls=cls.__name__, actual=type(data).__name__,
))
raise TypeError(f'Data should be an int, str or {cls.__name__}, but {type(data).__name__} found.')


class Plantuml(metaclass=ABCMeta):
Expand Down Expand Up @@ -123,11 +121,8 @@ def _properties(self) -> Mapping[str, Any]:
return {}

def __repr__(self):
return '<{cls} {properties}>'.format(
cls=self.__class__.__name__,
properties=', '.join(['{key}: {value}'.format(key=key, value=repr(value))
for key, value in sorted(self._properties().items())]),
)
prop_str = ', '.join([f'{key}: {value!r}' for key, value in sorted(self._properties().items())])
return f'<{self.__class__.__name__} {prop_str}>'


_Tp = TypeVar('_Tp', bound=Plantuml)
Expand Down
18 changes: 9 additions & 9 deletions plantumlcli/models/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,20 @@ def _check_local(java: str, plantuml: str):
if not java:
raise ValueError('Java executable not given.')
if not os.path.exists(java):
raise FileNotFoundError('Java executable {exec} not found.'.format(exec=repr(java)))
raise FileNotFoundError(f'Java executable {java!r} not found.')
if not os.path.isfile(java):
raise IsADirectoryError('Java executable {exec} is not a file.'.format(exec=repr(java)))
raise IsADirectoryError(f'Java executable {java!r} is not a file.')
if not os.access(java, os.X_OK):
raise PermissionError('Java executable {exec} not executable.'.format(exec=repr(java)))
raise PermissionError(f'Java executable {java!r} not executable.')

Check warning on line 37 in plantumlcli/models/local.py

View check run for this annotation

Codecov / codecov/patch

plantumlcli/models/local.py#L37

Added line #L37 was not covered by tests

if not plantuml:
raise ValueError('Plantuml jar file not given.')
if not os.path.exists(plantuml):
raise FileNotFoundError('Plantuml jar file {jar} not found.'.format(jar=repr(plantuml)))
raise FileNotFoundError(f'Plantuml jar file {plantuml!r} not found.')
if not os.path.isfile(plantuml):
raise IsADirectoryError('Plantuml jar file {jar} is not a file.'.format(jar=repr(plantuml)))
raise IsADirectoryError(f'Plantuml jar file {plantuml!r} is not a file.')
if not os.access(plantuml, os.R_OK):
raise PermissionError('Plantuml jar file {jar} not readable.'.format(jar=repr(plantuml)))
raise PermissionError(f'Plantuml jar file {plantuml!r} not readable.')

Check warning on line 46 in plantumlcli/models/local.py

View check run for this annotation

Codecov / codecov/patch

plantumlcli/models/local.py#L46

Added line #L46 was not covered by tests


class LocalPlantumlExecuteError(CommandLineExecuteError):
Expand Down Expand Up @@ -100,7 +100,7 @@ def __execute(self, *args) -> Tuple[str, str]:

def _check_version(self, version: str):
if (not version) or ("plantuml" not in version.lower()):
raise ValueError("Invalid version of plantuml - {version}.".format(version=repr(version)))
raise ValueError(f"Invalid version of plantuml - {version!r}.")

def _get_version(self) -> str:
_stdout, _ = self.__execute('-version')
Expand All @@ -114,10 +114,10 @@ def _generate_uml_data(self, type_: PlantumlResourceType, code: str) -> bytes:
with TemporaryDirectory(prefix='puml') as output_path_name:
with NamedTemporaryFile(prefix='puml', suffix='.puml') as input_file:
save_text_file(input_file.name, code)
self.__execute('-t{type}'.format(type=type_.name.lower()), '-o', output_path_name, input_file.name)
self.__execute(f'-t{type_.name.lower()}', '-o', output_path_name, input_file.name)
_file_list = os.listdir(output_path_name)
if _file_list:
output_filename = os.path.join(output_path_name, _file_list[0])
return load_binary_file(output_filename)
else:
raise FileNotFoundError('No expected file found in {path}.'.format(path=repr(output_path_name)))
raise FileNotFoundError(f'No expected file found in {output_path_name!r}.')
11 changes: 5 additions & 6 deletions plantumlcli/models/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,11 @@ def _host_process(host: str) -> URLObject:

def _check_remote(host: str):
if not host:
raise ValueError("Host should be present, but {actual} found.".format(actual=repr(host)))
raise ValueError(f"Host should be present, but {host!r} found.")

_host_url = _host_process(host)
if _host_url.scheme not in ['http', 'https']:
raise ValueError(
"Host's scheme should be http or https, but {actual} found.".format(actual=repr(_host_url.scheme)))
raise ValueError(f"Host's scheme should be http or https, but {_host_url.scheme!r} found.")


class RemotePlantuml(Plantuml):
Expand Down Expand Up @@ -100,12 +99,12 @@ def __get_homepage(self):

def _is_official(self):
return self.__host.hostname in ('plantuml.com', 'www.plantuml.com') and \
len(self.__host.path.segments) > 0 and self.__host.path.segments[0] == 'plantuml'
len(self.__host.path.segments) > 0 and self.__host.path.segments[0] == 'plantuml'

def _check_version(self, version: str):
if not self._is_official():
if (not version) or ("plantuml" not in version.lower()) or ("version" not in version.lower()):
raise ValueError("Invalid version information from homepage - {info}.".format(info=repr(version)))
raise ValueError(f"Invalid version information from homepage - {version!r}.")

def _get_version(self) -> str:
if not self._is_official():
Expand All @@ -115,7 +114,7 @@ def _get_version(self) -> str:
return 'Official Site'

def __get_uml_path(self, type_: str, code: str):
return "{}/{}".format(type_, self.__compress(code))
return f"{type_}/{self.__compress(code)}"

def __get_uml_url(self, type_: str, code: str) -> str:
return self.__request_url(self.__get_uml_path(type_, code))
Expand Down
6 changes: 1 addition & 5 deletions plantumlcli/utils/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,7 @@ def stderr(self) -> Optional[str]:
return self.__stderr

def __repr__(self):
return '<{cls} exitcode: {code}, command_line: {cmd}>'.format(
cls=self.__class__.__name__,
cmd=repr(self.__command_line),
code=repr(self.__exitcode),
)
return f'<{self.__class__.__name__} exitcode: {self.__exitcode!r}, command_line: {self.__command_line!r}>'

@classmethod
def try_raise(cls, command_line: Tuple[str], exitcode: int,
Expand Down
6 changes: 2 additions & 4 deletions test/models/test_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,8 @@ def test_plantuml(self, plantuml_jar_file, plantuml):
assert plantuml.plantuml == plantuml_jar_file

def test_repr(self, plantuml_jar_file, plantuml):
assert repr(plantuml) == '<LocalPlantuml java: {java}, plantuml: {plantuml}>'.format(
java=repr(shutil.which('java')),
plantuml=repr(plantuml_jar_file),
)
assert repr(plantuml) == \
f'<LocalPlantuml java: {shutil.which("java")!r}, plantuml: {plantuml_jar_file!r}>'

def test_check_and_test(self, plantuml):
plantuml.check()
Expand Down
6 changes: 3 additions & 3 deletions test/utils/test_concurrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def _timing_4():
def test_linear_process_error_skip(self):
def _process(x):
if x == 5:
raise ValueError('value error for this awesome_test, value is {v}'.format(v=x))
raise ValueError(f'value error for this awesome_test, value is {x}')
else:
return x * x

Expand All @@ -77,7 +77,7 @@ def _process(x):
def test_linear_process_error_not_skip(self):
def _process(x):
if x in [3, 7]:
raise ValueError('value error for this awesome_test, value is {v}'.format(v=x))
raise ValueError(f'value error for this awesome_test, value is {x}')
else:
return x * x

Expand Down Expand Up @@ -122,7 +122,7 @@ def test_linear_process_error_post(self):

def _post_process(i, x, r):
if x == 3:
raise ValueError('value error for this awesome_test, value is {v}'.format(v=x))
raise ValueError(f'value error for this awesome_test, value is {x}')
_list.append((i, x, r))

with pytest.raises(ValueError) as e:
Expand Down
6 changes: 3 additions & 3 deletions test/utils/test_execute.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
import shutil

import pytest
import where

from plantumlcli.utils import execute, CommandLineExecuteError

Expand All @@ -16,7 +16,7 @@ def test_execute(self):

def test_execute_error(self):
with pytest.raises(CommandLineExecuteError) as r:
execute(where.first('python'), '-c',
execute(shutil.which('python'), '-c',
r'import sys;print(2345678);print(2333333, file=sys.stderr);raise RuntimeError;')

err = r.value
Expand All @@ -28,7 +28,7 @@ def test_execute_error(self):
('-c', r'import sys;print(2345678);print(2333333, file=sys.stderr);raise RuntimeError;')
assert repr(err) == "<CommandLineExecuteError exitcode: 1, command_line: ({python}, '-c', " \
"'import sys;print(2345678);print(2333333, file=sys.stderr);raise RuntimeError;')>" \
.format(python=repr(where.first('python')))
.format(python=repr(shutil.which('python')))


if __name__ == "__main__":
Expand Down

0 comments on commit f92ec96

Please sign in to comment.