##// END OF EJS Templates
fixed bug in test and in support for passing alternative formatters
Greg Caporaso -
Show More
@@ -1,215 +1,216 b''
1 1 """Various display related classes.
2 2
3 3 Authors : MinRK, gregcaporaso
4 4 """
5 5
6 6 from os.path import exists, isfile, splitext, abspath, join, isdir, walk
7 7
8 8
9 9 class YouTubeVideo(object):
10 10 """Class for embedding a YouTube Video in an IPython session, based on its video id.
11 11
12 12 e.g. to embed the video on this page:
13 13
14 14 http://www.youtube.com/watch?v=foo
15 15
16 16 you would do:
17 17
18 18 vid = YouTubeVideo("foo")
19 19 display(vid)
20 20 """
21 21
22 22 def __init__(self, id, width=400, height=300):
23 23 self.id = id
24 24 self.width = width
25 25 self.height = height
26 26
27 27 def _repr_html_(self):
28 28 """return YouTube embed iframe for this video id"""
29 29 return """
30 30 <iframe
31 31 width="%i"
32 32 height="%i"
33 33 src="http://www.youtube.com/embed/%s"
34 34 frameborder="0"
35 35 allowfullscreen
36 36 ></iframe>
37 37 """%(self.width, self.height, self.id)
38 38
39 39 class FileLink(object):
40 40 """Class for embedding a local file link in an IPython session, based on path
41 41
42 42 e.g. to embed a link that was generated in the IPython notebook as my/data.txt
43 43
44 44 you would do:
45 45
46 46 local_file = FileLink("my/data.txt")
47 47 display(local_file)
48 48
49 49 or in the HTML notebook, just
50 50
51 51 FileLink("my/data.txt")
52 52 """
53 53
54 54 html_link_str = "<a href='%s' target='_blank'>%s</a>"
55 55
56 56 def __init__(self,
57 57 path,
58 58 url_prefix='files/',
59 59 result_html_prefix='',
60 60 result_html_suffix='<br>'):
61 61 """
62 62 path : path to the file or directory that should be formatted
63 63 directory_prefix : prefix to be prepended to all files to form a
64 64 working link [default: 'files']
65 65 result_html_prefix : text to append to beginning to link
66 66 [default: none]
67 67 result_html_suffix : text to append at the end of link
68 68 [default: '<br>']
69 69 """
70 70 self.path = path
71 71 self.url_prefix = url_prefix
72 72 self.result_html_prefix = result_html_prefix
73 73 self.result_html_suffix = result_html_suffix
74 74
75 75 def _format_path(self):
76 76 fp = ''.join([self.url_prefix,self.path])
77 77 return ''.join([self.result_html_prefix,
78 78 self.html_link_str % (fp, self.path),
79 79 self.result_html_suffix])
80 80
81 81 def _repr_html_(self):
82 82 """return html link to file
83 83 """
84 84 if not exists(self.path):
85 85 return ("Path (<tt>%s</tt>) doesn't exist. "
86 86 "It may still be in the process of "
87 87 "being generated, or you may have the "
88 88 "incorrect path." % self.path)
89 89
90 90 return self._format_path()
91 91
92 92 def __repr__(self):
93 93 """return absolute path to file
94 94 """
95 95 return abspath(self.path)
96 96
97 97 # Create an alias for formatting a single directory name as a link.
98 98 # Right now this is the same as a formatting for a single file, but
99 99 # we'll encourage users to reference these with a different class in
100 100 # case we want to change this in the future.
101 101 DirectoryLink = FileLink
102 102
103 103 class FileLinks(FileLink):
104 104 """Class for embedding local file links in an IPython session, based on path
105 105
106 106 e.g. to embed links to files that were generated in the IPython notebook under my/data
107 107
108 108 you would do:
109 109
110 110 local_files = FileLinks("my/data")
111 111 display(local_files)
112 112
113 113 or in the HTML notebook, just
114 114
115 115 FileLinks("my/data")
116 116
117 117 """
118 118 def __init__(self,
119 119 path,
120 120 url_prefix='files/',
121 121 included_suffixes=None,
122 122 result_html_prefix='',
123 123 result_html_suffix='<br>',
124 124 notebook_display_formatter=None,
125 125 terminal_display_formatter=None):
126 126 """
127 127 included_suffixes : list of filename suffixes to include when
128 128 formatting output [default: include all files]
129 129
130 130 See the FileLink (baseclass of LocalDirectory) docstring for
131 131 information on additional parameters.
132
132 133 """
133 134 self.included_suffixes = included_suffixes
134 135
135 136 FileLink.__init__(self,
136 137 path,
137 138 url_prefix,
138 139 result_html_prefix,
139 140 result_html_suffix)
140 141
141 142 self.notebook_display_formatter = \
142 self._get_notebook_display_formatter()
143 notebook_display_formatter or self._get_notebook_display_formatter()
143 144 self.terminal_display_formatter = \
144 self._get_terminal_display_formatter()
145 terminal_display_formatter or self._get_terminal_display_formatter()
145 146
146 147 def _get_display_formatter(self,
147 148 dirname_output_format,
148 149 fname_output_format,
149 150 fp_format):
150 151
151 152 included_suffixes = self.included_suffixes
152 153
153 154 def f(output_lines, dirname, fnames):
154 155 """ """
155 156 # begin by figuring out which filenames, if any,
156 157 # are going to be displayed
157 158 display_fnames = []
158 159 for fname in fnames:
159 160 if (isfile(join(dirname,fname)) and
160 161 (included_suffixes == None or
161 162 splitext(fname)[1] in included_suffixes)):
162 163 display_fnames.append(fname)
163 164
164 165 if len(display_fnames) == 0:
165 166 pass
166 167 else:
167 168 dirname_output_line = dirname_output_format % dirname
168 169 output_lines.append(dirname_output_line)
169 170 for fname in display_fnames:
170 171 fp = fp_format % (dirname,fname)
171 172 try:
172 173 # output can include both a filepath and a filename...
173 174 fname_output_line = fname_output_format % (fp, fname)
174 175 except TypeError:
175 176 # ... or just a single filepath
176 177 fname_output_line = fname_output_format % fname
177 178 output_lines.append(fname_output_line)
178 179 return
179 180 return f
180 181
181 182 def _get_notebook_display_formatter(self,
182 183 spacer="&nbsp;&nbsp;"):
183 184 """ """
184 185 dirname_output_format = \
185 186 self.result_html_prefix + "%s" + self.result_html_suffix
186 187 fname_output_format = \
187 188 self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
188 189 fp_format = self.url_prefix + '%s/%s'
189 190
190 191 return self._get_display_formatter(dirname_output_format,
191 192 fname_output_format,
192 193 fp_format)
193 194
194 195 def _get_terminal_display_formatter(self,
195 196 spacer=" "):
196 197 """ """
197 198 dirname_output_format = "%s"
198 199 fname_output_format = spacer + "%s"
199 200 fp_format = '%s/%s'
200 201
201 202 return self._get_display_formatter(dirname_output_format,
202 203 fname_output_format,
203 204 fp_format)
204 205
205 206 def _format_path(self):
206 207 result_lines = []
207 208 walk(self.path, self.notebook_display_formatter, result_lines)
208 209 return '\n'.join(result_lines)
209 210
210 211 def __repr__(self):
211 212 """return newline-separated absolute paths
212 213 """
213 214 result_lines = []
214 215 walk(self.path, self.terminal_display_formatter, result_lines)
215 216 return '\n'.join(result_lines) No newline at end of file
@@ -1,120 +1,120 b''
1 1 """Tests for IPython.lib.display.
2 2
3 3 """
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (c) 2012, the IPython Development Team.
6 6 #
7 7 # Distributed under the terms of the Modified BSD License.
8 8 #
9 9 # The full license is in the file COPYING.txt, distributed with this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Imports
14 14 #-----------------------------------------------------------------------------
15 15 from __future__ import print_function
16 16 from tempfile import NamedTemporaryFile, mkdtemp
17 17 from os.path import split
18 18
19 19 # Third-party imports
20 20 import nose.tools as nt
21 21
22 22 # Our own imports
23 23 from IPython.lib import display
24 24
25 25 #-----------------------------------------------------------------------------
26 26 # Classes and functions
27 27 #-----------------------------------------------------------------------------
28 28
29 29 #--------------------------
30 30 # FileLink tests
31 31 #--------------------------
32 32
33 33 def test_instantiation_FileLink():
34 34 """Test classes can be instantiated"""
35 35 fl = display.FileLink('example.txt')
36 36
37 37 def test_warning_on_non_existant_path_FileLink():
38 38 """Calling _repr_html_ on non-existant files returns a warning"""
39 39 fl = display.FileLink('example.txt')
40 40 nt.assert_true(fl._repr_html_().startswith('Path (<tt>example.txt</tt>)'))
41 41
42 42 def test_existing_path_FileLink():
43 43 """ Calling _repr_html_ functions as expected on existing filepath """
44 44 tf = NamedTemporaryFile()
45 45 fl = display.FileLink(tf.name)
46 46 actual = fl._repr_html_()
47 47 expected = "<a href='files/%s' target='_blank'>%s</a><br>" % (tf.name,tf.name)
48 48 nt.assert_equal(actual,expected)
49 49
50 50 def test_existing_path_FileLink_repr():
51 51 """ Calling repr() functions as expected on existing filepath """
52 52 tf = NamedTemporaryFile()
53 53 fl = display.FileLink(tf.name)
54 54 actual = repr(fl)
55 55 expected = tf.name
56 56 nt.assert_equal(actual,expected)
57 57
58 58 #--------------------------
59 59 # FileLinks tests
60 60 #--------------------------
61 61
62 62 def test_instantiation_FileLinks():
63 63 """Test classes can be instantiated"""
64 64 fls = display.FileLinks('example')
65 65
66 66 def test_warning_on_non_existant_path_FileLinks():
67 67 """Calling _repr_html_ on non-existant files returns a warning"""
68 68 fls = display.FileLinks('example')
69 69 nt.assert_true(fls._repr_html_().startswith('Path (<tt>example</tt>)'))
70 70
71 71 def test_existing_path_FileLinks():
72 72 """ Calling _repr_html_ functions as expected on existing directory """
73 73 td = mkdtemp()
74 74 tf1 = NamedTemporaryFile(dir=td)
75 75 tf2 = NamedTemporaryFile(dir=td)
76 76 fl = display.FileLinks(td)
77 77 actual = fl._repr_html_()
78 78 actual = actual.split('\n')
79 79 actual.sort()
80 80 expected = ["%s<br>" % td,
81 81 "&nbsp;&nbsp;<a href='files/%s' target='_blank'>%s</a><br>" % (tf2.name,split(tf2.name)[1]),
82 82 "&nbsp;&nbsp;<a href='files/%s' target='_blank'>%s</a><br>" % (tf1.name,split(tf1.name)[1])]
83 83 expected.sort()
84 84 # We compare the sorted list of links here as that's more reliable
85 85 nt.assert_equal(actual,expected)
86 86
87 87 def test_existing_path_FileLinks_repr():
88 88 """ Calling repr() functions as expected on existing directory """
89 89 td = mkdtemp()
90 90 tf1 = NamedTemporaryFile(dir=td)
91 91 tf2 = NamedTemporaryFile(dir=td)
92 92 fl = display.FileLinks(td)
93 93 actual = repr(fl)
94 94 actual = actual.split('\n')
95 95 actual.sort()
96 expected = [td, ' %s' % tf1.name,' %s' % tf2.name]
96 expected = [td, ' %s' % split(tf1.name)[1],' %s' % split(tf2.name)[1]]
97 97 expected.sort()
98 98 # We compare the sorted list of links here as that's more reliable
99 99 nt.assert_equal(actual,expected)
100 100
101 101 #--------------------------
102 102 # DirectoryLink tests
103 103 #--------------------------
104 104
105 105 def test_instantiation_DirectoryLink():
106 106 """Test classes can be instantiated"""
107 107 dl = display.DirectoryLink('example')
108 108
109 109 def test_warning_on_non_existant_path_DirectoryLink():
110 110 """Calling _repr_html_ on non-existant files returns a warning"""
111 111 dl = display.DirectoryLink('example')
112 112 nt.assert_true(dl._repr_html_().startswith('Path (<tt>example</tt>)'))
113 113
114 114 def test_existing_path_DirectoryLink():
115 115 """ Calling _repr_html_ functions as expected on existing directory """
116 116 td = mkdtemp()
117 117 dl = display.DirectoryLink(td)
118 118 actual = dl._repr_html_()
119 119 expected = "<a href='files/%s' target='_blank'>%s</a><br>" % (td,td)
120 120 nt.assert_equal(actual,expected)
General Comments 0
You need to be logged in to leave comments. Login now