Merge Konrad Hinsen and Fernando Perez's installation-testing scripts
[swc-setup-installation-test.git] / workshop_checklist.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """Minimal test script to check for modules needed in python workshop.
4
5 Execute this code at the command line by typing:
6
7 python workshop_checklist.py
8
9 How to get a command line:
10
11 - On OSX run this with the Terminal application.
12
13 - On Windows, go to the Start menu, select 'Run' and type 'cmd' (without the
14 quotes) to run the cmd.exe Windows Command Prompt.
15
16 Run the script and follow the instructions it prints at the end.
17 """
18
19 ##############################################################################
20 # Config here
21
22 # Modules whose imports we're going to validate
23 MODULES = ['IPython',
24            'numpy',
25            'scipy',
26            'scipy.io',
27            'matplotlib','pylab',
28            # 'sympy', 'Cython', 'networkx', 'mayavi.mlab',
29            # 'setuptools',
30            ]
31
32 ##############################################################################
33 # Code begins
34
35 # Standard library imports
36 import glob
37 import os
38 import platform
39 import sys
40
41 from StringIO import StringIO
42
43 # Third-party imports
44 import nose
45 import nose.tools as nt
46
47 #-----------------------------------------------------------------------------
48 # Generic utility functions
49 def sys_info():
50     """Summarize some info about the system"""
51
52     print '=================='
53     print 'System information'
54     print '=================='
55     print 'os.name      :',os.name
56     try:
57         print 'os.uname     :',os.uname()
58     except:
59         pass
60     print 'platform     :',sys.platform
61     print 'platform+    :',platform.platform()
62     print 'prefix       :',sys.prefix
63     print 'exec_prefix  :',sys.exec_prefix
64     print 'executable   :',sys.executable
65     print 'version_info :',sys.version_info
66     print 'version      :',sys.version
67     print '=================='
68
69
70 #-----------------------------------------------------------------------------
71 # Tests
72
73 def check_import(mname):
74     "Check that the given name imports correctly"
75     exec "import %s as m" % mname
76
77     if mname == 'matplotlib':
78         m.use('Agg')
79         m.rcParams['figure.subplot.top']= 0.85
80     
81     try:
82         vinfo = m.__version__
83     except AttributeError:
84         vinfo = '*no info*'
85
86     print 'MOD: %s, version: %s' % (mname,vinfo)
87
88
89 # Test generators are best written without docstrings, because nose can then
90 # show the parameters being used.
91 def test_imports():
92     for mname in MODULES:
93         yield check_import, mname
94
95
96 # Test generator, don't put a docstring in it
97 def test_loadtxt():
98     import numpy as np
99     import numpy.testing as npt
100
101     # Examples taken from the loadtxt docstring
102     array = np.array
103     
104     c = StringIO("0 1\n2 3")
105     a1 = np.loadtxt(c)
106     a2 = np.array([[ 0.,  1.],
107                    [ 2.,  3.]])
108     yield npt.assert_array_equal,a1,a2
109
110     d = StringIO("M 21 72\nF 35 58")
111     a1 = np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
112                          'formats': ('S1', 'i4', 'f4')})
113     
114     a2 = np.array([('M', 21, 72.0), ('F', 35, 58.0)],
115                   dtype=[('gender', '|S1'), ('age', '<i4'), ('weight', '<f4')])
116     yield npt.assert_array_equal,a1,a2
117
118     c = StringIO("1,0,2\n3,0,4")
119     x,y = np.loadtxt(c, delimiter=',', usecols=(0,2), unpack=True)
120     yield npt.assert_array_equal,x,np.array([ 1.,  3.])
121     yield npt.assert_array_equal,y,np.array([ 2.,  4.])
122
123
124 def test_plot():
125     "Simple plot generation."
126     from matplotlib import pyplot as plt
127     plt.figure()
128     plt.plot([1,2,3])
129     plt.xlabel('some numbers')
130     plt.savefig('tmp_test_plot.png')
131
132
133 def test_plot_math():
134     "Plots with math"
135     from matplotlib import pyplot as plt
136     plt.figure()
137     plt.plot([1,2,3],label='data')
138     t=(r'And X is $\sum_{i=0}^\infty \gamma_i + \frac{\alpha^{i^2}}{\gamma}'
139        r'+ \cos(2 \theta^2)$')
140     plt.title(t)
141     plt.legend()
142     plt.grid()
143     plt.savefig('tmp_test_plot_math.png')
144
145
146 def cleanup_pngs():
147     """Remove temporary pngs made by our plotting tests"""
148
149     for f in glob.glob('tmp_test_plot*.png'):
150         try:
151             os.remove(f)
152         except OSError:
153             print '*** Error: could not remove file',f
154             
155
156 #-----------------------------------------------------------------------------
157 # Main routine, executed when this file is run as a script
158 #
159 if __name__ == '__main__':
160     print "Running tests:"
161     # This call form is ipython-friendly
162     nose.runmodule(argv=[__file__,'-vvs'],
163                    exit=False)
164     print """
165 ***************************************************************************
166                            TESTS FINISHED
167 ***************************************************************************
168
169 If the printout above did not finish in 'OK' but instead says 'FAILED', copy
170 and send the *entire* output (all info above and summary below) to the
171 instructor for help.
172 """
173     sys_info()