Merge branch release-2019 into master
[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 @pytest.fixture()
47 def cleandir():
48     """Provide a clean temporary working directory for a test.
49
50     Example usage:
51
52         import os
53         import pytest
54
55         @pytest.mark.usefixtures("cleandir")
56         def test_cwd_starts_empty():
57             assert os.listdir(os.getcwd()) == []
58             with open("myfile", "w") as f:
59                 f.write("hello")
60
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:
65                 f.write("hello")
66
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:
72                     f.write("hello")
73
74             def test_cwd_also_starts_empty(self):
75                 assert os.listdir(os.getcwd()) == []
76                 with open("myfile", "w") as f:
77                     f.write("hello")
78
79     Ref: https://docs.pytest.org/en/latest/fixture.html#using-fixtures-from-classes-modules-or-projects
80     """
81     oldpath = os.getcwd()
82     newpath = tempfile.mkdtemp()
83     os.chdir(newpath)
84     yield newpath
85     os.chdir(oldpath)
86     # TODO: Allow override to prevent removal of the temporary directory
87     shutil.rmtree(newpath)
88
89
90 @pytest.fixture(scope='session')
91 def gmxcli():
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']
96     command = None
97     for command_name in allowed_command_names:
98         if command is not None:
99             break
100         command = shutil.which(command_name)
101         if command is None:
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)
114     if command is None:
115         message = "Tests need 'gmx' command line tool, but could not find it on the path."
116         raise RuntimeError(message)
117     try:
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
121     yield command
122
123
124 @pytest.fixture(scope='class')
125 def spc_water_box(gmxcli):
126     """Provide a TPR input file for a simple simulation.
127
128     Prepare the MD input in a freshly created working directory.
129     """
130     import gmxapi as gmx
131
132     # TODO: (#2896) Fetch MD input from package / library data.
133     # Example:
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
139
140     tempdir = tempfile.mkdtemp()
141
142     testdir = os.path.dirname(__file__)
143     with open(os.path.join(testdir, 'testdata.json'), 'r') as fh:
144         testdata = json.load(fh)
145
146     # TODO: (#2756) Don't rely on so many automagical behaviors (as described in comments below)
147
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))
153     #         fh.write('\n')
154
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]))
161         fh.write('\n')
162
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,
168                                                       '-o': structurefile,
169                                                       }
170                                         )
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.')
174
175     mdp_input = [('integrator', 'md'),
176                  ('cutoff-scheme', 'Verlet'),
177                  ('nsteps', 2),
178                  ('nstxout', 1),
179                  ('nstvout', 1),
180                  ('nstfout', 1),
181                  ('tcoupl', 'v-rescale'),
182                  ('tc-grps', 'System'),
183                  ('tau-t', 1),
184                  ('ref-t', 298)]
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:
188         fh.write(mdp_input)
189         fh.write('\n')
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')
194
195     grompp = gmx.commandline_operation(gmxcli, 'grompp',
196                                        input_files={
197                                            '-f': mdpfile,
198                                            '-p': solvate.output.file['-p'],
199                                            '-c': solvate.output.file['-o'],
200                                            '-po': mdout_mdp,
201                                        },
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.')
207
208     # TODO: more inspection of grompp errors...
209     assert os.path.exists(tprfilename)
210     yield tprfilename
211
212     # Clean up.
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)