More Python testing infrastructure for gmxapi.
[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     command = shutil.which('gmx')
97     if command is None:
98         gmxbindir = os.getenv('GMXBIN')
99         if gmxbindir is None:
100             gromacsdir = os.getenv('GROMACS_DIR')
101             if gromacsdir is not None and gromacsdir != '':
102                 gmxbindir = os.path.join(gromacsdir, 'bin')
103         if gmxbindir is None:
104             gmxapidir = os.getenv('gmxapi_DIR')
105             if gmxapidir is not None and gmxapidir != '':
106                 gmxbindir = os.path.join(gmxapidir, 'bin')
107         if gmxbindir is not None:
108             gmxbindir = os.path.abspath(gmxbindir)
109             command = shutil.which('gmx', path=gmxbindir)
110         else:
111             message = "Tests need 'gmx' command line tool, but could not find it on the path."
112             raise RuntimeError(message)
113     if command is None:
114         message = "Tests need 'gmx' command line tool, but could not find it on the path."
115         raise RuntimeError(message)
116     try:
117         assert os.access(command, os.X_OK)
118     except Exception as E:
119         raise RuntimeError('"{}" is not an executable gmx wrapper program') from E
120     yield command
121
122
123 @pytest.fixture(scope='class')
124 def spc216(gmxcli):
125     """Provide a TPR input file for a simple simulation.
126
127     Prepare the MD input in a freshly created working directory.
128     """
129     import gmxapi as gmx
130
131     # TODO: (#2896) Fetch MD input from package / library data.
132     # Example:
133     #     import pkg_resources
134     #     # Note: importing pkg_resources means setuptools is required for running this test.
135     #     # Get or build TPR file from data bundled via setup(package_data=...)
136     #     # Ref https://setuptools.readthedocs.io/en/latest/setuptools.html#including-data-files
137     #     from gmx.data import tprfilename
138
139     tempdir = tempfile.mkdtemp()
140
141     testdir = os.path.dirname(__file__)
142     with open(os.path.join(testdir, 'testdata.json'), 'r') as fh:
143         testdata = json.load(fh)
144
145     # TODO: (#2756) Don't rely on so many automagical behaviors (as described in comments below)
146
147     structurefile = os.path.join(tempdir, 'structure.gro')
148     # We let `gmx solvate` use the default solvent. Otherwise, we would do
149     #     gro_input = testdata['solvent_structure']
150     #     with open(structurefile, 'w') as fh:
151     #         fh.write('\n'.join(gro_input))
152     #         fh.write('\n')
153
154     topfile = os.path.join(tempdir, 'topology.top')
155     top_input = testdata['solvent_topology']
156     # `gmx solvate` will append a line to the provided file with the molecule count,
157     # so we strip the last line from the input topology.
158     with open(topfile, 'w') as fh:
159         fh.write('\n'.join(top_input[:-1]))
160         fh.write('\n')
161
162     solvate = gmx.commandline_operation(gmxcli,
163                                         arguments=['solvate', '-box', '5', '5', '5'],
164                                         # We use the default solvent instead of specifying one.
165                                         # input_files={'-cs': structurefile},
166                                         output_files={'-p': topfile,
167                                                       '-o': structurefile,
168                                                       }
169                                         )
170     assert solvate.output.returncode.result() == 0
171
172     mdp_input = [('integrator', 'md'),
173                  ('cutoff-scheme', 'Verlet'),
174                  ('nsteps', 1000),
175                  ('nstxout', 100),
176                  ('nstvout', 100),
177                  ('nstfout', 100),
178                  ('tcoupl', 'v-rescale'),
179                  ('tc-grps', 'System'),
180                  ('tau-t', 1),
181                  ('ref-t', 298)]
182     mdp_input = '\n'.join([' = '.join([str(item) for item in kvpair]) for kvpair in mdp_input])
183     mdpfile = os.path.join(tempdir, 'md.mdp')
184     with open(mdpfile, 'w') as fh:
185         fh.write('\n'.join(mdp_input))
186         fh.write('\n')
187     tprfile = os.path.join(tempdir, 'topol.tpr')
188     # We don't use mdout_mdp, but if we don't specify it to grompp,
189     # it will be created in the current working directory.
190     mdout_mdp = os.path.join(tempdir, 'mdout.mdp')
191
192     grompp = gmx.commandline_operation(gmxcli, 'grompp',
193                                        input_files={
194                                            '-f': mdpfile,
195                                            '-p': solvate.output.file['-p'],
196                                            '-c': solvate.output.file['-o'],
197                                            '-po': mdout_mdp,
198                                        },
199                                        output_files={'-o': tprfile})
200     tprfilename = grompp.output.file['-o'].result()
201     if grompp.output.returncode.result() != 0:
202         logging.debug(grompp.output.erroroutput.result())
203         raise RuntimeError('grompp failed in spc216 testing fixture.')
204
205     # TODO: more inspection of grompp errors...
206     assert os.path.exists(tprfilename)
207     yield tprfilename
208
209     # Clean up.
210     # Note: these lines are not executed (and tempdir is not removed) if there
211     # are exceptions before `yield`
212     # TODO: Allow override to prevent removal of the temporary directory
213     shutil.rmtree(tempdir)