Skip to content

Commit

Permalink
refactor: small improvements to test settings (#3577)
Browse files Browse the repository at this point in the history
* ci: adding timeout to each test

* chore: adding changelog file 3577.dependencies.md [dependabot-skip]

* test: avoid checking command output

* test: avoid checking command output

* fix: unpack

* feat: disabling subscription to channel

* fix: components typo

* chore: adding changelog file 3577.documentation.md [dependabot-skip]

* feat: avoid checking on not set channel

* ci: automate logging when testing

* fix: reading nset when no RST is generated

* fix: detecting comments as parameters sets when they have =.

* fix: avoid fail on reading rst file

* feat: setting verbosity when debug env var

* feat: using non-interactive for using iterable in XSEL commands

* fix: running post.__repr__ as post1

* feat: logging non_interactive in MAPDL logging and APDL logging

* fix: post_processing repr

* test: post string

* fix: test

* feat: showing a warning when rebooting MAPDL.

* tests: skip some test Temporary

* fix: initial channel state

* fix: removing APDL comment so it does not interfere on the last_respone

* fix: database tests

* fix: path test

* feat: stripping spaces from the command output

* fix: checking pids when there is no cleanup file.

* fix: make sure we are properly comparing paths when MAPDL is also installed on a machine.

* ci: auto fixes from pre-commit.com hooks.

for more information, see https://pre-commit.ci

* fix: small fixes in database tests

* fix: skip testing on windows for the moment

* ci: auto fixes from pre-commit.com hooks.

for more information, see https://pre-commit.ci

* fix: precommit

* fix: xpl not loading full file

* refactor: moving xpl tests to a class

* feat: adding apdl output

* tests: removing redundant test

* chore: merge fix/avoid-error-when-retriving-routine

* chore: adding changelog file 3596.miscellaneous.md [dependabot-skip]

* revert: "revert: "Merge branches 'feat/piping-MAPDL-output-to-a-given-file', 'main' and 'main' of https://github.com/ansys/pymapdl" (#3607)"

This reverts commit afad43e.

* chore: adding changelog file 3577.dependencies.md [dependabot-skip]

* refactor: reorg allowed arguments order

* fix: removing `file` call.

* feat: apply suggestions from code review

* feat: apply suggestions from code review

* chore: adding changelog file 3577.added.md [dependabot-skip]

* fix: removing left behind code

---------

Co-authored-by: pyansys-ci-bot <[email protected]>
Co-authored-by: gayuso <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
4 people authored Jan 7, 2025
1 parent 841313d commit 7b544b4
Show file tree
Hide file tree
Showing 15 changed files with 238 additions and 139 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ env:
ON_CI: True
PYTEST_ARGUMENTS: '-vvv -rxXsa --color=yes --durations=10 --random-order --random-order-bucket=class --maxfail=10 --reruns 3 --reruns-delay 4 --cov=ansys.mapdl.core --cov-report=html --timeout=180'


BUILD_CHEATSHEET: True
PYMAPDL_DEBUG_TESTING: True

Expand Down Expand Up @@ -63,7 +64,6 @@ permissions:

jobs:


update-changelog:
name: "Update CHANGELOG (on release)"
if: github.event_name == 'push' && contains(github.ref, 'refs/tags')
Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/3577.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
refactor: small improvements to test settings
5 changes: 3 additions & 2 deletions src/ansys/mapdl/core/database/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,9 @@ def stop(self):

self._mapdl._log.debug("Closing the connection with the MAPDL DB Server")
self._stop()
self._channel.close()
self._channel = None
if self._channel:
self._channel.close()
self._channel = None
self._stub = None
self._state = None

Expand Down
4 changes: 2 additions & 2 deletions src/ansys/mapdl/core/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ def version_from_path(*args, **kwargs):
"additional_switches",
"cleanup_on_exit",
"clear_on_connect",
"running_on_hpc",
"exec_file",
"force_intel" "ip",
"ip",
Expand All @@ -125,6 +124,7 @@ def version_from_path(*args, **kwargs):
"remove_temp_dir_on_exit",
"replace_env_vars",
"run_location",
"running_on_hpc",
"scheduler_options",
"set_no_abort",
"start_instance",
Expand Down Expand Up @@ -554,7 +554,7 @@ def check_mapdl_launch(
MAPDL did not start.
"""
LOG.debug("Generating queue object for stdout")
stdout_queue, _ = _create_queue_for_std(process.stdout)
stdout_queue, thread = _create_queue_for_std(process.stdout)

# Checking connection
try:
Expand Down
4 changes: 3 additions & 1 deletion src/ansys/mapdl/core/mapdl_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1396,7 +1396,8 @@ def __init__(self, parent):
self._parent = weakref.ref(parent)

def __enter__(self):
self._parent()._log.debug("Entering non-interactive mode")
self._parent()._log.debug("Entering in non-interactive mode")
self._parent().com("Entering in non_interactive mode")
self._parent()._store_commands = True

def __exit__(self, *args):
Expand Down Expand Up @@ -2283,6 +2284,7 @@ def run(
self._before_run(command)

short_cmd = parse_to_short_cmd(command)
self._log.debug(f"Running (verbose: {verbose}, mute={mute}): '{command}'")
text = self._run(command, verbose=verbose, mute=mute)

if (
Expand Down
7 changes: 6 additions & 1 deletion src/ansys/mapdl/core/mapdl_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1334,7 +1334,12 @@ def _cache_pids(self):
pids = set(re.findall(r"-9 (\d+)", raw))
self._pids = [int(pid) for pid in pids]

if not self._pids:
if not self._pids and not self._mapdl_process:
self._log.debug(
f"MAPDL process is not provided. PIDs could not be retrieved."
)
return
elif not self._pids:
# For the cases where the cleanup file is not generated,
# we relay on the process.
parent_pid = self._mapdl_process.pid
Expand Down
7 changes: 4 additions & 3 deletions src/ansys/mapdl/core/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -571,9 +571,10 @@ def wrapper(self, *args, **kwargs):
# assuming you want to select nothing because you supplied an empty list/tuple/array
return original_sel_func(self, "none")

self._perform_entity_list_selection(
entity, original_sel_func, type_, item, comp, vmin, kabs
)
with self.non_interactive: # to speed up
self._perform_entity_list_selection(
entity, original_sel_func, type_, item, comp, vmin, kabs
)

if kwargs.pop("Used_P", False):
# we want to return the
Expand Down
2 changes: 1 addition & 1 deletion src/ansys/mapdl/core/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ def _get_parameter_array(self, parm_name, shape):
f"that could not be read using '{format_str}'."
)

arr_flat = np.fromstring(output, sep="\n").reshape(shape)
arr_flat = np.fromstring(output.strip(), sep="\n").reshape(shape)

if len(shape) == 3:
if shape[2] == 1:
Expand Down
34 changes: 29 additions & 5 deletions src/ansys/mapdl/core/post.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,37 @@ def _mapdl(self):
@supress_logging
def __repr__(self):
info = "PyMAPDL PostProcessing Instance\n"
info += "\tActive Result File: %s\n" % self.filename
info += "\tNumber of result sets: %d\n" % self.nsets
info += "\tCurrent load step: %d\n" % self.load_step
info += "\tCurrent sub step: %d\n" % self.sub_step
info += f"\tActive Result File: {self.filename}\n"

# If there is no result file, this fails.
try:
nsets = int(self.nsets)
except MapdlRuntimeError as error:
self._mapdl.logger.debug(
f"Error when obtaining the number of sets:\n{error}"
)
nsets = "NA"

info += f"\tNumber of result sets: {nsets}\n"
info += f"\tCurrent load step: {self.load_step}\n"
info += f"\tCurrent sub step: {self.sub_step}\n"

if self._mapdl.parameters.routine == "POST1":
info += "\n\n" + self._mapdl.set("LIST")
try:
nlist = self._mapdl.set("LIST")
except MapdlRuntimeError as err:
if (
"An error occurred while attempting to open the results file"
in str(err)
):
self._mapdl.logger.debug(
f"List of steps could not be obtained due to error:\n{err}"
)
nlist = "Results file is not available"
else:
raise err

info += "\n\n" + nlist
else:
info += "\n\nEnable routine POST1 to see a table of available results"

Expand Down
7 changes: 6 additions & 1 deletion tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,10 @@ def is_exited(mapdl: Mapdl):

# we cannot connect.
# Kill the instance
mapdl.exit()
try:
mapdl.exit()
except Exception as e:
LOG.error(f"An error occurred when killing the instance:\n{str(e)}")

# Relaunching MAPDL
mapdl = launch_mapdl(
Expand All @@ -285,6 +288,8 @@ def is_exited(mapdl: Mapdl):
log_apdl=log_apdl(),
)

LOG.info("Successfully re-connected to MAPDL")

# Restoring the local configuration
mapdl._local = local_
mapdl._exited = False
Expand Down
13 changes: 8 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,9 @@ def requires_dependency(dependency: str):

# the following files are also generated by MAPDL gRPC:
# - "pymapdl.apdl": The APDL commands sent to MAPDL by PyMAPDL
# - "apdl.out" : MAPDL console output. Very likely only contains the output until connected.
# - "apdl.out" : MAPDL console output. Very likely only contains the output
# until connected.

################################################################
#
# Importing packages
Expand Down Expand Up @@ -230,14 +232,12 @@ def requires_dependency(dependency: str):

viz_interface.TESTING_MODE = True


################################################################
#
# Pytest configuration
# --------------------
#


# check if the user wants to permit pytest to start MAPDL
START_INSTANCE = get_start_instance()

Expand Down Expand Up @@ -558,7 +558,10 @@ def mapdl_console(request):
)

mapdl = launch_mapdl(
console_path, mode="console", log_apdl="pymapdl.apdl" if DEBUG_TESTING else None
console_path,
mode="console",
log_apdl="pymapdl.apdl" if DEBUG_TESTING else None,
loglevel="DEBUG" if DEBUG_TESTING else "ERROR",
)
from ansys.mapdl.core.mapdl_console import MapdlConsole

Expand Down Expand Up @@ -604,7 +607,7 @@ def mapdl(request, tmpdir_factory):
if ON_CI:
mapdl._local = ON_LOCAL # CI: override for testing

if mapdl.is_local:
if ON_LOCAL and mapdl.is_local:
assert Path(mapdl.directory) == Path(run_path)

# using yield rather than return here to be able to test exit
Expand Down
25 changes: 21 additions & 4 deletions tests/test_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ def db(mapdl):
)

mapdl.clear()
if mapdl.db.active or mapdl.db._stub is None:
mapdl.db.stop()

mapdl.db.start()
return mapdl.db

Expand Down Expand Up @@ -91,6 +94,9 @@ def test_database_start_stop(mapdl, cleared):
f"This MAPDL version ({mapdl_version}) docker image seems to not support DB, but local does."
)

if MapdlDb(mapdl).active:
MapdlDb(mapdl)._stop()

# verify it can be created twice
mapdl.prep7()
for _ in range(2):
Expand All @@ -111,6 +117,9 @@ def test_database_start_stop(mapdl, cleared):
with pytest.warns(UserWarning):
database.stop()

# Starting the database for the rest of the test session
mapdl.db.start()


def test_database_repr(db):
assert db._channel_str in str(db)
Expand Down Expand Up @@ -138,8 +147,8 @@ def test_clear(db):
def test__channel_str(db):
assert db._channel_str is not None
assert ":" in db._channel_str
assert re.search("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", db._channel_str)
assert re.search("\d{4,6}", db._channel_str)
assert re.search(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", db._channel_str)
assert re.search(r"\d{4,6}", db._channel_str)


def test_off_db(mapdl, cleared, db):
Expand Down Expand Up @@ -186,6 +195,10 @@ def test_repr(mapdl, cleared, db):

def gen_block(mapdl):
"""Generate nodes and elements in a simple block."""
from conftest import clear

clear(mapdl)

mapdl.block(0, 1, 0, 1, 0, 1)
mapdl.et(1, 186)
mapdl.esize(0.25)
Expand Down Expand Up @@ -226,8 +239,8 @@ def test_nodes_next(nodes):
def test_nodes_info(nodes):
assert nodes.info(1, DBDef.DB_SELECTED) == 1

@pytest.mark.parametrize("selected", [True, False])
@staticmethod
@pytest.mark.parametrize("selected", [True, False])
def test_nodes_num(nodes, selected):
assert nodes.num(selected=selected) == 425

Expand All @@ -250,7 +263,7 @@ def test_nodes_asarray(nodes):
assert np.allclose(angles, 0)

@staticmethod
def test_nodes_push(nodes):
def test_nodes_push(mapdl, nodes):
nnum = 100000
x, y, z, xang, yang, zang = 1, 5, 10, 30, 40, 50
nodes.push(nnum, x, y, z, xang, yang, zang)
Expand All @@ -265,6 +278,10 @@ def test_nodes_push(nodes):
with pytest.raises(ValueError, match="X and Y angles must be input"):
nodes.push(nnum, x, y, z, zang=1)

# this test changes the database, so let's restore it back
# as in `nodes` fixture.
gen_block(mapdl)


class Test_Elems(TestClass):

Expand Down
2 changes: 1 addition & 1 deletion tests/test_mapdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2219,7 +2219,7 @@ def test_inquire_invalid(mapdl, cleared):

def test_inquire_default(mapdl, cleared):
mapdl.title("heeeelloo")
assert Path(mapdl.directory) == Path(mapdl.inquire())
assert str(Path(mapdl.directory)) == str(Path(mapdl.inquire()))


def test_vwrite_error(mapdl, cleared):
Expand Down
17 changes: 14 additions & 3 deletions tests/test_post.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,10 @@ def test_repr(mapdl, cleared):
assert "Enable routine POST1 to see a table of available results" in repr_

mapdl.post1()
repr_ = mapdl.post_processing.__repr__()
assert "Enable routine POST1 to see a table of available results" not in repr_
assert mapdl.set("LIST") in repr_
assert (
"Enable routine POST1 to see a table of available results"
not in mapdl.post_processing.__repr__()
)


class Test_static_solve(TestClass):
Expand Down Expand Up @@ -770,6 +771,16 @@ def resume(mapdl, plastic_solve):
nsigfig = 10
mapdl.format("", "E", nsigfig + 9, nsigfig)

@staticmethod
def test_list_in_repr(mapdl, resume):
mapdl.finish()
assert "Enable routine POST1 to see a table of available results" in str(
mapdl.post_processing
)

mapdl.post1()
assert mapdl.set("LIST") in mapdl.post_processing.__str__()

@staticmethod
@pytest.mark.parametrize("comp", COMPONENT_STRESS_TYPE)
def test_nodal_plastic_component_strain(mapdl, resume, comp):
Expand Down
Loading

0 comments on commit 7b544b4

Please sign in to comment.