Skip to content
Snippets Groups Projects
Commit 0c2f8a70 authored by Krzysztof Mochocki's avatar Krzysztof Mochocki
Browse files

Add ensured accessors in settings for working_directory and

http_endpoint
parent b504070c
No related branches found
No related tags found
1 merge request!73Clive integration related fixes
Showing
with 49 additions and 25 deletions
...@@ -19,7 +19,9 @@ if TYPE_CHECKING: ...@@ -19,7 +19,9 @@ if TYPE_CHECKING:
class BeekeeperExecutable(Executable[BeekeeperConfig, BeekeeperArguments]): class BeekeeperExecutable(Executable[BeekeeperConfig, BeekeeperArguments]):
def __init__(self, settings: Settings, logger: Logger) -> None: def __init__(self, settings: Settings, logger: Logger) -> None:
super().__init__(settings.binary_path or get_beekeeper_binary_path(), settings.working_directory, logger) super().__init__(
settings.binary_path or get_beekeeper_binary_path(), settings.ensured_working_directory, logger
)
def _construct_config(self) -> BeekeeperConfig: def _construct_config(self) -> BeekeeperConfig:
return BeekeeperConfig(wallet_dir=self.working_directory) return BeekeeperConfig(wallet_dir=self.working_directory)
......
...@@ -145,14 +145,13 @@ class BeekeeperCommon(BeekeeperNotificationCallbacks, ABC): ...@@ -145,14 +145,13 @@ class BeekeeperCommon(BeekeeperNotificationCallbacks, ABC):
def _run_application(self, settings: Settings, additional_cli_arguments: BeekeeperArguments) -> None: def _run_application(self, settings: Settings, additional_cli_arguments: BeekeeperArguments) -> None:
assert settings.notification_endpoint is not None assert settings.notification_endpoint is not None
assert settings.http_endpoint is not None
self.__exec.run( self.__exec.run(
blocking=False, blocking=False,
arguments=additional_cli_arguments.copy( arguments=additional_cli_arguments.copy(
update={ update={
"notifications_endpoint": settings.notification_endpoint, "notifications_endpoint": settings.notification_endpoint,
"webserver_http_endpoint": settings.http_endpoint, "webserver_http_endpoint": settings.ensured_http_endpoint,
"data_dir": settings.working_directory, "data_dir": settings.ensured_working_directory,
} }
), ),
propagate_sigint=settings.propagate_sigint, propagate_sigint=settings.propagate_sigint,
......
...@@ -77,6 +77,10 @@ class Beekeeper(BeekeeperInterface, StateInvalidator): ...@@ -77,6 +77,10 @@ class Beekeeper(BeekeeperInterface, StateInvalidator):
@classmethod @classmethod
async def _remote_factory(cls, *, url_or_settings: Settings | HttpUrl) -> BeekeeperInterface: async def _remote_factory(cls, *, url_or_settings: Settings | HttpUrl) -> BeekeeperInterface:
if isinstance(url_or_settings, Settings):
assert (
url_or_settings.http_endpoint is not None
), "Settings.http_endpoint has to be set when passing to remote_factory"
settings = url_or_settings if isinstance(url_or_settings, Settings) else Settings(http_endpoint=url_or_settings) settings = url_or_settings if isinstance(url_or_settings, Settings) else Settings(http_endpoint=url_or_settings)
handle = AsynchronousRemoteBeekeeperHandle(settings=settings) handle = AsynchronousRemoteBeekeeperHandle(settings=settings)
cls.__apply_existing_session_token(settings=settings, handle=handle) cls.__apply_existing_session_token(settings=settings, handle=handle)
......
...@@ -22,10 +22,7 @@ class Settings(HandleSettings): ...@@ -22,10 +22,7 @@ class Settings(HandleSettings):
PROPAGATE_SIGINT: ClassVar[bool] = True PROPAGATE_SIGINT: ClassVar[bool] = True
CLOSE_TIMEOUT: ClassVar[timedelta] = timedelta(seconds=10.0) CLOSE_TIMEOUT: ClassVar[timedelta] = timedelta(seconds=10.0)
working_directory: Path = Defaults.default_factory( working_directory: Path | None = None
EnvironNames.WORKING_DIRECTORY,
lambda x: (Settings.Defaults.WORKING_DIRECTORY if x is None else Path(x)),
)
"""Path, where beekeeper binary will store all it's data and logs.""" """Path, where beekeeper binary will store all it's data and logs."""
http_endpoint: HttpUrl | None = None # type: ignore[assignment] http_endpoint: HttpUrl | None = None # type: ignore[assignment]
...@@ -51,3 +48,19 @@ class Settings(HandleSettings): ...@@ -51,3 +48,19 @@ class Settings(HandleSettings):
lambda x: (Settings.Defaults.CLOSE_TIMEOUT if x is None else timedelta(seconds=int(x))), lambda x: (Settings.Defaults.CLOSE_TIMEOUT if x is None else timedelta(seconds=int(x))),
) )
"""Affects time handle waits before beekeepy closes.""" """Affects time handle waits before beekeepy closes."""
@property
def ensured_working_directory(self) -> Path:
"""This property should be used to make sure, that path to working dir is returned.
Note: If Settings.working_directory is not set, Path.cwd() is returned.
"""
return self.working_directory or Settings.Defaults.WORKING_DIRECTORY
@property
def ensured_http_endpoint(self) -> HttpUrl:
"""Returns Settings.http_endpoint, if set to None, raises Exception."""
if self.http_endpoint is None:
raise ValueError("Settings.http_endpoint is None")
return self.http_endpoint
...@@ -77,6 +77,10 @@ class Beekeeper(BeekeeperInterface, StateInvalidator): ...@@ -77,6 +77,10 @@ class Beekeeper(BeekeeperInterface, StateInvalidator):
@classmethod @classmethod
def _remote_factory(cls, *, url_or_settings: Settings | HttpUrl) -> BeekeeperInterface: def _remote_factory(cls, *, url_or_settings: Settings | HttpUrl) -> BeekeeperInterface:
if isinstance(url_or_settings, Settings):
assert (
url_or_settings.http_endpoint is not None
), "Settings.http_endpoint has to be set when passing to remote_factory"
settings = url_or_settings if isinstance(url_or_settings, Settings) else Settings(http_endpoint=url_or_settings) settings = url_or_settings if isinstance(url_or_settings, Settings) else Settings(http_endpoint=url_or_settings)
handle = SynchronousRemoteBeekeeperHandle(settings=settings) handle = SynchronousRemoteBeekeeperHandle(settings=settings)
cls.__apply_existing_session_token(settings=settings, handle=handle) cls.__apply_existing_session_token(settings=settings, handle=handle)
......
...@@ -39,7 +39,7 @@ def settings_with_logger(request: pytest.FixtureRequest, settings: SettingsFacto ...@@ -39,7 +39,7 @@ def settings_with_logger(request: pytest.FixtureRequest, settings: SettingsFacto
log = logger.bind(test_name=test_name) log = logger.bind(test_name=test_name)
handlers_to_remove.append( handlers_to_remove.append(
log.add( log.add(
sets.working_directory / "beekeeper.log", sets.ensured_working_directory / "beekeeper.log",
filter=lambda params: params["extra"].get("test_name") == test_name, filter=lambda params: params["extra"].get("test_name") == test_name,
) )
) )
......
...@@ -30,7 +30,7 @@ def test_api_close_session(beekeeper: Beekeeper) -> None: ...@@ -30,7 +30,7 @@ def test_api_close_session(beekeeper: Beekeeper) -> None:
beekeeper.api.close_session() beekeeper.api.close_session()
assert checkers.check_for_pattern_in_file( assert checkers.check_for_pattern_in_file(
beekeeper.settings.working_directory / "stderr.log", close_log_entry beekeeper.settings.ensured_working_directory / "stderr.log", close_log_entry
), "Log should have information about closing session with specific token created during create_session call." ), "Log should have information about closing session with specific token created during create_session call."
...@@ -47,7 +47,7 @@ def test_if_beekeeper_closes_after_last_session_termination( ...@@ -47,7 +47,7 @@ def test_if_beekeeper_closes_after_last_session_termination(
beekeeper.api.list_wallets() beekeeper.api.list_wallets()
assert checkers.check_for_pattern_in_file( assert checkers.check_for_pattern_in_file(
beekeeper.settings.working_directory / "stderr.log", "exited cleanly" beekeeper.settings.ensured_working_directory / "stderr.log", "exited cleanly"
), "Beekeeper should be closed after last session termination." ), "Beekeeper should be closed after last session termination."
......
...@@ -32,7 +32,7 @@ def create_session(beekeeper: Beekeeper, salt: str) -> None: ...@@ -32,7 +32,7 @@ def create_session(beekeeper: Beekeeper, salt: str) -> None:
# ASSERT # ASSERT
assert len(token), "Returned token should not be empty" assert len(token), "Returned token should not be empty"
assert checkers.check_for_pattern_in_file( assert checkers.check_for_pattern_in_file(
beekeeper.settings.working_directory / "stderr.log", message_to_check beekeeper.settings.ensured_working_directory / "stderr.log", message_to_check
), "Log should have information about create_session call." ), "Log should have information about create_session call."
......
...@@ -13,7 +13,7 @@ def test_api_open(beekeeper: Beekeeper) -> None: ...@@ -13,7 +13,7 @@ def test_api_open(beekeeper: Beekeeper) -> None:
"""Test test_api_open will test beekeeper_api.open api call.""" """Test test_api_open will test beekeeper_api.open api call."""
# ARRANGE # ARRANGE
wallet = WalletInfo(password=generate_wallet_password(), name=generate_wallet_name()) wallet = WalletInfo(password=generate_wallet_password(), name=generate_wallet_name())
wallet_path = beekeeper.settings.working_directory / f"{wallet.name}.wallet" wallet_path = beekeeper.settings.ensured_working_directory / f"{wallet.name}.wallet"
assert wallet_path.exists() is False, "Before creation there should be no wallet file." assert wallet_path.exists() is False, "Before creation there should be no wallet file."
beekeeper.api.create(wallet_name=wallet.name, password=wallet.password) beekeeper.api.create(wallet_name=wallet.name, password=wallet.password)
......
...@@ -107,7 +107,7 @@ def test_api_sign_digest_with_deleted_wallet(beekeeper: Beekeeper, wallet: Walle ...@@ -107,7 +107,7 @@ def test_api_sign_digest_with_deleted_wallet(beekeeper: Beekeeper, wallet: Walle
assert signature == EXPECTED_SIGNATURE, "Signatures should match." assert signature == EXPECTED_SIGNATURE, "Signatures should match."
# ACT # ACT
wallet_path = beekeeper.settings.working_directory / f"{wallet.name}.wallet" wallet_path = beekeeper.settings.ensured_working_directory / f"{wallet.name}.wallet"
assert wallet_path.exists() is True, "Wallet should exists." assert wallet_path.exists() is True, "Wallet should exists."
wallet_path.unlink() wallet_path.unlink()
assert wallet_path.exists() is False, "Wallet should not exists." assert wallet_path.exists() is False, "Wallet should not exists."
......
...@@ -15,6 +15,6 @@ def test_proper_closing(beekeeper: Beekeeper) -> None: ...@@ -15,6 +15,6 @@ def test_proper_closing(beekeeper: Beekeeper) -> None:
@pytest.mark.parametrize("wallet_name", ["test", "123", "test"]) # noqa: PT014 we want to test duplicate wallet_name @pytest.mark.parametrize("wallet_name", ["test", "123", "test"]) # noqa: PT014 we want to test duplicate wallet_name
def test_clean_dirs(beekeeper: Beekeeper, wallet_name: str) -> None: def test_clean_dirs(beekeeper: Beekeeper, wallet_name: str) -> None:
test_file = beekeeper.settings.working_directory / f"{wallet_name}.wallet" test_file = beekeeper.settings.ensured_working_directory / f"{wallet_name}.wallet"
assert not test_file.exists() assert not test_file.exists()
test_file.touch() test_file.touch()
...@@ -50,7 +50,7 @@ def test_export_keys(beekeeper: Beekeeper) -> None: ...@@ -50,7 +50,7 @@ def test_export_keys(beekeeper: Beekeeper) -> None:
wallet_name_keys = f"{wallet_name}.keys" wallet_name_keys = f"{wallet_name}.keys"
nondefault_wallet_name_keys = f"nondefault-{wallet_name_keys}" nondefault_wallet_name_keys = f"nondefault-{wallet_name_keys}"
extract_path = beekeeper.settings.working_directory extract_path = beekeeper.settings.ensured_working_directory
create = beekeeper.api.create(wallet_name=wallet_name) create = beekeeper.api.create(wallet_name=wallet_name)
beekeeper.api.open(wallet_name=wallet_name) beekeeper.api.open(wallet_name=wallet_name)
......
...@@ -22,7 +22,7 @@ def check_log_json_rpc(log_json_rpc_path: Path) -> None: ...@@ -22,7 +22,7 @@ def check_log_json_rpc(log_json_rpc_path: Path) -> None:
def test_log_json_rpc(beekeeper_not_started: Beekeeper) -> None: def test_log_json_rpc(beekeeper_not_started: Beekeeper) -> None:
"""Test will check command line flag --log-json-rpc.""" """Test will check command line flag --log-json-rpc."""
# ARRANGE # ARRANGE
path_to_jsonrpc_logs = beekeeper_not_started.settings.working_directory path_to_jsonrpc_logs = beekeeper_not_started.settings.ensured_working_directory
# ACT # ACT
beekeeper_not_started.run(additional_cli_arguments=BeekeeperArguments(log_json_rpc=path_to_jsonrpc_logs)) beekeeper_not_started.run(additional_cli_arguments=BeekeeperArguments(log_json_rpc=path_to_jsonrpc_logs))
......
...@@ -21,6 +21,6 @@ def test_webserver_thread_pool_size(beekeeper_not_started: Beekeeper, webserver_ ...@@ -21,6 +21,6 @@ def test_webserver_thread_pool_size(beekeeper_not_started: Beekeeper, webserver_
# ASSERT # ASSERT
assert checkers.check_for_pattern_in_file( assert checkers.check_for_pattern_in_file(
beekeeper_not_started.settings.working_directory / "stderr.log", beekeeper_not_started.settings.ensured_working_directory / "stderr.log",
f"configured with {webserver_thread_pool_size} thread pool size", f"configured with {webserver_thread_pool_size} thread pool size",
) )
...@@ -40,7 +40,7 @@ def test_multiply_beekeepeer_same_storage(working_directory: Path) -> None: ...@@ -40,7 +40,7 @@ def test_multiply_beekeepeer_same_storage(working_directory: Path) -> None:
bk2.run() bk2.run()
assert checkers.check_for_pattern_in_file( assert checkers.check_for_pattern_in_file(
bk2.settings.working_directory / "stderr.log", bk2.settings.ensured_working_directory / "stderr.log",
"Failed to lock access to wallet directory; is another `beekeeper` running?", "Failed to lock access to wallet directory; is another `beekeeper` running?",
), "There should be an info about another instance of beekeeper locking wallet directory." ), "There should be an info about another instance of beekeeper locking wallet directory."
...@@ -70,7 +70,7 @@ def test_multiply_beekeepeer_different_storage(working_directory: Path) -> None: ...@@ -70,7 +70,7 @@ def test_multiply_beekeepeer_different_storage(working_directory: Path) -> None:
for bk in bks: for bk in bks:
assert ( assert (
checkers.check_for_pattern_in_file( checkers.check_for_pattern_in_file(
bk.settings.working_directory / "stderr.log", bk.settings.ensured_working_directory / "stderr.log",
"Failed to lock access to wallet directory; is another `beekeeper` running?", "Failed to lock access to wallet directory; is another `beekeeper` running?",
) )
is False is False
...@@ -90,7 +90,7 @@ def get_remote_address_from_connection_file(working_dir: Path) -> HttpUrl: ...@@ -90,7 +90,7 @@ def get_remote_address_from_connection_file(working_dir: Path) -> HttpUrl:
def test_beekeepers_files_generation(beekeeper: Beekeeper) -> None: def test_beekeepers_files_generation(beekeeper: Beekeeper) -> None:
"""Test test_beekeepers_files_generation will check if beekeeper files are generated and have same content.""" """Test test_beekeepers_files_generation will check if beekeeper files are generated and have same content."""
# ARRANGE & ACT # ARRANGE & ACT
wallet_dir = beekeeper.settings.working_directory wallet_dir = beekeeper.settings.ensured_working_directory
beekeeper_connection_file = wallet_dir / "beekeeper.connection" beekeeper_connection_file = wallet_dir / "beekeeper.connection"
beekeeper_pid_file = wallet_dir / "beekeeper.pid" beekeeper_pid_file = wallet_dir / "beekeeper.pid"
beekeeper_wallet_lock_file = wallet_dir / "beekeeper.wallet.lock" beekeeper_wallet_lock_file = wallet_dir / "beekeeper.wallet.lock"
......
...@@ -6,7 +6,7 @@ from sys import argv ...@@ -6,7 +6,7 @@ from sys import argv
from beekeepy import Beekeeper, Settings, close_already_running_beekeeper from beekeepy import Beekeeper, Settings, close_already_running_beekeeper
settings = Settings(working_directory=Path(argv[1])) settings = Settings(working_directory=Path(argv[1]))
pid_file = settings.working_directory / "pid.txt" pid_file = settings.ensured_working_directory / "pid.txt"
if argv[2] == "start": if argv[2] == "start":
bk = Beekeeper.factory(settings=settings) bk = Beekeeper.factory(settings=settings)
......
...@@ -29,14 +29,14 @@ def test_closing_with_delete(settings: SettingsFactory) -> None: ...@@ -29,14 +29,14 @@ def test_closing_with_delete(settings: SettingsFactory) -> None:
# ACT & ASSERT (no throw) # ACT & ASSERT (no throw)
bk.teardown() bk.teardown()
assert not (sets.working_directory / "beekeeper.pid").exists() assert not (sets.ensured_working_directory / "beekeeper.pid").exists()
def test_closing_with_with(settings: SettingsFactory) -> None: def test_closing_with_with(settings: SettingsFactory) -> None:
# ARRANGE, ACT & ASSERT (no throw) # ARRANGE, ACT & ASSERT (no throw)
sets = settings() sets = settings()
with Beekeeper.factory(settings=sets): with Beekeeper.factory(settings=sets):
assert (sets.working_directory / "beekeeper.pid").exists() assert (sets.ensured_working_directory / "beekeeper.pid").exists()
def test_session_tokens(settings: SettingsFactory) -> None: def test_session_tokens(settings: SettingsFactory) -> None:
......
...@@ -12,6 +12,8 @@ if TYPE_CHECKING: ...@@ -12,6 +12,8 @@ if TYPE_CHECKING:
def wait_for_beekeeper_to_close(beekeeper: Beekeeper, timeout_seconds: int = 10) -> None: def wait_for_beekeeper_to_close(beekeeper: Beekeeper, timeout_seconds: int = 10) -> None:
start = datetime.now(timezone.utc) start = datetime.now(timezone.utc)
while (datetime.now(timezone.utc) - start).total_seconds() <= timeout_seconds: while (datetime.now(timezone.utc) - start).total_seconds() <= timeout_seconds:
if checkers.check_for_pattern_in_file(beekeeper.settings.working_directory / "stderr.log", "exited cleanly"): if checkers.check_for_pattern_in_file(
beekeeper.settings.ensured_working_directory / "stderr.log", "exited cleanly"
):
return return
raise TimeoutError raise TimeoutError
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment