##// END OF EJS Templates
Merge pull request #2844 from gregcaporaso/issue-2732...
Thomas Kluyver -
r9306:e8e6d482 merge
parent child Browse files
Show More
@@ -1,291 +1,305 b''
1 """Various display related classes.
1 """Various display related classes.
2
2
3 Authors : MinRK, gregcaporaso, dannystaple
3 Authors : MinRK, gregcaporaso, dannystaple
4 """
4 """
5 import urllib
5 import urllib
6
6
7 from os.path import exists, isfile, splitext, abspath, join, isdir
7 from os.path import exists, isfile, splitext, abspath, join, isdir
8 from os import walk
8 from os import walk, sep
9
9
10
10
11 class YouTubeVideo(object):
11 class YouTubeVideo(object):
12 """Class for embedding a YouTube Video in an IPython session, based on its video id.
12 """Class for embedding a YouTube Video in an IPython session, based on its video id.
13
13
14 e.g. to embed the video on this page:
14 e.g. to embed the video on this page:
15
15
16 http://www.youtube.com/watch?v=foo
16 http://www.youtube.com/watch?v=foo
17
17
18 you would do:
18 you would do:
19
19
20 vid = YouTubeVideo("foo")
20 vid = YouTubeVideo("foo")
21 display(vid)
21 display(vid)
22
22
23 To start from 30 seconds:
23 To start from 30 seconds:
24
24
25 vid = YouTubeVideo("abc", start=30)
25 vid = YouTubeVideo("abc", start=30)
26 display(vid)
26 display(vid)
27
27
28 To calculate seconds from time as hours, minutes, seconds use:
28 To calculate seconds from time as hours, minutes, seconds use:
29 start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
29 start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
30
30
31 Other parameters can be provided as documented at
31 Other parameters can be provided as documented at
32 https://developers.google.com/youtube/player_parameters#parameter-subheader
32 https://developers.google.com/youtube/player_parameters#parameter-subheader
33 """
33 """
34
34
35 def __init__(self, id, width=400, height=300, **kwargs):
35 def __init__(self, id, width=400, height=300, **kwargs):
36 self.id = id
36 self.id = id
37 self.width = width
37 self.width = width
38 self.height = height
38 self.height = height
39 self.params = kwargs
39 self.params = kwargs
40
40
41 def _repr_html_(self):
41 def _repr_html_(self):
42 """return YouTube embed iframe for this video id"""
42 """return YouTube embed iframe for this video id"""
43 if self.params:
43 if self.params:
44 params = "?" + urllib.urlencode(self.params)
44 params = "?" + urllib.urlencode(self.params)
45 else:
45 else:
46 params = ""
46 params = ""
47 return """
47 return """
48 <iframe
48 <iframe
49 width="%i"
49 width="%i"
50 height="%i"
50 height="%i"
51 src="http://www.youtube.com/embed/%s%s"
51 src="http://www.youtube.com/embed/%s%s"
52 frameborder="0"
52 frameborder="0"
53 allowfullscreen
53 allowfullscreen
54 ></iframe>
54 ></iframe>
55 """ % (self.width, self.height, self.id, params)
55 """ % (self.width, self.height, self.id, params)
56
56
57 class FileLink(object):
57 class FileLink(object):
58 """Class for embedding a local file link in an IPython session, based on path
58 """Class for embedding a local file link in an IPython session, based on path
59
59
60 e.g. to embed a link that was generated in the IPython notebook as my/data.txt
60 e.g. to embed a link that was generated in the IPython notebook as my/data.txt
61
61
62 you would do::
62 you would do::
63
63
64 local_file = FileLink("my/data.txt")
64 local_file = FileLink("my/data.txt")
65 display(local_file)
65 display(local_file)
66
66
67 or in the HTML notebook, just::
67 or in the HTML notebook, just::
68
68
69 FileLink("my/data.txt")
69 FileLink("my/data.txt")
70 """
70 """
71
71
72 html_link_str = "<a href='%s' target='_blank'>%s</a>"
72 html_link_str = "<a href='%s' target='_blank'>%s</a>"
73
73
74 def __init__(self,
74 def __init__(self,
75 path,
75 path,
76 url_prefix='files/',
76 url_prefix='files/',
77 result_html_prefix='',
77 result_html_prefix='',
78 result_html_suffix='<br>'):
78 result_html_suffix='<br>'):
79 """
79 """
80 Parameters
80 Parameters
81 ----------
81 ----------
82 path : str
82 path : str
83 path to the file or directory that should be formatted
83 path to the file or directory that should be formatted
84 directory_prefix : str
84 directory_prefix : str
85 prefix to be prepended to all files to form a working link [default:
85 prefix to be prepended to all files to form a working link [default:
86 'files']
86 'files']
87 result_html_prefix : str
87 result_html_prefix : str
88 text to append to beginning to link [default: none]
88 text to append to beginning to link [default: none]
89 result_html_suffix : str
89 result_html_suffix : str
90 text to append at the end of link [default: '<br>']
90 text to append at the end of link [default: '<br>']
91 """
91 """
92 if isdir(path):
92 if isdir(path):
93 raise ValueError,\
93 raise ValueError,\
94 ("Cannot display a directory using FileLink. "
94 ("Cannot display a directory using FileLink. "
95 "Use FileLinks to display '%s'." % path)
95 "Use FileLinks to display '%s'." % path)
96 self.path = path
96 self.path = path
97 self.url_prefix = url_prefix
97 self.url_prefix = url_prefix
98 self.result_html_prefix = result_html_prefix
98 self.result_html_prefix = result_html_prefix
99 self.result_html_suffix = result_html_suffix
99 self.result_html_suffix = result_html_suffix
100
100
101 def _format_path(self):
101 def _format_path(self):
102 fp = ''.join([self.url_prefix,self.path])
102 fp = ''.join([self.url_prefix,self.path])
103 return ''.join([self.result_html_prefix,
103 return ''.join([self.result_html_prefix,
104 self.html_link_str % (fp, self.path),
104 self.html_link_str % (fp, self.path),
105 self.result_html_suffix])
105 self.result_html_suffix])
106
106
107 def _repr_html_(self):
107 def _repr_html_(self):
108 """return html link to file
108 """return html link to file
109 """
109 """
110 if not exists(self.path):
110 if not exists(self.path):
111 return ("Path (<tt>%s</tt>) doesn't exist. "
111 return ("Path (<tt>%s</tt>) doesn't exist. "
112 "It may still be in the process of "
112 "It may still be in the process of "
113 "being generated, or you may have the "
113 "being generated, or you may have the "
114 "incorrect path." % self.path)
114 "incorrect path." % self.path)
115
115
116 return self._format_path()
116 return self._format_path()
117
117
118 def __repr__(self):
118 def __repr__(self):
119 """return absolute path to file
119 """return absolute path to file
120 """
120 """
121 return abspath(self.path)
121 return abspath(self.path)
122
122
123 class FileLinks(FileLink):
123 class FileLinks(FileLink):
124 """Class for embedding local file links in an IPython session, based on path
124 """Class for embedding local file links in an IPython session, based on path
125
125
126 e.g. to embed links to files that were generated in the IPython notebook under my/data
126 e.g. to embed links to files that were generated in the IPython notebook under my/data
127
127
128 you would do:
128 you would do:
129
129
130 local_files = FileLinks("my/data")
130 local_files = FileLinks("my/data")
131 display(local_files)
131 display(local_files)
132
132
133 or in the HTML notebook, just
133 or in the HTML notebook, just
134
134
135 FileLinks("my/data")
135 FileLinks("my/data")
136
136
137 """
137 """
138 def __init__(self,
138 def __init__(self,
139 path,
139 path,
140 url_prefix='files/',
140 url_prefix='files/',
141 included_suffixes=None,
141 included_suffixes=None,
142 result_html_prefix='',
142 result_html_prefix='',
143 result_html_suffix='<br>',
143 result_html_suffix='<br>',
144 notebook_display_formatter=None,
144 notebook_display_formatter=None,
145 terminal_display_formatter=None):
145 terminal_display_formatter=None):
146 """
146 """
147 included_suffixes : list of filename suffixes to include when
147 included_suffixes : list of filename suffixes to include when
148 formatting output [default: include all files]
148 formatting output [default: include all files]
149
149
150 See the FileLink (baseclass of LocalDirectory) docstring for
150 See the FileLink (baseclass of LocalDirectory) docstring for
151 information on additional parameters.
151 information on additional parameters.
152
152
153 notebook_display_formatter : func used to format links for display
153 notebook_display_formatter : func used to format links for display
154 in the notebook. See discussion of formatter function below.
154 in the notebook. See discussion of formatter function below.
155
155
156 terminal_display_formatter : func used to format links for display
156 terminal_display_formatter : func used to format links for display
157 in the terminal. See discussion of formatter function below.
157 in the terminal. See discussion of formatter function below.
158
158
159
159
160 Passing custom formatter functions
160 Passing custom formatter functions
161 ----------------------------------
161 ----------------------------------
162 Formatter functions must be of the form:
162 Formatter functions must be of the form:
163 f(dirname, fnames, included_suffixes)
163 f(dirname, fnames, included_suffixes)
164 dirname : the name of a directory (a string),
164 dirname : the name of a directory (a string),
165 fnames : a list of the files in that directory
165 fnames : a list of the files in that directory
166 included_suffixes : a list of the file suffixes that should be
166 included_suffixes : a list of the file suffixes that should be
167 included in the output (passing None means
167 included in the output (passing None means
168 to include all suffixes in the output in
168 to include all suffixes in the output in
169 the built-in formatters)
169 the built-in formatters)
170
170
171 returns a list of lines that should will be print in the
171 returns a list of lines that should will be print in the
172 notebook (if passing notebook_display_formatter) or the terminal
172 notebook (if passing notebook_display_formatter) or the terminal
173 (if passing terminal_display_formatter). This function is iterated
173 (if passing terminal_display_formatter). This function is iterated
174 over for each directory in self.path. Default formatters are in
174 over for each directory in self.path. Default formatters are in
175 place, can be passed here to support alternative formatting.
175 place, can be passed here to support alternative formatting.
176
176
177 """
177 """
178 if isfile(path):
178 if isfile(path):
179 raise ValueError,\
179 raise ValueError,\
180 ("Cannot display a file using FileLinks. "
180 ("Cannot display a file using FileLinks. "
181 "Use FileLink to display '%s'." % path)
181 "Use FileLink to display '%s'." % path)
182 self.included_suffixes = included_suffixes
182 self.included_suffixes = included_suffixes
183 # remove trailing slashs for more consistent output formatting
183 # remove trailing slashs for more consistent output formatting
184 path = path.rstrip('/')
184 path = path.rstrip('/')
185
185
186 self.path = path
186 self.path = path
187 self.url_prefix = url_prefix
187 self.url_prefix = url_prefix
188 self.result_html_prefix = result_html_prefix
188 self.result_html_prefix = result_html_prefix
189 self.result_html_suffix = result_html_suffix
189 self.result_html_suffix = result_html_suffix
190
190
191 self.notebook_display_formatter = \
191 self.notebook_display_formatter = \
192 notebook_display_formatter or self._get_notebook_display_formatter()
192 notebook_display_formatter or self._get_notebook_display_formatter()
193 self.terminal_display_formatter = \
193 self.terminal_display_formatter = \
194 terminal_display_formatter or self._get_terminal_display_formatter()
194 terminal_display_formatter or self._get_terminal_display_formatter()
195
195
196 def _get_display_formatter(self,
196 def _get_display_formatter(self,
197 dirname_output_format,
197 dirname_output_format,
198 fname_output_format,
198 fname_output_format,
199 fp_format):
199 fp_format,
200 fp_cleaner=None):
200 """ generate built-in formatter function
201 """ generate built-in formatter function
201
202
202 this is used to define both the notebook and terminal built-in
203 this is used to define both the notebook and terminal built-in
203 formatters as they only differ by some wrapper text for each entry
204 formatters as they only differ by some wrapper text for each entry
204
205
205 dirname_output_format: string to use for formatting directory
206 dirname_output_format: string to use for formatting directory
206 names, dirname will be substituted for a single "%s" which
207 names, dirname will be substituted for a single "%s" which
207 must appear in this string
208 must appear in this string
208 fname_output_format: string to use for formatting file names,
209 fname_output_format: string to use for formatting file names,
209 if a single "%s" appears in the string, fname will be substituted
210 if a single "%s" appears in the string, fname will be substituted
210 if two "%s" appear in the string, the path to fname will be
211 if two "%s" appear in the string, the path to fname will be
211 substituted for the first and fname will be substituted for the
212 substituted for the first and fname will be substituted for the
212 second
213 second
213 fp_format: string to use for formatting filepaths, must contain
214 fp_format: string to use for formatting filepaths, must contain
214 exactly two "%s" and the dirname will be subsituted for the first
215 exactly two "%s" and the dirname will be subsituted for the first
215 and fname will be substituted for the second
216 and fname will be substituted for the second
216 """
217 """
217 def f(dirname, fnames, included_suffixes=None):
218 def f(dirname, fnames, included_suffixes=None):
218 result = []
219 result = []
219 # begin by figuring out which filenames, if any,
220 # begin by figuring out which filenames, if any,
220 # are going to be displayed
221 # are going to be displayed
221 display_fnames = []
222 display_fnames = []
222 for fname in fnames:
223 for fname in fnames:
223 if (isfile(join(dirname,fname)) and
224 if (isfile(join(dirname,fname)) and
224 (included_suffixes == None or
225 (included_suffixes == None or
225 splitext(fname)[1] in included_suffixes)):
226 splitext(fname)[1] in included_suffixes)):
226 display_fnames.append(fname)
227 display_fnames.append(fname)
227
228
228 if len(display_fnames) == 0:
229 if len(display_fnames) == 0:
229 # if there are no filenames to display, don't print anything
230 # if there are no filenames to display, don't print anything
230 # (not even the directory name)
231 # (not even the directory name)
231 pass
232 pass
232 else:
233 else:
233 # otherwise print the formatted directory name followed by
234 # otherwise print the formatted directory name followed by
234 # the formatted filenames
235 # the formatted filenames
235 dirname_output_line = dirname_output_format % dirname
236 dirname_output_line = dirname_output_format % dirname
236 result.append(dirname_output_line)
237 result.append(dirname_output_line)
237 for fname in display_fnames:
238 for fname in display_fnames:
238 fp = fp_format % (dirname,fname)
239 fp = fp_format % (dirname,fname)
240 if fp_cleaner is not None:
241 fp = fp_cleaner(fp)
239 try:
242 try:
240 # output can include both a filepath and a filename...
243 # output can include both a filepath and a filename...
241 fname_output_line = fname_output_format % (fp, fname)
244 fname_output_line = fname_output_format % (fp, fname)
242 except TypeError:
245 except TypeError:
243 # ... or just a single filepath
246 # ... or just a single filepath
244 fname_output_line = fname_output_format % fname
247 fname_output_line = fname_output_format % fname
245 result.append(fname_output_line)
248 result.append(fname_output_line)
246 return result
249 return result
247 return f
250 return f
248
251
249 def _get_notebook_display_formatter(self,
252 def _get_notebook_display_formatter(self,
250 spacer="&nbsp;&nbsp;"):
253 spacer="&nbsp;&nbsp;"):
251 """ generate function to use for notebook formatting
254 """ generate function to use for notebook formatting
252 """
255 """
253 dirname_output_format = \
256 dirname_output_format = \
254 self.result_html_prefix + "%s/" + self.result_html_suffix
257 self.result_html_prefix + "%s/" + self.result_html_suffix
255 fname_output_format = \
258 fname_output_format = \
256 self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
259 self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
257 fp_format = self.url_prefix + '%s/%s'
260 fp_format = self.url_prefix + '%s/%s'
261 if sep == "\\":
262 # Working on a platform where the path separator is "\", so
263 # must convert these to "/" for generating a URI
264 def fp_cleaner(fp):
265 # Replace all occurences of backslash ("\") with a forward
266 # slash ("/") - this is necessary on windows when a path is
267 # provided as input, but we must link to a URI
268 return fp.replace('\\','/')
269 else:
270 fp_cleaner = None
258
271
259 return self._get_display_formatter(dirname_output_format,
272 return self._get_display_formatter(dirname_output_format,
260 fname_output_format,
273 fname_output_format,
261 fp_format)
274 fp_format,
275 fp_cleaner)
262
276
263 def _get_terminal_display_formatter(self,
277 def _get_terminal_display_formatter(self,
264 spacer=" "):
278 spacer=" "):
265 """ generate function to use for terminal formatting
279 """ generate function to use for terminal formatting
266 """
280 """
267 dirname_output_format = "%s/"
281 dirname_output_format = "%s/"
268 fname_output_format = spacer + "%s"
282 fname_output_format = spacer + "%s"
269 fp_format = '%s/%s'
283 fp_format = '%s/%s'
270
284
271 return self._get_display_formatter(dirname_output_format,
285 return self._get_display_formatter(dirname_output_format,
272 fname_output_format,
286 fname_output_format,
273 fp_format)
287 fp_format)
274
288
275 def _format_path(self):
289 def _format_path(self):
276 result_lines = []
290 result_lines = []
277 walked_dir = list(walk(self.path))
291 walked_dir = list(walk(self.path))
278 walked_dir.sort()
292 walked_dir.sort()
279 for dirname, subdirs, fnames in walked_dir:
293 for dirname, subdirs, fnames in walked_dir:
280 result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
294 result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
281 return '\n'.join(result_lines)
295 return '\n'.join(result_lines)
282
296
283 def __repr__(self):
297 def __repr__(self):
284 """return newline-separated absolute paths
298 """return newline-separated absolute paths
285 """
299 """
286 result_lines = []
300 result_lines = []
287 walked_dir = list(walk(self.path))
301 walked_dir = list(walk(self.path))
288 walked_dir.sort()
302 walked_dir.sort()
289 for dirname, subdirs, fnames in walked_dir:
303 for dirname, subdirs, fnames in walked_dir:
290 result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
304 result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
291 return '\n'.join(result_lines)
305 return '\n'.join(result_lines)
@@ -1,153 +1,158 b''
1 """Tests for IPython.lib.display.
1 """Tests for IPython.lib.display.
2
2
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012, the IPython Development Team.
5 # Copyright (c) 2012, the IPython Development Team.
6 #
6 #
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8 #
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 from __future__ import print_function
15 from __future__ import print_function
16 from tempfile import NamedTemporaryFile, mkdtemp
16 from tempfile import NamedTemporaryFile, mkdtemp
17 from os.path import split
17 from os.path import split
18 from os import sep
18
19
19 # Third-party imports
20 # Third-party imports
20 import nose.tools as nt
21 import nose.tools as nt
21
22
22 # Our own imports
23 # Our own imports
23 from IPython.lib import display
24 from IPython.lib import display
24
25
25 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
26 # Classes and functions
27 # Classes and functions
27 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
28
29
29 #--------------------------
30 #--------------------------
30 # FileLink tests
31 # FileLink tests
31 #--------------------------
32 #--------------------------
32
33
33 def test_instantiation_FileLink():
34 def test_instantiation_FileLink():
34 """FileLink: Test class can be instantiated"""
35 """FileLink: Test class can be instantiated"""
35 fl = display.FileLink('example.txt')
36 fl = display.FileLink('example.txt')
36
37
37 def test_warning_on_non_existant_path_FileLink():
38 def test_warning_on_non_existant_path_FileLink():
38 """FileLink: Calling _repr_html_ on non-existant files returns a warning
39 """FileLink: Calling _repr_html_ on non-existant files returns a warning
39 """
40 """
40 fl = display.FileLink('example.txt')
41 fl = display.FileLink('example.txt')
41 nt.assert_true(fl._repr_html_().startswith('Path (<tt>example.txt</tt>)'))
42 nt.assert_true(fl._repr_html_().startswith('Path (<tt>example.txt</tt>)'))
42
43
43 def test_existing_path_FileLink():
44 def test_existing_path_FileLink():
44 """FileLink: Calling _repr_html_ functions as expected on existing filepath
45 """FileLink: Calling _repr_html_ functions as expected on existing filepath
45 """
46 """
46 tf = NamedTemporaryFile()
47 tf = NamedTemporaryFile()
47 fl = display.FileLink(tf.name)
48 fl = display.FileLink(tf.name)
48 actual = fl._repr_html_()
49 actual = fl._repr_html_()
49 expected = "<a href='files/%s' target='_blank'>%s</a><br>" % (tf.name,tf.name)
50 expected = "<a href='files/%s' target='_blank'>%s</a><br>" % (tf.name,tf.name)
50 nt.assert_equal(actual,expected)
51 nt.assert_equal(actual,expected)
51
52
52 def test_existing_path_FileLink_repr():
53 def test_existing_path_FileLink_repr():
53 """FileLink: Calling repr() functions as expected on existing filepath
54 """FileLink: Calling repr() functions as expected on existing filepath
54 """
55 """
55 tf = NamedTemporaryFile()
56 tf = NamedTemporaryFile()
56 fl = display.FileLink(tf.name)
57 fl = display.FileLink(tf.name)
57 actual = repr(fl)
58 actual = repr(fl)
58 expected = tf.name
59 expected = tf.name
59 nt.assert_equal(actual,expected)
60 nt.assert_equal(actual,expected)
60
61
61 def test_error_on_directory_to_FileLink():
62 def test_error_on_directory_to_FileLink():
62 """FileLink: Raises error when passed directory
63 """FileLink: Raises error when passed directory
63 """
64 """
64 td = mkdtemp()
65 td = mkdtemp()
65 nt.assert_raises(ValueError,display.FileLink,td)
66 nt.assert_raises(ValueError,display.FileLink,td)
66
67
67 #--------------------------
68 #--------------------------
68 # FileLinks tests
69 # FileLinks tests
69 #--------------------------
70 #--------------------------
70
71
71 def test_instantiation_FileLinks():
72 def test_instantiation_FileLinks():
72 """FileLinks: Test class can be instantiated
73 """FileLinks: Test class can be instantiated
73 """
74 """
74 fls = display.FileLinks('example')
75 fls = display.FileLinks('example')
75
76
76 def test_warning_on_non_existant_path_FileLinks():
77 def test_warning_on_non_existant_path_FileLinks():
77 """FileLinks: Calling _repr_html_ on non-existant files returns a warning
78 """FileLinks: Calling _repr_html_ on non-existant files returns a warning
78 """
79 """
79 fls = display.FileLinks('example')
80 fls = display.FileLinks('example')
80 nt.assert_true(fls._repr_html_().startswith('Path (<tt>example</tt>)'))
81 nt.assert_true(fls._repr_html_().startswith('Path (<tt>example</tt>)'))
81
82
82 def test_existing_path_FileLinks():
83 def test_existing_path_FileLinks():
83 """FileLinks: Calling _repr_html_ functions as expected on existing dir
84 """FileLinks: Calling _repr_html_ functions as expected on existing dir
84 """
85 """
85 td = mkdtemp()
86 td = mkdtemp()
86 tf1 = NamedTemporaryFile(dir=td)
87 tf1 = NamedTemporaryFile(dir=td)
87 tf2 = NamedTemporaryFile(dir=td)
88 tf2 = NamedTemporaryFile(dir=td)
88 fl = display.FileLinks(td)
89 fl = display.FileLinks(td)
89 actual = fl._repr_html_()
90 actual = fl._repr_html_()
90 actual = actual.split('\n')
91 actual = actual.split('\n')
91 actual.sort()
92 actual.sort()
93 # the links should always have forward slashes, even on windows, so replace
94 # backslashes with forward slashes here
92 expected = ["%s/<br>" % td,
95 expected = ["%s/<br>" % td,
93 "&nbsp;&nbsp;<a href='files/%s' target='_blank'>%s</a><br>" % (tf2.name,split(tf2.name)[1]),
96 "&nbsp;&nbsp;<a href='files/%s' target='_blank'>%s</a><br>" %\
94 "&nbsp;&nbsp;<a href='files/%s' target='_blank'>%s</a><br>" % (tf1.name,split(tf1.name)[1])]
97 (tf2.name.replace("\\","/"),split(tf2.name)[1]),
98 "&nbsp;&nbsp;<a href='files/%s' target='_blank'>%s</a><br>" %\
99 (tf1.name.replace("\\","/"),split(tf1.name)[1])]
95 expected.sort()
100 expected.sort()
96 # We compare the sorted list of links here as that's more reliable
101 # We compare the sorted list of links here as that's more reliable
97 nt.assert_equal(actual,expected)
102 nt.assert_equal(actual,expected)
98
103
99 def test_existing_path_FileLinks_alt_formatter():
104 def test_existing_path_FileLinks_alt_formatter():
100 """FileLinks: Calling _repr_html_ functions as expected w/ an alt formatter
105 """FileLinks: Calling _repr_html_ functions as expected w/ an alt formatter
101 """
106 """
102 td = mkdtemp()
107 td = mkdtemp()
103 tf1 = NamedTemporaryFile(dir=td)
108 tf1 = NamedTemporaryFile(dir=td)
104 tf2 = NamedTemporaryFile(dir=td)
109 tf2 = NamedTemporaryFile(dir=td)
105 def fake_formatter(dirname,fnames,included_suffixes):
110 def fake_formatter(dirname,fnames,included_suffixes):
106 return ["hello","world"]
111 return ["hello","world"]
107 fl = display.FileLinks(td,notebook_display_formatter=fake_formatter)
112 fl = display.FileLinks(td,notebook_display_formatter=fake_formatter)
108 actual = fl._repr_html_()
113 actual = fl._repr_html_()
109 actual = actual.split('\n')
114 actual = actual.split('\n')
110 actual.sort()
115 actual.sort()
111 expected = ["hello","world"]
116 expected = ["hello","world"]
112 expected.sort()
117 expected.sort()
113 # We compare the sorted list of links here as that's more reliable
118 # We compare the sorted list of links here as that's more reliable
114 nt.assert_equal(actual,expected)
119 nt.assert_equal(actual,expected)
115
120
116 def test_existing_path_FileLinks_repr():
121 def test_existing_path_FileLinks_repr():
117 """FileLinks: Calling repr() functions as expected on existing directory """
122 """FileLinks: Calling repr() functions as expected on existing directory """
118 td = mkdtemp()
123 td = mkdtemp()
119 tf1 = NamedTemporaryFile(dir=td)
124 tf1 = NamedTemporaryFile(dir=td)
120 tf2 = NamedTemporaryFile(dir=td)
125 tf2 = NamedTemporaryFile(dir=td)
121 fl = display.FileLinks(td)
126 fl = display.FileLinks(td)
122 actual = repr(fl)
127 actual = repr(fl)
123 actual = actual.split('\n')
128 actual = actual.split('\n')
124 actual.sort()
129 actual.sort()
125 expected = ['%s/' % td, ' %s' % split(tf1.name)[1],' %s' % split(tf2.name)[1]]
130 expected = ['%s/' % td, ' %s' % split(tf1.name)[1],' %s' % split(tf2.name)[1]]
126 expected.sort()
131 expected.sort()
127 # We compare the sorted list of links here as that's more reliable
132 # We compare the sorted list of links here as that's more reliable
128 nt.assert_equal(actual,expected)
133 nt.assert_equal(actual,expected)
129
134
130 def test_existing_path_FileLinks_repr_alt_formatter():
135 def test_existing_path_FileLinks_repr_alt_formatter():
131 """FileLinks: Calling repr() functions as expected w/ alt formatter
136 """FileLinks: Calling repr() functions as expected w/ alt formatter
132 """
137 """
133 td = mkdtemp()
138 td = mkdtemp()
134 tf1 = NamedTemporaryFile(dir=td)
139 tf1 = NamedTemporaryFile(dir=td)
135 tf2 = NamedTemporaryFile(dir=td)
140 tf2 = NamedTemporaryFile(dir=td)
136 def fake_formatter(dirname,fnames,included_suffixes):
141 def fake_formatter(dirname,fnames,included_suffixes):
137 return ["hello","world"]
142 return ["hello","world"]
138 fl = display.FileLinks(td,terminal_display_formatter=fake_formatter)
143 fl = display.FileLinks(td,terminal_display_formatter=fake_formatter)
139 actual = repr(fl)
144 actual = repr(fl)
140 actual = actual.split('\n')
145 actual = actual.split('\n')
141 actual.sort()
146 actual.sort()
142 expected = ["hello","world"]
147 expected = ["hello","world"]
143 expected.sort()
148 expected.sort()
144 # We compare the sorted list of links here as that's more reliable
149 # We compare the sorted list of links here as that's more reliable
145 nt.assert_equal(actual,expected)
150 nt.assert_equal(actual,expected)
146
151
147 def test_error_on_file_to_FileLinks():
152 def test_error_on_file_to_FileLinks():
148 """FileLinks: Raises error when passed file
153 """FileLinks: Raises error when passed file
149 """
154 """
150 td = mkdtemp()
155 td = mkdtemp()
151 tf1 = NamedTemporaryFile(dir=td)
156 tf1 = NamedTemporaryFile(dir=td)
152 nt.assert_raises(ValueError,display.FileLinks,tf1.name)
157 nt.assert_raises(ValueError,display.FileLinks,tf1.name)
153
158
General Comments 0
You need to be logged in to leave comments. Login now