Make gmxcli pytest fixture more robust.
[alexxy/gromacs.git] / python_packaging / src / test / conftest.py
1 #
2 # This file is part of the GROMACS molecular simulation package.
3 #
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.
8 #
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.
13 #
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.
18 #
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.
23 #
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.
31 #
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.
34
35 """Configuration and fixtures for pytest."""
36
37 import json
38 import logging
39 import os
40 import shutil
41 import tempfile
42
43 import pytest
44
45
46
47 @pytest.fixture()
48 def cleandir():
49     """Provide a clean temporary working directory for a test.
50
51     Example usage:
52
53         import os
54         import pytest
55
56         @pytest.mark.usefixtures("cleandir")
57         def test_cwd_starts_empty():
58             assert os.listdir(os.getcwd()) == []
59             with open("myfile", "w") as f:
60                 f.write("hello")
61
62         def test_cwd_also_starts_empty(cleandir):
63             assert os.listdir(os.getcwd()) == []
64             assert os.path.abspath(os.getcwd()) == os.path.abspath(cleandir)
65             with open("myfile", "w") as f:
66                 f.write("hello")
67
68         @pytest.mark.usefixtures("cleandir")
69         class TestDirectoryInit(object):
70             def test_cwd_starts_empty(self):
71                 assert os.listdir(os.getcwd()) == []
72                 with open("myfile", "w") as f:
73                     f.write("hello")
74
75             def test_cwd_also_starts_empty(self):
76                 assert os.listdir(os.getcwd()) == []
77                 with open("myfile", "w") as f:
78                     f.write("hello")
79
80     Ref: https://docs.pytest.org/en/latest/fixture.html#using-fixtures-from-classes-modules-or-projects
81     """
82     oldpath = os.getcwd()
83     newpath = tempfile.mkdtemp()
84     os.chdir(newpath)
85     yield newpath
86     os.chdir(oldpath)
87     # TODO: Allow override to prevent removal of the temporary directory
88     shutil.rmtree(newpath)
89
90
91 @pytest.fixture(scope='session')
92 def gmxcli():
93     # TODO: (#2896) Find a more canonical way to identify the GROMACS commandline wrapper binary.
94     #  We should be able to get the GMXRC contents and related hints from a gmxapi
95     #  package resource or from module attributes of a ``gromacs`` stub package.
96     allowed_command_names = ['gmx', 'gmx_mpi']
97     command = None
98     for command_name in allowed_command_names:
99         if command is not None:
100             break
101         command = shutil.which(command_name)
102         if command is None:
103             gmxbindir = os.getenv('GMXBIN')
104             if gmxbindir is None:
105                 gromacsdir = os.getenv('GROMACS_DIR')
106                 if gromacsdir is not None and gromacsdir != '':
107                     gmxbindir = os.path.join(gromacsdir, 'bin')
108             if gmxbindir is None:
109                 gmxapidir = os.getenv('gmxapi_DIR')
110                 if gmxapidir is not None and gmxapidir != '':
111                     gmxbindir = os.path.join(gmxapidir, 'bin')
112             if gmxbindir is not None:
113                 gmxbindir = os.path.abspath(gmxbindir)
114                 command = shutil.which(command_name, path=gmxbindir)
115     if command is None:
116         message = "Tests need 'gmx' command line tool, but could not find it on the path."
117         raise RuntimeError(message)
118     try:
119         assert os.access(command, os.X_OK)
120     except Exception as E:
121         raise RuntimeError('"{}" is not an executable gmx wrapper program'.format(command)) from E
122     yield command
123
124
125 @pytest.fixture(scope='class')
126 def spc_water_box(gmxcli):
127     """Provide a TPR input file for a simple simulation.
128
129     Prepare the MD input in a freshly created working directory.
130     """
131     import gmxapi as gmx
132
133     # TODO: (#2896) Fetch MD input from package / library data.
134     # Example:
135     #     import pkg_resources
136     #     # Note: importing pkg_resources means setuptools is required for running this test.
137     #     # Get or build TPR file from data bundled via setup(package_data=...)
138     #     # Ref https://setuptools.readthedocs.io/en/latest/setuptools.html#including-data-files
139     #     from gmx.data import tprfilename
140
141     tempdir = tempfile.mkdtemp()
142
143     testdir = os.path.dirname(__file__)
144     with open(os.path.join(testdir, 'testdata.json'), 'r') as fh:
145         testdata = json.load(fh)
146
147     # TODO: (#2756) Don't rely on so many automagical behaviors (as described in comments below)
148
149     structurefile = os.path.join(tempdir, 'structure.gro')
150     # We let `gmx solvate` use the default solvent. Otherwise, we would do
151     #     gro_input = testdata['solvent_structure']
152     #     with open(structurefile, 'w') as fh:
153     #         fh.write('\n'.join(gro_input))
154     #         fh.write('\n')
155
156     topfile = os.path.join(tempdir, 'topology.top')
157     top_input = testdata['solvent_topology']
158     # `gmx solvate` will append a line to the provided file with the molecule count,
159     # so we strip the last line from the input topology.
160     with open(topfile, 'w') as fh:
161         fh.write('\n'.join(top_input[:-1]))
162         fh.write('\n')
163
164     solvate = gmx.commandline_operation(gmxcli,
165                                         arguments=['solvate', '-box', '5', '5', '5'],
166                                         # We use the default solvent instead of specifying one.
167                                         # input_files={'-cs': structurefile},
168                                         output_files={'-p': topfile,
169                                                       '-o': structurefile,
170                                                       }
171                                         )
172     if solvate.output.returncode.result() != 0:
173         logging.debug(solvate.output.erroroutput.result())
174         raise RuntimeError('solvate failed in spc_water_box testing fixture.')
175
176     mdp_input = [('integrator', 'md'),
177                  ('cutoff-scheme', 'Verlet'),
178                  ('nsteps', 2),
179                  ('nstxout', 1),
180                  ('nstvout', 1),
181                  ('nstfout', 1),
182                  ('tcoupl', 'v-rescale'),
183                  ('tc-grps', 'System'),
184                  ('tau-t', 1),
185                  ('ref-t', 298)]
186     mdp_input = '\n'.join([' = '.join([str(item) for item in kvpair]) for kvpair in mdp_input])
187     mdpfile = os.path.join(tempdir, 'md.mdp')
188     with open(mdpfile, 'w') as fh:
189         fh.write(mdp_input)
190         fh.write('\n')
191     tprfile = os.path.join(tempdir, 'topol.tpr')
192     # We don't use mdout_mdp, but if we don't specify it to grompp,
193     # it will be created in the current working directory.
194     mdout_mdp = os.path.join(tempdir, 'mdout.mdp')
195
196     grompp = gmx.commandline_operation(gmxcli, 'grompp',
197                                        input_files={
198                                            '-f': mdpfile,
199                                            '-p': solvate.output.file['-p'],
200                                            '-c': solvate.output.file['-o'],
201                                            '-po': mdout_mdp,
202                                        },
203                                        output_files={'-o': tprfile})
204     tprfilename = grompp.output.file['-o'].result()
205     if grompp.output.returncode.result() != 0:
206         logging.debug(grompp.output.erroroutput.result())
207         raise RuntimeError('grompp failed in spc_water_box testing fixture.')
208
209     # TODO: more inspection of grompp errors...
210     assert os.path.exists(tprfilename)
211     yield tprfilename
212
213     # Clean up.
214     # Note: these lines are not executed (and tempdir is not removed) if there
215     # are exceptions before `yield`
216     # TODO: Allow override to prevent removal of the temporary directory
217     shutil.rmtree(tempdir)