/
test_notebook.py
173 lines (142 loc) · 5.53 KB
/
test_notebook.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import os
import glob
import subprocess
try:
from unittest.mock import patch
except ImportError:
# py2
from mock import patch
from notebook import jstest
import platform
import nb_conda_kernels.install
IS_WIN = "Windows" in platform.system()
here = os.path.dirname(__file__)
# global npm installs are bad, add the local node_modules to the path
os.environ["PATH"] = os.pathsep.join([
os.environ["PATH"],
os.path.abspath(os.path.join(here, "node_modules", ".bin"))
])
TEST_LOG = ".jupyter.jstest.log"
class NBCondaKernelsTestController(jstest.JSController):
""" Javascript test subclass that installs widget nbextension in test
environment
"""
def __init__(self, section, *args, **kwargs):
extra_args = kwargs.pop('extra_args', None)
super(NBCondaKernelsTestController, self).__init__(section, *args, **kwargs)
self.xunit = True
test_cases = glob.glob(os.path.join(here, 'js', 'test_notebook_*.js'))
js_test_dir = jstest.get_js_test_dir()
includes = [
os.path.join(js_test_dir, 'util.js')
] + glob.glob(os.path.join(here, 'js', '_*.js'))
self.cmd = [
'casperjs', 'test',
'--includes={}'.format(",".join(includes)),
'--engine={}'.format(self.engine)
] + test_cases
if extra_args is not None:
self.cmd = self.cmd + extra_args
if IS_WIN:
self.cmd[0] = "{}.cmd".format(self.cmd[0])
def launch(self, buffer_output=False, capture_output=False):
# print('*** ENV:', self.env) # dbg
# print('*** CMD:', self.cmd) # dbg
env = os.environ.copy()
env.update(self.env)
if buffer_output:
capture_output = True
self.stdout_capturer = c = jstest.StreamCapturer(
echo=not buffer_output)
c.start()
stdout = c.writefd if capture_output else None
# stderr = subprocess.STDOUT if capture_output else None
self.process = subprocess.Popen(
self.cmd,
stderr=subprocess.PIPE,
stdout=stdout,
env=env)
def wait(self):
self.process.communicate()
self.stdout_capturer.halt()
self.stdout = self.stdout_capturer.get_buffer()
return self.process.returncode
# copy pasta from...
# https://github.com/jupyter/notebook/blob/master/notebook/jstest.py#L234
def setup(self):
self.ipydir = jstest.TemporaryDirectory()
self.config_dir = jstest.TemporaryDirectory()
self.nbdir = jstest.TemporaryDirectory()
self.home = jstest.TemporaryDirectory()
self.env = {
'HOME': self.home.name,
'JUPYTER_CONFIG_DIR': self.config_dir.name,
'IPYTHONDIR': self.ipydir.name,
}
self.dirs.append(self.ipydir)
self.dirs.append(self.home)
self.dirs.append(self.config_dir)
self.dirs.append(self.nbdir)
os.makedirs(os.path.join(self.nbdir.name,
os.path.join(u'sub dir1', u'sub dir 1a')))
os.makedirs(os.path.join(self.nbdir.name,
os.path.join(u'sub dir2', u'sub dir 1b')))
if self.xunit:
self.add_xunit()
# If a url was specified, use that for the testing.
if self.url:
try:
alive = jstest.requests.get(self.url).status_code == 200
except:
alive = False
if alive:
self.cmd.append("--url=%s" % self.url)
else:
raise Exception('Could not reach "%s".' % self.url)
else:
# start the ipython notebook, so we get the port number
self.server_port = 0
self._init_server()
if self.server_port:
self.cmd.append('--url=http://localhost:%i%s' % (
self.server_port, self.base_url))
else:
# don't launch tests if the server didn't start
self.cmd = [
jstest.sys.executable, '-c', 'raise SystemExit(1)']
def add_xunit(self):
""" Hack the setup in the middle (after paths, before server)
"""
super(NBCondaKernelsTestController, self).add_xunit()
# ensure the system-of-interest is installed and enabled!
with patch.dict(os.environ, self.env):
nb_conda_kernels.install.install(
prefix=os.environ.get("CONDA_ENV_PATH",
os.environ.get("CONDA_DEFAULT_ENV")),
enable=True,
verbose=True)
def cleanup(self):
if hasattr(self, "stream_capturer"):
captured = self.stream_capturer.get_buffer().decode(
'utf-8', 'replace')
with open(TEST_LOG, "a+") as fp:
fp.write("-----------------------\n{} results:\n{}\n".format(
self.section,
self.server_command))
fp.write(captured)
super(NBCondaKernelsTestController, self).cleanup()
def prepare_controllers(options):
"""Monkeypatched prepare_controllers for running widget js tests
instead of notebook js tests
"""
if options.testgroups:
groups = options.testgroups
else:
groups = ['']
return [NBCondaKernelsTestController(g, extra_args=options.extra_args)
for g in groups], []
def test_notebook():
with patch.object(jstest, 'prepare_controllers', prepare_controllers):
jstest.main()
if __name__ == '__main__':
test_notebook()