2 # This file is part of the GROMACS molecular simulation package.
4 # Copyright (c) 2019, 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 """Configuration and fixtures for pytest."""
48 """Provide a clean temporary working directory for a test.
55 @pytest.mark.usefixtures("cleandir")
56 def test_cwd_starts_empty():
57 assert os.listdir(os.getcwd()) == []
58 with open("myfile", "w") as f:
61 def test_cwd_also_starts_empty(cleandir):
62 assert os.listdir(os.getcwd()) == []
63 assert os.path.abspath(os.getcwd()) == os.path.abspath(cleandir)
64 with open("myfile", "w") as f:
67 @pytest.mark.usefixtures("cleandir")
68 class TestDirectoryInit(object):
69 def test_cwd_starts_empty(self):
70 assert os.listdir(os.getcwd()) == []
71 with open("myfile", "w") as f:
74 def test_cwd_also_starts_empty(self):
75 assert os.listdir(os.getcwd()) == []
76 with open("myfile", "w") as f:
79 Ref: https://docs.pytest.org/en/latest/fixture.html#using-fixtures-from-classes-modules-or-projects
82 newpath = tempfile.mkdtemp()
86 # TODO: Allow override to prevent removal of the temporary directory
87 shutil.rmtree(newpath)
90 @pytest.fixture(scope='session')
92 # TODO: (#2896) Find a more canonical way to identify the GROMACS commandline wrapper binary.
93 # We should be able to get the GMXRC contents and related hints from a gmxapi
94 # package resource or from module attributes of a ``gromacs`` stub package.
95 allowed_command_names = ['gmx', 'gmx_mpi']
97 for command_name in allowed_command_names:
98 if command is not None:
100 command = shutil.which(command_name)
102 gmxbindir = os.getenv('GMXBIN')
103 if gmxbindir is None:
104 gromacsdir = os.getenv('GROMACS_DIR')
105 if gromacsdir is not None and gromacsdir != '':
106 gmxbindir = os.path.join(gromacsdir, 'bin')
107 if gmxbindir is None:
108 gmxapidir = os.getenv('gmxapi_DIR')
109 if gmxapidir is not None and gmxapidir != '':
110 gmxbindir = os.path.join(gmxapidir, 'bin')
111 if gmxbindir is not None:
112 gmxbindir = os.path.abspath(gmxbindir)
113 command = shutil.which(command_name, path=gmxbindir)
115 message = "Tests need 'gmx' command line tool, but could not find it on the path."
116 raise RuntimeError(message)
118 assert os.access(command, os.X_OK)
119 except Exception as E:
120 raise RuntimeError('"{}" is not an executable gmx wrapper program'.format(command)) from E
124 @pytest.fixture(scope='class')
125 def spc_water_box(gmxcli):
126 """Provide a TPR input file for a simple simulation.
128 Prepare the MD input in a freshly created working directory.
132 # TODO: (#2896) Fetch MD input from package / library data.
134 # import pkg_resources
135 # # Note: importing pkg_resources means setuptools is required for running this test.
136 # # Get or build TPR file from data bundled via setup(package_data=...)
137 # # Ref https://setuptools.readthedocs.io/en/latest/setuptools.html#including-data-files
138 # from gmx.data import tprfilename
140 tempdir = tempfile.mkdtemp()
142 testdir = os.path.dirname(__file__)
143 with open(os.path.join(testdir, 'testdata.json'), 'r') as fh:
144 testdata = json.load(fh)
146 # TODO: (#2756) Don't rely on so many automagical behaviors (as described in comments below)
148 structurefile = os.path.join(tempdir, 'structure.gro')
149 # We let `gmx solvate` use the default solvent. Otherwise, we would do
150 # gro_input = testdata['solvent_structure']
151 # with open(structurefile, 'w') as fh:
152 # fh.write('\n'.join(gro_input))
155 topfile = os.path.join(tempdir, 'topology.top')
156 top_input = testdata['solvent_topology']
157 # `gmx solvate` will append a line to the provided file with the molecule count,
158 # so we strip the last line from the input topology.
159 with open(topfile, 'w') as fh:
160 fh.write('\n'.join(top_input[:-1]))
163 solvate = gmx.commandline_operation(gmxcli,
164 arguments=['solvate', '-box', '5', '5', '5'],
165 # We use the default solvent instead of specifying one.
166 # input_files={'-cs': structurefile},
167 output_files={'-p': topfile,
171 if solvate.output.returncode.result() != 0:
172 logging.debug(solvate.output.erroroutput.result())
173 raise RuntimeError('solvate failed in spc_water_box testing fixture.')
175 mdp_input = [('integrator', 'md'),
176 ('cutoff-scheme', 'Verlet'),
181 ('tcoupl', 'v-rescale'),
182 ('tc-grps', 'System'),
185 mdp_input = '\n'.join([' = '.join([str(item) for item in kvpair]) for kvpair in mdp_input])
186 mdpfile = os.path.join(tempdir, 'md.mdp')
187 with open(mdpfile, 'w') as fh:
190 tprfile = os.path.join(tempdir, 'topol.tpr')
191 # We don't use mdout_mdp, but if we don't specify it to grompp,
192 # it will be created in the current working directory.
193 mdout_mdp = os.path.join(tempdir, 'mdout.mdp')
195 grompp = gmx.commandline_operation(gmxcli, 'grompp',
198 '-p': solvate.output.file['-p'],
199 '-c': solvate.output.file['-o'],
202 output_files={'-o': tprfile})
203 tprfilename = grompp.output.file['-o'].result()
204 if grompp.output.returncode.result() != 0:
205 logging.debug(grompp.output.erroroutput.result())
206 raise RuntimeError('grompp failed in spc_water_box testing fixture.')
208 # TODO: more inspection of grompp errors...
209 assert os.path.exists(tprfilename)
213 # Note: these lines are not executed (and tempdir is not removed) if there
214 # are exceptions before `yield`
215 # TODO: Allow override to prevent removal of the temporary directory
216 shutil.rmtree(tempdir)