##// END OF EJS Templates
Use IPython parameterized testing
Jonathan Frederic -
Show More
@@ -1,88 +1,84 b''
1 """
1 """
2 Module with tests for ansi filters
2 Module with tests for ansi filters
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from IPython.testing import decorators as dec
18 from IPython.utils.coloransi import TermColors
17 from IPython.utils.coloransi import TermColors
19
18
20 from ...tests.base import TestsBase
19 from ...tests.base import TestsBase
21 from ..ansi import strip_ansi, ansi2html, ansi2latex
20 from ..ansi import strip_ansi, ansi2html, ansi2latex
22
21
23
22
24 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
25 # Class
24 # Class
26 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
27
26
28 class TestAnsi(TestsBase):
27 class TestAnsi(TestsBase):
29 """Contains test functions for ansi.py"""
28 """Contains test functions for ansi.py"""
30
29
31 @dec.parametric
32 def test_strip_ansi(self):
30 def test_strip_ansi(self):
33 """strip_ansi test"""
31 """strip_ansi test"""
34 correct_outputs = {
32 correct_outputs = {
35 '%s%s%s' % (TermColors.Green, TermColors.White, TermColors.Red) : '',
33 '%s%s%s' % (TermColors.Green, TermColors.White, TermColors.Red) : '',
36 'hello%s' % TermColors.Blue: 'hello',
34 'hello%s' % TermColors.Blue: 'hello',
37 'he%s%sllo' % (TermColors.Yellow, TermColors.Cyan) : 'hello',
35 'he%s%sllo' % (TermColors.Yellow, TermColors.Cyan) : 'hello',
38 '%shello' % TermColors.Blue : 'hello',
36 '%shello' % TermColors.Blue : 'hello',
39 '{0}h{0}e{0}l{0}l{0}o{0}'.format(TermColors.Red) : 'hello',
37 '{0}h{0}e{0}l{0}l{0}o{0}'.format(TermColors.Red) : 'hello',
40 'hel%slo' % TermColors.Green : 'hello',
38 'hel%slo' % TermColors.Green : 'hello',
41 'hello' : 'hello'}
39 'hello' : 'hello'}
42
40
43 for inval, outval in correct_outputs.items():
41 for inval, outval in correct_outputs.items():
44 yield self._try_strip_ansi, inval, outval
42 yield self._try_strip_ansi(inval, outval)
45
43
46
44
47 def _try_strip_ansi(self, inval, outval):
45 def _try_strip_ansi(self, inval, outval):
48 self.assert_equal(outval, strip_ansi(inval))
46 self.assertEqual(outval, strip_ansi(inval))
49
47
50
48
51 @dec.parametric
52 def test_ansi2html(self):
49 def test_ansi2html(self):
53 """ansi2html test"""
50 """ansi2html test"""
54 correct_outputs = {
51 correct_outputs = {
55 '%s' % (TermColors.Red) : '<span class="ansired"></span>',
52 '%s' % (TermColors.Red) : '<span class="ansired"></span>',
56 'hello%s' % TermColors.Blue: 'hello<span class="ansiblue"></span>',
53 'hello%s' % TermColors.Blue: 'hello<span class="ansiblue"></span>',
57 'he%s%sllo' % (TermColors.Green, TermColors.Cyan) : 'he<span class="ansigreen"></span><span class="ansicyan">llo</span>',
54 'he%s%sllo' % (TermColors.Green, TermColors.Cyan) : 'he<span class="ansigreen"></span><span class="ansicyan">llo</span>',
58 '%shello' % TermColors.Yellow : '<span class="ansiyellow">hello</span>',
55 '%shello' % TermColors.Yellow : '<span class="ansiyellow">hello</span>',
59 '{0}h{0}e{0}l{0}l{0}o{0}'.format(TermColors.White) : '<span class="ansigrey">h</span><span class="ansigrey">e</span><span class="ansigrey">l</span><span class="ansigrey">l</span><span class="ansigrey">o</span><span class="ansigrey"></span>',
56 '{0}h{0}e{0}l{0}l{0}o{0}'.format(TermColors.White) : '<span class="ansigrey">h</span><span class="ansigrey">e</span><span class="ansigrey">l</span><span class="ansigrey">l</span><span class="ansigrey">o</span><span class="ansigrey"></span>',
60 'hel%slo' % TermColors.Green : 'hel<span class="ansigreen">lo</span>',
57 'hel%slo' % TermColors.Green : 'hel<span class="ansigreen">lo</span>',
61 'hello' : 'hello'}
58 'hello' : 'hello'}
62
59
63 for inval, outval in correct_outputs.items():
60 for inval, outval in correct_outputs.items():
64 yield self._try_ansi2html, inval, outval
61 yield self._try_ansi2html(inval, outval)
65
62
66
63
67 def _try_ansi2html(self, inval, outval):
64 def _try_ansi2html(self, inval, outval):
68 self.fuzzy_compare(outval, ansi2html(inval))
65 self.fuzzy_compare(outval, ansi2html(inval))
69
66
70
67
71 @dec.parametric
72 def test_ansi2latex(self):
68 def test_ansi2latex(self):
73 """ansi2latex test"""
69 """ansi2latex test"""
74 correct_outputs = {
70 correct_outputs = {
75 '%s' % (TermColors.Red) : r'\red{}',
71 '%s' % (TermColors.Red) : r'\red{}',
76 'hello%s' % TermColors.Blue: r'hello\blue{}',
72 'hello%s' % TermColors.Blue: r'hello\blue{}',
77 'he%s%sllo' % (TermColors.Green, TermColors.Cyan) : r'he\green{}\cyan{llo}',
73 'he%s%sllo' % (TermColors.Green, TermColors.Cyan) : r'he\green{}\cyan{llo}',
78 '%shello' % TermColors.Yellow : r'\yellow{hello}',
74 '%shello' % TermColors.Yellow : r'\yellow{hello}',
79 '{0}h{0}e{0}l{0}l{0}o{0}'.format(TermColors.White) : r'\white{h}\white{e}\white{l}\white{l}\white{o}\white{}',
75 '{0}h{0}e{0}l{0}l{0}o{0}'.format(TermColors.White) : r'\white{h}\white{e}\white{l}\white{l}\white{o}\white{}',
80 'hel%slo' % TermColors.Green : r'hel\green{lo}',
76 'hel%slo' % TermColors.Green : r'hel\green{lo}',
81 'hello' : 'hello'}
77 'hello' : 'hello'}
82
78
83 for inval, outval in correct_outputs.items():
79 for inval, outval in correct_outputs.items():
84 yield self._try_ansi2latex, inval, outval
80 yield self._try_ansi2latex(inval, outval)
85
81
86
82
87 def _try_ansi2latex(self, inval, outval):
83 def _try_ansi2latex(self, inval, outval):
88 self.fuzzy_compare(outval, ansi2latex(inval), case_sensitive=True)
84 self.fuzzy_compare(outval, ansi2latex(inval), case_sensitive=True)
@@ -1,46 +1,46 b''
1 """
1 """
2 Module with tests for DataTypeFilter
2 Module with tests for DataTypeFilter
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17
17
18 from ...tests.base import TestsBase
18 from ...tests.base import TestsBase
19 from ..datatypefilter import DataTypeFilter
19 from ..datatypefilter import DataTypeFilter
20
20
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Class
23 # Class
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 class TestDataTypeFilter(TestsBase):
26 class TestDataTypeFilter(TestsBase):
27 """Contains test functions for datatypefilter.py"""
27 """Contains test functions for datatypefilter.py"""
28
28
29
29
30 def test_constructor(self):
30 def test_constructor(self):
31 """Can an instance of a DataTypeFilter be created?"""
31 """Can an instance of a DataTypeFilter be created?"""
32 DataTypeFilter()
32 DataTypeFilter()
33
33
34
34
35 def test_junk_types(self):
35 def test_junk_types(self):
36 """Can the DataTypeFilter pickout a useful type from a list of junk types?"""
36 """Can the DataTypeFilter pickout a useful type from a list of junk types?"""
37 filter = DataTypeFilter()
37 filter = DataTypeFilter()
38 assert "png" in filter(["hair", "water", "png", "rock"])
38 assert "png" in filter(["hair", "water", "png", "rock"])
39 assert "pdf" in filter(["pdf", "hair", "water", "png", "rock"])
39 assert "pdf" in filter(["pdf", "hair", "water", "png", "rock"])
40 self.assert_equals(filter(["hair", "water", "rock"]), [])
40 self.assertEqual(filter(["hair", "water", "rock"]), [])
41
41
42
42
43 def test_null(self):
43 def test_null(self):
44 """Will the DataTypeFilter fail if no types are passed in?"""
44 """Will the DataTypeFilter fail if no types are passed in?"""
45 filter = DataTypeFilter()
45 filter = DataTypeFilter()
46 self.assert_equals(filter([]), [])
46 self.assertEqual(filter([]), [])
@@ -1,69 +1,65 b''
1 """
1 """
2 Module with tests for Highlight
2 Module with tests for Highlight
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from IPython.testing import decorators as dec
18
19 from ...tests.base import TestsBase
17 from ...tests.base import TestsBase
20 from ..highlight import highlight2html, highlight2latex
18 from ..highlight import highlight2html, highlight2latex
21
19
22
20
23 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
24 # Class
22 # Class
25 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
26
24
27 class TestHighlight(TestsBase):
25 class TestHighlight(TestsBase):
28 """Contains test functions for highlight.py"""
26 """Contains test functions for highlight.py"""
29
27
30 #Hello world test, magics test, blank string test
28 #Hello world test, magics test, blank string test
31 tests = [
29 tests = [
32 """
30 """
33 #Hello World Example
31 #Hello World Example
34
32
35 def say(text):
33 def say(text):
36 print(text)
34 print(text)
37
35
38 say('Hello World!')
36 say('Hello World!')
39 """,
37 """,
40 """
38 """
41 %%pylab
39 %%pylab
42 plot(x,y, 'r')
40 plot(x,y, 'r')
43 """
41 """
44 ]
42 ]
45
43
46 tokens = [
44 tokens = [
47 ['Hello World Example', 'say', 'text', 'print', 'def'],
45 ['Hello World Example', 'say', 'text', 'print', 'def'],
48 ['pylab', 'plot']]
46 ['pylab', 'plot']]
49
47
50
48
51 @dec.parametric
52 def test_highlight2html(self):
49 def test_highlight2html(self):
53 """highlight2html test"""
50 """highlight2html test"""
54 for index, test in enumerate(self.tests):
51 for index, test in enumerate(self.tests):
55 yield self._try_highlight, highlight2html, test, self.tokens[index]
52 yield self._try_highlight(highlight2html, test, self.tokens[index])
56
53
57
54
58 @dec.parametric
59 def test_highlight2latex(self):
55 def test_highlight2latex(self):
60 """highlight2latex test"""
56 """highlight2latex test"""
61 for index, test in enumerate(self.tests):
57 for index, test in enumerate(self.tests):
62 yield self._try_highlight, highlight2latex, test, self.tokens[index]
58 yield self._try_highlight(highlight2latex, test, self.tokens[index])
63
59
64
60
65 def _try_highlight(self, method, test, tokens):
61 def _try_highlight(self, method, test, tokens):
66 """Try highlighting source, look for key tokens"""
62 """Try highlighting source, look for key tokens"""
67 results = method(test)
63 results = method(test)
68 for token in tokens:
64 for token in tokens:
69 assert token in results
65 assert token in results
@@ -1,69 +1,65 b''
1 """
1 """
2 Module with tests for Latex
2 Module with tests for Latex
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from IPython.testing import decorators as dec
18
19 from ...tests.base import TestsBase
17 from ...tests.base import TestsBase
20 from ..latex import escape_latex, strip_math_space
18 from ..latex import escape_latex, strip_math_space
21
19
22
20
23 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
24 # Class
22 # Class
25 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
26
24
27 class TestLatex(TestsBase):
25 class TestLatex(TestsBase):
28
26
29
27
30 @dec.parametric
31 def test_escape_latex(self):
28 def test_escape_latex(self):
32 """escape_latex test"""
29 """escape_latex test"""
33 tests = [
30 tests = [
34 (r'How are \you doing today?', r'How are \textbackslashyou doing today?'),
31 (r'How are \you doing today?', r'How are \textbackslashyou doing today?'),
35 (r'\escapechar=`\A\catcode`\|=0 |string|foo', r'\textbackslashescapechar=`\textbackslashA\textbackslashcatcode`\textbackslash|=0 |string|foo'),
32 (r'\escapechar=`\A\catcode`\|=0 |string|foo', r'\textbackslashescapechar=`\textbackslashA\textbackslashcatcode`\textbackslash|=0 |string|foo'),
36 (r'# $ % & ~ _ ^ \ { }',r'\# \$ \% \& \~{} \_ \^{} \textbackslash \{ \}'),
33 (r'# $ % & ~ _ ^ \ { }',r'\# \$ \% \& \~{} \_ \^{} \textbackslash \{ \}'),
37 ('','')]
34 ('','')]
38
35
39 for test in tests:
36 for test in tests:
40 yield self._try_escape_latex, test[0], test[1]
37 yield self._try_escape_latex(test[0], test[1])
41
38
42
39
43 def _try_escape_latex(self, test, result):
40 def _try_escape_latex(self, test, result):
44 """Try to remove latex from string"""
41 """Try to remove latex from string"""
45 self.assert_equal(escape_latex(test), result)
42 self.assertEqual(escape_latex(test), result)
46
43
47
44
48 @dec.parametric
49 def test_strip_math_space(self):
45 def test_strip_math_space(self):
50 """strip_math_space test"""
46 """strip_math_space test"""
51 tests = [
47 tests = [
52 ('$e$','$e$'),
48 ('$e$','$e$'),
53 ('$ e $','$e$'),
49 ('$ e $','$e$'),
54 ('xxx$e^i$yyy','xxx$e^i$yyy'),
50 ('xxx$e^i$yyy','xxx$e^i$yyy'),
55 ('xxx$ e^i $yyy','xxx$e^i$yyy'),
51 ('xxx$ e^i $yyy','xxx$e^i$yyy'),
56 ('xxx$e^i $yyy','xxx$e^i$yyy'),
52 ('xxx$e^i $yyy','xxx$e^i$yyy'),
57 ('xxx$ e^i$yyy','xxx$e^i$yyy'),
53 ('xxx$ e^i$yyy','xxx$e^i$yyy'),
58 ('\$ e $ e $','\$ e $e$'),
54 ('\$ e $ e $','\$ e $e$'),
59 ('','')]
55 ('','')]
60
56
61 for test in tests:
57 for test in tests:
62 yield self._try_strip_math_space, test[0], test[1]
58 yield self._try_strip_math_space(test[0], test[1])
63
59
64
60
65 def _try_strip_math_space(self, test, result):
61 def _try_strip_math_space(self, test, result):
66 """
62 """
67 Try to remove spaces between dollar symbols and contents correctly
63 Try to remove spaces between dollar symbols and contents correctly
68 """
64 """
69 self.assert_equal(strip_math_space(test), result)
65 self.assertEqual(strip_math_space(test), result)
@@ -1,96 +1,93 b''
1
1
2 """
2 """
3 Module with tests for Markdown
3 Module with tests for Markdown
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (c) 2013, the IPython Development Team.
7 # Copyright (c) 2013, the IPython Development Team.
8 #
8 #
9 # Distributed under the terms of the Modified BSD License.
9 # Distributed under the terms of the Modified BSD License.
10 #
10 #
11 # The full license is in the file COPYING.txt, distributed with this software.
11 # The full license is in the file COPYING.txt, distributed with this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 from copy import copy
18 from copy import copy
19
19
20 from IPython.utils.py3compat import string_types
20 from IPython.utils.py3compat import string_types
21 from IPython.testing import decorators as dec
21 from IPython.testing import decorators as dec
22
22
23 from ...tests.base import TestsBase
23 from ...tests.base import TestsBase
24 from ..markdown import markdown2latex, markdown2html, markdown2rst
24 from ..markdown import markdown2latex, markdown2html, markdown2rst
25
25
26
26
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28 # Class
28 # Class
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30
30
31 class TestMarkdown(TestsBase):
31 class TestMarkdown(TestsBase):
32
32
33 tests = [
33 tests = [
34 '*test',
34 '*test',
35 '**test',
35 '**test',
36 '*test*',
36 '*test*',
37 '_test_',
37 '_test_',
38 '__test__',
38 '__test__',
39 '__*test*__',
39 '__*test*__',
40 '**test**',
40 '**test**',
41 '#test',
41 '#test',
42 '##test',
42 '##test',
43 'test\n----',
43 'test\n----',
44 'test [link](https://google.com/)']
44 'test [link](https://google.com/)']
45
45
46 tokens = [
46 tokens = [
47 '*test',
47 '*test',
48 '**test',
48 '**test',
49 'test',
49 'test',
50 'test',
50 'test',
51 'test',
51 'test',
52 'test',
52 'test',
53 'test',
53 'test',
54 'test',
54 'test',
55 'test',
55 'test',
56 'test',
56 'test',
57 ('test', 'https://google.com/')]
57 ('test', 'https://google.com/')]
58
58
59
59
60 @dec.onlyif_cmds_exist('pandoc')
60 @dec.onlyif_cmds_exist('pandoc')
61 @dec.parametric
62 def test_markdown2latex(self):
61 def test_markdown2latex(self):
63 """markdown2latex test"""
62 """markdown2latex test"""
64 for index, test in enumerate(self.tests):
63 for index, test in enumerate(self.tests):
65 yield self._try_markdown, markdown2latex, test, self.tokens[index]
64 yield self._try_markdown(markdown2latex, test, self.tokens[index])
66
65
67
66
68 @dec.onlyif_cmds_exist('pandoc')
67 @dec.onlyif_cmds_exist('pandoc')
69 @dec.parametric
70 def test_markdown2html(self):
68 def test_markdown2html(self):
71 """markdown2html test"""
69 """markdown2html test"""
72 for index, test in enumerate(self.tests):
70 for index, test in enumerate(self.tests):
73 yield self._try_markdown, markdown2html, test, self.tokens[index]
71 yield self._try_markdown(markdown2html, test, self.tokens[index])
74
72
75
73
76 @dec.onlyif_cmds_exist('pandoc')
74 @dec.onlyif_cmds_exist('pandoc')
77 @dec.parametric
78 def test_markdown2rst(self):
75 def test_markdown2rst(self):
79 """markdown2rst test"""
76 """markdown2rst test"""
80
77
81 #Modify token array for rst, escape asterik
78 #Modify token array for rst, escape asterik
82 tokens = copy(self.tokens)
79 tokens = copy(self.tokens)
83 tokens[0] = r'\*test'
80 tokens[0] = r'\*test'
84 tokens[1] = r'\*\*test'
81 tokens[1] = r'\*\*test'
85
82
86 for index, test in enumerate(self.tests):
83 for index, test in enumerate(self.tests):
87 yield self._try_markdown, markdown2rst, test, tokens[index]
84 yield self._try_markdown(markdown2rst, test, tokens[index])
88
85
89
86
90 def _try_markdown(self, method, test, tokens):
87 def _try_markdown(self, method, test, tokens):
91 results = method(test)
88 results = method(test)
92 if isinstance(tokens, string_types):
89 if isinstance(tokens, string_types):
93 assert tokens in results
90 assert tokens in results
94 else:
91 else:
95 for token in tokens:
92 for token in tokens:
96 assert token in results
93 assert token in results
@@ -1,122 +1,119 b''
1 """
1 """
2 Module with tests for Strings
2 Module with tests for Strings
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from IPython.testing import decorators as dec
17 from IPython.testing import decorators as dec
18 from ...tests.base import TestsBase
18 from ...tests.base import TestsBase
19 from ..strings import (wrap_text, html2text, add_anchor, strip_dollars,
19 from ..strings import (wrap_text, html2text, add_anchor, strip_dollars,
20 strip_files_prefix, get_lines, comment_lines, ipython2python)
20 strip_files_prefix, get_lines, comment_lines, ipython2python)
21
21
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Class
24 # Class
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 class TestStrings(TestsBase):
27 class TestStrings(TestsBase):
28
28
29 @dec.parametric
30 def test_wrap_text(self):
29 def test_wrap_text(self):
31 """wrap_text test"""
30 """wrap_text test"""
32 test_text = """
31 test_text = """
33 Tush! never tell me; I take it much unkindly
32 Tush! never tell me; I take it much unkindly
34 That thou, Iago, who hast had my purse
33 That thou, Iago, who hast had my purse
35 As if the strings were thine, shouldst know of this.
34 As if the strings were thine, shouldst know of this.
36 """
35 """
37 for length in [30,5,1]:
36 for length in [30,5,1]:
38 yield self._confirm_wrap_text, test_text, length
37 yield self._confirm_wrap_text(test_text, length)
39
38
40
39
41 def _confirm_wrap_text(self, text, length):
40 def _confirm_wrap_text(self, text, length):
42 for line in wrap_text(text, length).split('\n'):
41 for line in wrap_text(text, length).split('\n'):
43 assert len(line) <= length
42 assert len(line) <= length
44
43
45
44
46 def test_html2text(self):
45 def test_html2text(self):
47 """html2text test"""
46 """html2text test"""
48 #TODO: More tests
47 #TODO: More tests
49 self.assert_equal(html2text('<name>joe</name>'), 'joe')
48 self.assertEqual(html2text('<name>joe</name>'), 'joe')
50
49
51
50
52 def test_add_anchor(self):
51 def test_add_anchor(self):
53 """add_anchor test"""
52 """add_anchor test"""
54 #TODO: More tests
53 #TODO: More tests
55 results = add_anchor('<b>Hello World!</b>')
54 results = add_anchor('<b>Hello World!</b>')
56 assert 'Hello World!' in results
55 assert 'Hello World!' in results
57 assert 'id="' in results
56 assert 'id="' in results
58 assert 'class="anchor-link"' in results
57 assert 'class="anchor-link"' in results
59 assert '<b' in results
58 assert '<b' in results
60 assert '</b>' in results
59 assert '</b>' in results
61
60
62
61
63 @dec.parametric
64 def test_strip_dollars(self):
62 def test_strip_dollars(self):
65 """strip_dollars test"""
63 """strip_dollars test"""
66 tests = [
64 tests = [
67 ('', ''),
65 ('', ''),
68 ('$$', ''),
66 ('$$', ''),
69 ('$H$', 'H'),
67 ('$H$', 'H'),
70 ('$He', 'He'),
68 ('$He', 'He'),
71 ('H$el', 'H$el'),
69 ('H$el', 'H$el'),
72 ('Hell$', 'Hell'),
70 ('Hell$', 'Hell'),
73 ('Hello', 'Hello'),
71 ('Hello', 'Hello'),
74 ('W$o$rld', 'W$o$rld')]
72 ('W$o$rld', 'W$o$rld')]
75 for test in tests:
73 for test in tests:
76 yield self._try_strip_dollars, test[0], test[1]
74 yield self._try_strip_dollars(test[0], test[1])
77
75
78
76
79 def _try_strip_dollars(self, test, result):
77 def _try_strip_dollars(self, test, result):
80 self.assert_equal(strip_dollars(test), result)
78 self.assertEqual(strip_dollars(test), result)
81
79
82
80
83 @dec.parametric
84 def test_strip_files_prefix(self):
81 def test_strip_files_prefix(self):
85 """strip_files_prefix test"""
82 """strip_files_prefix test"""
86 tests = [
83 tests = [
87 ('', ''),
84 ('', ''),
88 ('/files', '/files'),
85 ('/files', '/files'),
89 ('test="/files"', 'test="/files"'),
86 ('test="/files"', 'test="/files"'),
90 ('My files are in `files/`', 'My files are in `files/`'),
87 ('My files are in `files/`', 'My files are in `files/`'),
91 ('<a href="files/test.html">files/test.html</a>', '<a href="test.html">files/test.html</a>')]
88 ('<a href="files/test.html">files/test.html</a>', '<a href="test.html">files/test.html</a>')]
92 for test in tests:
89 for test in tests:
93 yield self._try_files_prefix, test[0], test[1]
90 yield self._try_files_prefix(test[0], test[1])
94
91
95
92
96 def _try_files_prefix(self, test, result):
93 def _try_files_prefix(self, test, result):
97 self.assert_equal(strip_files_prefix(test), result)
94 self.assertEqual(strip_files_prefix(test), result)
98
95
99
96
100 def test_comment_lines(self):
97 def test_comment_lines(self):
101 """comment_lines test"""
98 """comment_lines test"""
102 for line in comment_lines('hello\nworld\n!').split('\n'):
99 for line in comment_lines('hello\nworld\n!').split('\n'):
103 assert line.startswith('# ')
100 assert line.startswith('# ')
104 for line in comment_lines('hello\nworld\n!', 'beep').split('\n'):
101 for line in comment_lines('hello\nworld\n!', 'beep').split('\n'):
105 assert line.startswith('beep')
102 assert line.startswith('beep')
106
103
107
104
108 def test_get_lines(self):
105 def test_get_lines(self):
109 """get_lines test"""
106 """get_lines test"""
110 text = "hello\nworld\n!"
107 text = "hello\nworld\n!"
111 self.assert_equal(get_lines(text, start=1), "world\n!")
108 self.assertEqual(get_lines(text, start=1), "world\n!")
112 self.assert_equal(get_lines(text, end=2), "hello\nworld")
109 self.assertEqual(get_lines(text, end=2), "hello\nworld")
113 self.assert_equal(get_lines(text, start=2, end=5), "!")
110 self.assertEqual(get_lines(text, start=2, end=5), "!")
114 self.assert_equal(get_lines(text, start=-2), "world\n!")
111 self.assertEqual(get_lines(text, start=-2), "world\n!")
115
112
116
113
117 def test_ipython2python(self):
114 def test_ipython2python(self):
118 """ipython2python test"""
115 """ipython2python test"""
119 #TODO: More tests
116 #TODO: More tests
120 results = ipython2python(u'%%pylab\nprint("Hello-World")').replace("u'", "'")
117 results = ipython2python(u'%%pylab\nprint("Hello-World")').replace("u'", "'")
121 self.fuzzy_compare(results, u"get_ipython().run_cell_magic('pylab', '', 'print(\"Hello-World\")')",
118 self.fuzzy_compare(results, u"get_ipython().run_cell_magic('pylab', '', 'print(\"Hello-World\")')",
122 ignore_spaces=True, ignore_newlines=True)
119 ignore_spaces=True, ignore_newlines=True)
@@ -1,151 +1,143 b''
1 """
1 """
2 Contains base test class for nbconvert
2 Contains base test class for nbconvert
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 #Copyright (c) 2013, the IPython Development Team.
5 #Copyright (c) 2013, 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
15
16 import os
16 import os
17 import glob
17 import glob
18 import shutil
18 import shutil
19
19
20 from nose.tools import assert_equal
21 import IPython
20 import IPython
22 from IPython.utils.tempdir import TemporaryWorkingDirectory
21 from IPython.utils.tempdir import TemporaryWorkingDirectory
23 from IPython.utils.process import get_output_error_code
22 from IPython.utils.process import get_output_error_code
24 from IPython.testing.tools import get_ipython_cmd
23 from IPython.testing.tools import get_ipython_cmd
24 from IPython.testing.ipunittest import ParametricTestCase
25
25
26 # a trailing space allows for simpler concatenation with the other arguments
26 # a trailing space allows for simpler concatenation with the other arguments
27 ipy_cmd = get_ipython_cmd(as_string=True) + " "
27 ipy_cmd = get_ipython_cmd(as_string=True) + " "
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Classes and functions
30 # Classes and functions
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33
33
34 class TestsBase(object):
34 class TestsBase(ParametricTestCase):
35 """Base tests class. Contains useful fuzzy comparison and nbconvert
35 """Base tests class. Contains useful fuzzy comparison and nbconvert
36 functions."""
36 functions."""
37
37
38
38
39 def __init__(self):
40
41 # We need to manually add assert_equal to the class instead of inheriting
42 # from unittest.TestCase because if we inherit from unittest.TestCase
43 # support for test generators is lost (a known 'feature' of nose).
44 self.assert_equal = assert_equal
45
46
47 def fuzzy_compare(self, a, b, newlines_are_spaces=True, tabs_are_spaces=True,
39 def fuzzy_compare(self, a, b, newlines_are_spaces=True, tabs_are_spaces=True,
48 fuzzy_spacing=True, ignore_spaces=False,
40 fuzzy_spacing=True, ignore_spaces=False,
49 ignore_newlines=False, case_sensitive=False, leave_padding=False):
41 ignore_newlines=False, case_sensitive=False, leave_padding=False):
50 """
42 """
51 Performs a fuzzy comparison of two strings. A fuzzy comparison is a
43 Performs a fuzzy comparison of two strings. A fuzzy comparison is a
52 comparison that ignores insignificant differences in the two comparands.
44 comparison that ignores insignificant differences in the two comparands.
53 The significance of certain differences can be specified via the keyword
45 The significance of certain differences can be specified via the keyword
54 parameters of this method.
46 parameters of this method.
55 """
47 """
56
48
57 if not leave_padding:
49 if not leave_padding:
58 a = a.strip()
50 a = a.strip()
59 b = b.strip()
51 b = b.strip()
60
52
61 if ignore_newlines:
53 if ignore_newlines:
62 a = a.replace('\n', '')
54 a = a.replace('\n', '')
63 b = b.replace('\n', '')
55 b = b.replace('\n', '')
64
56
65 if newlines_are_spaces:
57 if newlines_are_spaces:
66 a = a.replace('\n', ' ')
58 a = a.replace('\n', ' ')
67 b = b.replace('\n', ' ')
59 b = b.replace('\n', ' ')
68
60
69 if tabs_are_spaces:
61 if tabs_are_spaces:
70 a = a.replace('\t', ' ')
62 a = a.replace('\t', ' ')
71 b = b.replace('\t', ' ')
63 b = b.replace('\t', ' ')
72
64
73 if ignore_spaces:
65 if ignore_spaces:
74 a = a.replace(' ', '')
66 a = a.replace(' ', '')
75 b = b.replace(' ', '')
67 b = b.replace(' ', '')
76
68
77 if fuzzy_spacing:
69 if fuzzy_spacing:
78 a = self.recursive_replace(a, ' ', ' ')
70 a = self.recursive_replace(a, ' ', ' ')
79 b = self.recursive_replace(b, ' ', ' ')
71 b = self.recursive_replace(b, ' ', ' ')
80
72
81 if not case_sensitive:
73 if not case_sensitive:
82 a = a.lower()
74 a = a.lower()
83 b = b.lower()
75 b = b.lower()
84
76
85 self.assert_equal(a, b)
77 self.assertEqual(a, b)
86
78
87
79
88 def recursive_replace(self, text, search, replacement):
80 def recursive_replace(self, text, search, replacement):
89 """
81 """
90 Performs a recursive replacement operation. Replaces all instances
82 Performs a recursive replacement operation. Replaces all instances
91 of a search string in a text string with a replacement string until
83 of a search string in a text string with a replacement string until
92 the search string no longer exists. Recursion is needed because the
84 the search string no longer exists. Recursion is needed because the
93 replacement string may generate additional search strings.
85 replacement string may generate additional search strings.
94
86
95 For example:
87 For example:
96 Replace "ii" with "i" in the string "Hiiii" yields "Hii"
88 Replace "ii" with "i" in the string "Hiiii" yields "Hii"
97 Another replacement yields "Hi" (the desired output)
89 Another replacement yields "Hi" (the desired output)
98
90
99 Parameters:
91 Parameters:
100 -----------
92 -----------
101 text : string
93 text : string
102 Text to replace in.
94 Text to replace in.
103 search : string
95 search : string
104 String to search for within "text"
96 String to search for within "text"
105 replacement : string
97 replacement : string
106 String to replace "search" with
98 String to replace "search" with
107 """
99 """
108 while search in text:
100 while search in text:
109 text = text.replace(search, replacement)
101 text = text.replace(search, replacement)
110 return text
102 return text
111
103
112 def create_temp_cwd(self, copy_filenames=None):
104 def create_temp_cwd(self, copy_filenames=None):
113 temp_dir = TemporaryWorkingDirectory()
105 temp_dir = TemporaryWorkingDirectory()
114
106
115 #Copy the files if requested.
107 #Copy the files if requested.
116 if copy_filenames is not None:
108 if copy_filenames is not None:
117 self.copy_files_to(copy_filenames)
109 self.copy_files_to(copy_filenames)
118
110
119 #Return directory handler
111 #Return directory handler
120 return temp_dir
112 return temp_dir
121
113
122
114
123 def copy_files_to(self, copy_filenames, dest='.'):
115 def copy_files_to(self, copy_filenames, dest='.'):
124 "Copy test files into the destination directory"
116 "Copy test files into the destination directory"
125 if not os.path.isdir(dest):
117 if not os.path.isdir(dest):
126 os.makedirs(dest)
118 os.makedirs(dest)
127 files_path = self._get_files_path()
119 files_path = self._get_files_path()
128 for pattern in copy_filenames:
120 for pattern in copy_filenames:
129 for match in glob.glob(os.path.join(files_path, pattern)):
121 for match in glob.glob(os.path.join(files_path, pattern)):
130 shutil.copyfile(match, os.path.join(dest, os.path.basename(match)))
122 shutil.copyfile(match, os.path.join(dest, os.path.basename(match)))
131
123
132
124
133 def _get_files_path(self):
125 def _get_files_path(self):
134
126
135 #Get the relative path to this module in the IPython directory.
127 #Get the relative path to this module in the IPython directory.
136 names = self.__module__.split('.')[1:-1]
128 names = self.__module__.split('.')[1:-1]
137 names.append('files')
129 names.append('files')
138
130
139 #Build a path using the IPython directory and the relative path we just
131 #Build a path using the IPython directory and the relative path we just
140 #found.
132 #found.
141 path = IPython.__path__[0]
133 path = IPython.__path__[0]
142 for name in names:
134 for name in names:
143 path = os.path.join(path, name)
135 path = os.path.join(path, name)
144 return path
136 return path
145
137
146
138
147 def call(self, parameters, raise_on_error=True):
139 def call(self, parameters, raise_on_error=True):
148 stdout, stderr, retcode = get_output_error_code(ipy_cmd + parameters)
140 stdout, stderr, retcode = get_output_error_code(ipy_cmd + parameters)
149 if retcode != 0 and raise_on_error:
141 if retcode != 0 and raise_on_error:
150 raise OSError(stderr)
142 raise OSError(stderr)
151 return stdout, stderr
143 return stdout, stderr
General Comments 0
You need to be logged in to leave comments. Login now