From e63570efcfce46dd50cea0b192205e65dacf252f Mon Sep 17 00:00:00 2001 From: German <28149841+germa89@users.noreply.github.com> Date: Fri, 25 Oct 2024 15:21:54 +0200 Subject: [PATCH] feat: simplifying directory setter property (#3517) * feat: simplifying directory property * chore: adding changelog file 3517.miscellaneous.md [dependabot-skip] * test: adding test * feat: caching directory in cwd * feat: caching directory for sure. * feat: caching dir at the cwd level. * feat: retry mechanism inside /INQUIRE * feat: changing exception message * feat: adding tests * feat: caching directory --------- Co-authored-by: pyansys-ci-bot <92810346+pyansys-ci-bot@users.noreply.github.com> --- doc/changelog.d/3517.added.md | 1 + src/ansys/mapdl/core/mapdl_core.py | 42 ++++++-------- src/ansys/mapdl/core/mapdl_extended.py | 42 ++++++++------ src/ansys/mapdl/core/mapdl_grpc.py | 4 +- tests/conftest.py | 1 + tests/test_mapdl.py | 77 +++++++++++++++++++------- 6 files changed, 104 insertions(+), 63 deletions(-) create mode 100644 doc/changelog.d/3517.added.md diff --git a/doc/changelog.d/3517.added.md b/doc/changelog.d/3517.added.md new file mode 100644 index 0000000000..d245230f94 --- /dev/null +++ b/doc/changelog.d/3517.added.md @@ -0,0 +1 @@ +refactor: simplifying directory setter property \ No newline at end of file diff --git a/src/ansys/mapdl/core/mapdl_core.py b/src/ansys/mapdl/core/mapdl_core.py index c380cda782..f9664ad6a8 100644 --- a/src/ansys/mapdl/core/mapdl_core.py +++ b/src/ansys/mapdl/core/mapdl_core.py @@ -281,7 +281,6 @@ def __init__( self._krylov = None self._on_docker = None self._platform = None - self._path_cache = None # Cache self._print_com: bool = print_com # print the command /COM input. # Start_parameters @@ -498,33 +497,26 @@ def directory(self) -> str: accessible, ``cwd`` (:func:`MapdlBase.cwd`) will raise a warning. """ - # always attempt to cache the path - i = 0 - while (not self._path and i > 5) or i == 0: - try: - self._path = self.inquire("", "DIRECTORY") - except Exception as e: # pragma: no cover - logger.warning( - f"Failed to get the directory due to the following error: {e}" - ) - i += 1 - if not self._path: # pragma: no cover - time.sleep(0.1) + # Inside inquire there is already a retry mechanisim + path = None + try: + path = self.inquire("", "DIRECTORY") + except MapdlExitedError: + # Let's return the cached path + pass # os independent path format - if self._path: # self.inquire might return ''. - self._path = self._path.replace("\\", "/") + if path: # self.inquire might return ''. + path = path.replace("\\", "/") # new line to fix path issue, see #416 - self._path = repr(self._path)[1:-1] - else: # pragma: no cover - if self._path_cache: - return self._path_cache - else: - raise IOError( - f"The directory returned by /INQUIRE is not valid ('{self._path}')." - ) + path = repr(path)[1:-1] + self._path = path + + elif not self._path: + raise MapdlRuntimeError( + f"MAPDL could provide a path using /INQUIRE or the cached path ('{self._path}')." + ) - self._path_cache = self._path # update return self._path @directory.setter @@ -2319,7 +2311,7 @@ def __del__(self): self.exit() except Exception as e: try: # logger might be closed - if self._log is not None: + if hasattr(self, "_log") and self._log is not None: self._log.error("exit: %s", str(e)) except ValueError: pass diff --git a/src/ansys/mapdl/core/mapdl_extended.py b/src/ansys/mapdl/core/mapdl_extended.py index 06a7dd619e..fa8ce48de9 100644 --- a/src/ansys/mapdl/core/mapdl_extended.py +++ b/src/ansys/mapdl/core/mapdl_extended.py @@ -37,6 +37,7 @@ CommandDeprecated, ComponentDoesNotExits, IncorrectWorkingDirectory, + MapdlCommandIgnoredError, MapdlRuntimeError, ) from ansys.mapdl.core.mapdl_core import _MapdlCore @@ -354,14 +355,12 @@ def mpread(self, fname="", ext="", lib="", **kwargs): @wraps(_MapdlCore.cwd) def cwd(self, *args, **kwargs): """Wraps cwd.""" - output = super().cwd(*args, mute=False, **kwargs) - - if output is not None: - if "*** WARNING ***" in output: - raise IncorrectWorkingDirectory( - "\n" + "\n".join(output.splitlines()[1:]) - ) + try: + output = super().cwd(*args, mute=False, **kwargs) + except MapdlCommandIgnoredError as e: + raise IncorrectWorkingDirectory(e.args[0]) + self._path = args[0] # caching return output @wraps(_MapdlCore.list) @@ -1423,17 +1422,28 @@ def inquire(self, strarray="", func="", arg1="", arg2="", **kwargs): raise ValueError( f"The arguments (strarray='{strarray}', func='{func}') are not valid." ) + response = "" + n_try = 3 + i_try = 0 + while i_try < n_try and not response: + response = self.run( + f"/INQUIRE,{strarray},{func},{arg1},{arg2}", mute=False, **kwargs + ) + i_try += 1 - response = self.run( - f"/INQUIRE,{strarray},{func},{arg1},{arg2}", mute=False, **kwargs - ) - if func.upper() in [ - "ENV", - "TITLE", - ]: # the output is multiline, we just need the last line. - response = response.splitlines()[-1] + if not response: + if not self._store_commands: + raise MapdlRuntimeError("/INQUIRE command didn't return a response.") + else: + if func.upper() in [ + "ENV", + "TITLE", + ]: # the output is multiline, we just need the last line. + response = response.splitlines()[-1] + + response = response.split("=")[1].strip() - return response.split("=")[1].strip() + return response @wraps(_MapdlCore.parres) def parres(self, lab="", fname="", ext="", **kwargs): diff --git a/src/ansys/mapdl/core/mapdl_grpc.py b/src/ansys/mapdl/core/mapdl_grpc.py index 9ee6b7a84a..9e4158defa 100644 --- a/src/ansys/mapdl/core/mapdl_grpc.py +++ b/src/ansys/mapdl/core/mapdl_grpc.py @@ -905,7 +905,9 @@ def _run_at_connect(self): with self.run_as_routine("POST26"): self.numvar(200, mute=True) - self.inquire("", "DIRECTORY") + # Caching directory + self.directory + self.show(self._file_type_for_plots) self.version # Caching version self.file_type_for_plots # Setting /show,png and caching it. diff --git a/tests/conftest.py b/tests/conftest.py index b0434fe308..703bd3a36d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -439,6 +439,7 @@ def run_before_and_after_tests( assert prev == mapdl.is_local assert not mapdl.exited + assert not mapdl.ignore_errors make_sure_not_instances_are_left_open() diff --git a/tests/test_mapdl.py b/tests/test_mapdl.py index 909860f461..c3812a17f6 100644 --- a/tests/test_mapdl.py +++ b/tests/test_mapdl.py @@ -28,6 +28,7 @@ import shutil import tempfile import time +from unittest.mock import patch import grpc import numpy as np @@ -49,6 +50,7 @@ IncorrectWorkingDirectory, MapdlCommandIgnoredError, MapdlConnectionError, + MapdlExitedError, MapdlRuntimeError, ) from ansys.mapdl.core.launcher import launch_mapdl @@ -67,36 +69,26 @@ PORT1 = 50090 DEPRECATED_COMMANDS = [ + "edadapt", + "edale", "edasmp", "edbound", + "edbvis", "edbx", + "edcadapt", "edcgen", "edclist", "edcmore", "edcnstr", "edcontact", - "edcrb", - "edcurve", - "eddbl", - "eddc", - "edipart", - "edlcs", - "edmp", - "ednb", - "edndtsd", - "ednrot", - "edpart", - "edpc", - "edsp", - "edweld", - "edadapt", - "edale", - "edbvis", - "edcadapt", "edcpu", + "edcrb", "edcsc", "edcts", + "edcurve", "eddamp", + "eddbl", + "eddc", "eddrelax", "eddump", "edenergy", @@ -106,10 +98,18 @@ "edhist", "edhtime", "edint", + "edipart", "edis", + "edlcs", "edload", + "edmp", + "ednb", + "edndtsd", + "ednrot", "edopt", "edout", + "edpart", + "edpc", "edpl", "edpvel", "edrc", @@ -119,10 +119,12 @@ "edrun", "edshell", "edsolv", + "edsp", "edstart", "edterm", "edtp", "edvel", + "edweld", "edwrite", "rexport", ] @@ -467,7 +469,7 @@ def test_error(mapdl): mapdl.a(0, 0, 0, 0) -def test_ignore_error(mapdl): +def test_ignore_errors(mapdl): mapdl.ignore_errors = False assert not mapdl.ignore_errors mapdl.ignore_errors = True @@ -478,8 +480,8 @@ def test_ignore_error(mapdl): out = mapdl._run("A, 0, 0, 0") assert "*** ERROR ***" in out - mapdl.ignore_error = False - assert mapdl.ignore_error is False + mapdl.ignore_errors = False + assert mapdl.ignore_errors is False @requires("grpc") @@ -1726,6 +1728,7 @@ def test_on_docker(mapdl): def test_deprecation_allow_ignore_warning(mapdl): with pytest.warns(DeprecationWarning, match="'allow_ignore' is being deprecated"): mapdl.allow_ignore = True + mapdl.ignore_errors = False def test_deprecation_allow_ignore_errors_mapping(mapdl): @@ -2460,3 +2463,35 @@ def test_no_flush_stored(mapdl): assert not mapdl._store_commands assert mapdl._stored_commands == [] + + +def test_directory_setter(mapdl): + # Testing edge cases + prev_path = mapdl._path + + with patch( + "ansys.mapdl.core.Mapdl.inquire", side_effect=MapdlExitedError("mocked error") + ) as mck_inquire: + + assert prev_path == mapdl.directory + + mck_inquire.assert_called_once() + + mapdl._path = "" + with pytest.raises( + MapdlRuntimeError, + match="MAPDL could provide a path using /INQUIRE or the cached path", + ): + mapdl.directory + + mapdl._path = prev_path + + +def test_cwd_changing_directory(mapdl): + prev_path = mapdl._path + mapdl._path = None + + mapdl.cwd(prev_path) + + assert mapdl._path == prev_path + assert mapdl.directory == prev_path