Skip to content

Commit

Permalink
feat: simplifying directory setter property (#3517)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
germa89 and pyansys-ci-bot authored Oct 25, 2024
1 parent 88b8f14 commit e63570e
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 63 deletions.
1 change: 1 addition & 0 deletions doc/changelog.d/3517.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
refactor: simplifying directory setter property
42 changes: 17 additions & 25 deletions src/ansys/mapdl/core/mapdl_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
42 changes: 26 additions & 16 deletions src/ansys/mapdl/core/mapdl_extended.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
CommandDeprecated,
ComponentDoesNotExits,
IncorrectWorkingDirectory,
MapdlCommandIgnoredError,
MapdlRuntimeError,
)
from ansys.mapdl.core.mapdl_core import _MapdlCore
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down
4 changes: 3 additions & 1 deletion src/ansys/mapdl/core/mapdl_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
77 changes: 56 additions & 21 deletions tests/test_mapdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import shutil
import tempfile
import time
from unittest.mock import patch

import grpc
import numpy as np
Expand All @@ -49,6 +50,7 @@
IncorrectWorkingDirectory,
MapdlCommandIgnoredError,
MapdlConnectionError,
MapdlExitedError,
MapdlRuntimeError,
)
from ansys.mapdl.core.launcher import launch_mapdl
Expand All @@ -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",
Expand All @@ -106,10 +98,18 @@
"edhist",
"edhtime",
"edint",
"edipart",
"edis",
"edlcs",
"edload",
"edmp",
"ednb",
"edndtsd",
"ednrot",
"edopt",
"edout",
"edpart",
"edpc",
"edpl",
"edpvel",
"edrc",
Expand All @@ -119,10 +119,12 @@
"edrun",
"edshell",
"edsolv",
"edsp",
"edstart",
"edterm",
"edtp",
"edvel",
"edweld",
"edwrite",
"rexport",
]
Expand Down Expand Up @@ -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
Expand All @@ -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")
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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

0 comments on commit e63570e

Please sign in to comment.