2 # This file is part of the GROMACS molecular simulation package.
4 # Copyright (c) 2019,2020, by the GROMACS development team, led by
5 # Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 # and including many others, as listed in the AUTHORS file in the
7 # top-level source directory and at http://www.gromacs.org.
9 # GROMACS is free software; you can redistribute it and/or
10 # modify it under the terms of the GNU Lesser General Public License
11 # as published by the Free Software Foundation; either version 2.1
12 # of the License, or (at your option) any later version.
14 # GROMACS is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 # Lesser General Public License for more details.
19 # You should have received a copy of the GNU Lesser General Public
20 # License along with GROMACS; if not, see
21 # http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 # If you want to redistribute modifications to GROMACS, please
25 # consider that scientific software is very special. Version
26 # control is crucial - bugs must be traceable. We will be happy to
27 # consider code for inclusion in the official distribution, but
28 # derived work must not be called official GROMACS. Details are found
29 # in the README & COPYING files - if they are missing, get the
30 # official version at http://www.gromacs.org.
32 # To help us fund GROMACS development, we humbly ask that you cite
33 # the research papers on the package. Check out http://www.gromacs.org.
35 """Reusable definitions for test modules.
37 Provides utilities and pytest fixtures for gmxapi and GROMACS tests.
39 To load these facilities in a pytest environment, set a `pytest_plugins`
40 variable in a conftest.py
41 (Reference https://docs.pytest.org/en/latest/writing_plugins.html#requiring-loading-plugins-in-a-test-module-or-conftest-file)
43 pytest_plugins = "gmxapi.testsupport"
45 .. seealso:: https://docs.pytest.org/en/latest/plugins.html#findpluginname
47 .. todo:: Consider moving this to a separate optional package.
56 from contextlib import contextmanager
58 from typing import Union
62 mpi_status = 'Test requires mpi4py managing 2 MPI ranks.'
65 from mpi4py import MPI
67 if not MPI.Is_initialized():
69 mpi_status += ' MPI is not initialized'
70 elif MPI.COMM_WORLD.Get_size() < 2:
72 mpi_status += ' MPI context is too small.'
75 mpi_status += ' mpi4py is not available.'
78 def pytest_configure(config):
79 config.addinivalue_line("markers", "withmpi_only: test requires mpi4py managing 2 MPI ranks.")
82 def pytest_runtest_setup(item):
83 # Handle the withmpi_only marker.
84 for _ in item.iter_markers(name='withmpi_only'):
86 pytest.skip(mpi_status)
87 # The API uses iteration because markers may be duplicated, but we only
88 # care about whether 'withmpi_only' occurs at all.
92 def pytest_addoption(parser):
93 """Add a command-line user option for the pytest invocation."""
98 choices=['always', 'never', 'success'],
99 help='Remove temporary directories "always", "never", or on "success".'
103 class RmOption(Enum):
104 """Enumerate allowable values of the --rm option."""
110 @pytest.fixture(scope='session')
111 def remove_tempdir(request) -> RmOption:
112 """pytest fixture to get access to the --rm CLI option."""
113 arg = request.config.getoption('--rm')
118 def scoped_chdir(dir):
119 oldpath = os.getcwd()
123 # If the `with` block using scoped_chdir produces an exception, it will
124 # be raised at this point in this function. We want the exception to
125 # propagate out of the `with` block, but first we want to restore the
126 # original working directory, so we skip `except` but provide a `finally`.
132 def _cleandir(remove_tempdir: Union[str, RmOption]):
133 """Context manager for a clean temporary working directory.
136 remove_tempdir (RmOption): whether to remove temporary directory "always",
137 "never", or on "success"
140 ValueError: if remove_tempdir value is not valid.
142 The context manager will issue a warning for each temporary directory that
145 if not isinstance(remove_tempdir, RmOption):
146 remove_tempdir = RmOption(remove_tempdir)
148 newpath = tempfile.mkdtemp()
151 shutil.rmtree(newpath)
154 warnings.warn('Temporary directory not removed: {}'.format(newpath))
156 # Initialize callback function reference
157 if remove_tempdir == RmOption.always:
163 with scoped_chdir(newpath):
165 # If we get to this line, the `with` block using _cleandir did not throw.
166 # Clean up the temporary directory unless the user specified `--rm never`.
167 # I.e. If the user specified `--rm success`, then we need to toggle from `warn` to `remove`.
168 if remove_tempdir != RmOption.never:
175 def cleandir(remove_tempdir: RmOption):
176 """Provide a clean temporary working directory for a test.
183 @pytest.mark.usefixtures("cleandir")
184 def test_cwd_starts_empty():
185 assert os.listdir(os.getcwd()) == []
186 with open("myfile", "w") as f:
189 def test_cwd_also_starts_empty(cleandir):
190 assert os.listdir(os.getcwd()) == []
191 assert os.path.abspath(os.getcwd()) == os.path.abspath(cleandir)
192 with open("myfile", "w") as f:
195 @pytest.mark.usefixtures("cleandir")
196 class TestDirectoryInit(object):
197 def test_cwd_starts_empty(self):
198 assert os.listdir(os.getcwd()) == []
199 with open("myfile", "w") as f:
202 def test_cwd_also_starts_empty(self):
203 assert os.listdir(os.getcwd()) == []
204 with open("myfile", "w") as f:
207 Ref: https://docs.pytest.org/en/latest/fixture.html#using-fixtures-from-classes-modules-or-projects
209 with _cleandir(remove_tempdir) as newdir:
214 """Represent the detected GROMACS installation."""
216 # Try to use package resources to locate the "gmx" binary wrapper.
218 from importlib.resources import open_text
219 with open_text('gmxapi', 'gmxconfig.json') as textfile:
220 config = json.load(textfile)
221 gmxbindir = config.get('gmx_bindir', None)
222 command = config.get('gmx_executable', None)
225 # A backport of importlib.resources is available as importlib_resources
226 # with a somewhat different interface.
227 from importlib_resources import files, as_file
229 source = files('gmxapi').joinpath('gmxconfig.json')
230 with as_file(source) as gmxconfig:
231 with open(gmxconfig, 'r') as fp:
232 config = json.load(fp)
233 gmxbindir = config.get('gmx_bindir', None)
234 command = config.get('gmx_executable', None)
239 # TODO: Remove fall-back when we can rely on gmxconfig.json via importlib.resources in Py 3.7+.
240 allowed_command_names = ['gmx', 'gmx_mpi']
241 for command_name in allowed_command_names:
242 if command is not None:
244 command = shutil.which(command_name)
246 gmxbindir = os.getenv('GMXBIN')
247 if gmxbindir is None:
248 gromacsdir = os.getenv('GROMACS_DIR')
249 if gromacsdir is not None and gromacsdir != '':
250 gmxbindir = os.path.join(gromacsdir, 'bin')
251 if gmxbindir is None:
252 gmxapidir = os.getenv('gmxapi_DIR')
253 if gmxapidir is not None and gmxapidir != '':
254 gmxbindir = os.path.join(gmxapidir, 'bin')
255 if gmxbindir is not None:
256 gmxbindir = os.path.abspath(gmxbindir)
257 command = shutil.which(command_name, path=gmxbindir)
259 self._command = command
260 self._bindir = gmxbindir
272 @pytest.fixture(scope='session')
274 command = _gmx.command()
276 message = "Tests need 'gmx' command line tool, but could not find it on the path."
277 raise RuntimeError(message)
279 assert os.access(command, os.X_OK)
280 except Exception as E:
281 raise RuntimeError('"{}" is not an executable gmx wrapper program'.format(command)) from E