"""Test cases for Snippets.""" from .. import util import os from pymdownx.snippets import SnippetMissingError from unittest.mock import patch, MagicMock import urllib.error BASE = os.path.abspath(os.path.dirname(__file__)) class TestSnippetDedent(util.MdCase): """Test snippet cases.""" extension = [ 'pymdownx.snippets', 'pymdownx.superfences' ] extension_configs = { 'pymdownx.snippets': { 'base_path': [os.path.join(BASE, '_snippets')], 'dedent_subsections': True } } def test_dedent_section(self): """Test dedenting sections.""" self.check_markdown( R''' ```text ---8<--- "indented.txt:py-section" ``` ''', R'''
def some_method(self, param):
"""Docstring."""
return param
def some_method(self, param):
"""Docstring."""
return param
Paragraph
def some_method(self, param):
"""Docstring."""
return param
''',
True
)
class TestSnippets(util.MdCase):
"""Test snippet cases."""
extension = [
'pymdownx.snippets', 'pymdownx.superfences'
]
extension_configs = {
'pymdownx.snippets': {
'base_path': [os.path.join(BASE, '_snippets')]
}
}
def test_inline(self):
"""Test inline."""
self.check_markdown(
R'''
---8<--- "loop.txt"
---8<--- "a.txt"
---8<--- "b.txt"
;---8<--- "b.txt"
- Testing indentation
---8<--- "b.txt"
''',
R'''
Snippet
Snippet
---8<--- "b.txt"
Testing indentation
Snippet
Snippet
Snippet
---8<--- d.txt ---8<---
Testing indentation
Snippet
Snippet
Snippet
Snippet
Snippet
''', True ) def test_start_line_inline(self): """Test starting line with inline syntax.""" self.check_markdown( R''' ---8<--- "lines.txt:4" ''', '''Content resides on various lines. If we use line specifiers, we can select any number of lines we want.
This is the end of the file. There is no more.
''', True ) def test_start_1_1(self): """Test beginning of file, single line range.""" self.check_markdown( R''' ---8<--- "lines.txt:1:1" ''', '''This is a multi-line
''', True ) def test_start_1_2(self): """Test beginning of file span of multiple lines.""" self.check_markdown( R''' ---8<--- "lines.txt:1:2" ''', '''This is a multi-line snippet.
''', True ) def test_start_multi(self): """Test multiple line specifiers.""" self.check_markdown( R''' ---8<--- "lines.txt:1:2,8:9" ''', '''This is a multi-line snippet. This is the end of the file. There is no more.
''', True ) def test_start_multi_no_end(self): """Test multiple line specifiers but the last has no end.""" self.check_markdown( R''' ---8<--- "lines.txt:1:2,8" ''', '''This is a multi-line snippet. This is the end of the file. There is no more.
''', True ) def test_start_multi_no_start(self): """Test multiple line specifiers but the last has no start.""" self.check_markdown( R''' ---8<--- "lines.txt:1:2,:8" ''', '''This is a multi-line snippet. This is a multi-line snippet.
Content resides on various lines. If we use line specifiers, we can select any number of lines we want.
This is the end of the file.
''', True ) def test_start_multi_hanging_comma(self): """Test multiple line specifiers but there is a hanging comma.""" self.check_markdown( R''' ---8<--- "lines.txt:1:2," ''', ''' ''', True ) def test_negative_range(self): """Test negative indexing range.""" self.check_markdown( R''' ---8<--- "lines.txt:-3:-2" ''', '''This is the end of the file. There is no more.
''', True ) def test_negative_single(self): """Test negative indexing single line.""" self.check_markdown( R''' ---8<--- "lines.txt:-2:-2" ''', '''There is no more.
''', True ) def test_mixed_negative(self): """Test negative indexing single line.""" self.check_markdown( R''' ---8<--- "lines.txt:8:-2" ---8<--- "lines.txt:-3:9" ''', '''This is the end of the file. There is no more.
This is the end of the file. There is no more.
''', True ) def test_start_negative_multi(self): """Test multiple line specifiers with negative indexes.""" self.check_markdown( R''' ---8<--- "lines.txt:1:2,-3:-2" ''', '''This is a multi-line snippet. This is the end of the file. There is no more.
''', True ) def test_end_line_inline(self): """Test ending line with inline syntax.""" self.check_markdown( R''' ---8<--- "lines.txt::6" ''', '''This is a multi-line snippet.
Content resides on various lines. If we use line specifiers, we can select any number of lines we want.
''', True ) def test_start_end_line_inline(self): """Test starting and ending line with inline syntax.""" self.check_markdown( R''' ---8<--- "lines.txt:4:6" ''', '''Content resides on various lines. If we use line specifiers, we can select any number of lines we want.
''', True ) def test_start_line_block(self): """Test starting line with block syntax.""" self.check_markdown( R''' --8<-- lines.txt:4 --8<-- ''', '''Content resides on various lines. If we use line specifiers, we can select any number of lines we want.
This is the end of the file. There is no more.
''', True ) def test_end_line_block(self): """Test ending line with block syntax.""" self.check_markdown( R''' --8<-- lines.txt::6 --8<-- ''', '''This is a multi-line snippet.
Content resides on various lines. If we use line specifiers, we can select any number of lines we want.
''', True ) def test_start_end_line_block(self): """Test starting and ending line with block syntax.""" self.check_markdown( R''' --8<-- lines.txt:4:6 --8<-- ''', '''Content resides on various lines. If we use line specifiers, we can select any number of lines we want.
''', True ) def test_section_inline(self): """Test section partial in inline snippet.""" self.check_markdown( R''' ``` --8<-- "section.txt:css-section" ``` ''', '''div {
color: red;
}
div {
color: red;
}
div {
color: red;
background-color: white;
padding: 16px
}
div {
color: red;
/* --8<-- [start: css-section4] */
background-color: white;
padding: 16px
/* --8<-- [end: css-section4] */
}
div {
color: red;
background-color: white;
padding: 16px
}
div {
color: red;
/* --8<-- [start: css-section4] */
background-color: white;
padding: 16px
/* --8<-- [end: css-section4] */
}
div {
color: red;
background-color: white;
padding: 16px
}
div {
color: red;
background-color: white;
padding: 16px
}
content
content
content
Snippet
''', True ) class TestSnippetsFile(util.MdCase): """Test snippet file case.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': os.path.join(BASE, '_snippets', 'b.txt') } } def test_user(self): """Test file.""" self.check_markdown( R''' --8<-- "b.txt" ''', '''Snippet
''', True ) class TestSnippetsNested(util.MdCase): """Test nested restriction.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': os.path.join(BASE, '_snippets', 'nested'), 'check_paths': True } } def test_restricted(self): """Test file restriction.""" with self.assertRaises(SnippetMissingError): self.check_markdown( R''' --8<-- "../b.txt" ''', '''Snippet
''', True ) def test_restricted_directory_traversal(self): """Test file restriction directory traversal.""" with self.assertRaises(SnippetMissingError): self.check_markdown( R''' --8<-- "../nested_b.txt" ''', '''Snippet
''', True ) class TestSnippetsMultiNested(util.MdCase): """Test multi-nested restriction.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': os.path.join(BASE), 'check_paths': True } } def test_restricted_multi_nested(self): """Test file restriction.""" self.check_markdown( R''' --8<-- "_snippets/b.txt" ''', '''Snippet
''', True ) class TestSnippetsNestedUnrestricted(util.MdCase): """Test nested no bounds.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': os.path.join(BASE, '_snippets', 'nested'), 'restrict_base_path': False } } def test_restricted(self): """Test file restriction.""" self.check_markdown( R''' --8<-- "../b.txt" ''', '''Snippet
''', True ) def test_restricted_directory_traversal(self): """Test file restriction directory traversal.""" self.check_markdown( R''' --8<-- "../nested_b.txt" ''', '''Snippet
''', True ) class TestSnippetsAutoAppend(util.MdCase): """Test snippet file case.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': [os.path.join(BASE, '_snippets')], 'auto_append': ['b.txt'] } } def test_auto_append(self): """Test auto append.""" self.check_markdown( R''' Test ''', '''Test
Snippet
''', True ) class TestSnippetsMissing(util.MdCase): """Test snippet file case.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': [os.path.join(BASE, '_snippets')], 'check_paths': True } } def test_good(self): """Test found file.""" self.check_markdown( ''' --8<--- "d.txt" ''', '''Snippet
''', True ) def test_top_level(self): """Test top level.""" with self.assertRaises(SnippetMissingError): self.check_markdown( R''' --8<-- "not-here.txt" ''', ''' ''', True ) def test_nested(self): """Test nested.""" with self.assertRaises(SnippetMissingError): self.check_markdown( R''' --8<-- "missing.txt" ''', ''' ''', True ) def test_missing_file_lines(self): """Test missing file with line numbers.""" with self.assertRaises(SnippetMissingError): self.check_markdown( R''' --8<-- ":3:4" ''', ''' ''', True ) def test_missing_section(self): """Test missing section.""" with self.assertRaises(SnippetMissingError): self.check_markdown( R''' --8<-- "section.txt:missing-section" ''', ''' ''', True ) class TestSnippetsGracefulMissing(util.MdCase): """Test snippet file case.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': [os.path.join(BASE, '_snippets')] } } def test_top_level(self): """Test top level.""" self.check_markdown( R''' --8<-- "not-here.txt" ''', ''' ''', True ) def test_nested(self): """Test nested.""" self.check_markdown( R''' --8<-- "missing.txt" ''', ''' ''', True ) def test_missing_lines(self): """Test missing file with lines.""" self.check_markdown( R''' --8<-- ":3:4" ''', ''' ''', True ) class TestURLSnippets(util.MdCase): """Test snippet URL cases.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': [os.path.join(BASE, '_snippets')], 'url_download': True } } @patch('urllib.request.urlopen') def test_url(self, mock_urlopen): """Test URL.""" cm = MagicMock() cm.status = 200 cm.code = 200 cm.read.return_value = b'contents' cm.headers = {'content-length': '8'} cm.__enter__.return_value = cm mock_urlopen.return_value = cm self.check_markdown( R''' --8<-- "https://test.com/myfile.md" ''', '''contents
''', True ) @patch('urllib.request.urlopen') def test_url_nested(self, mock_urlopen): """Test nested URLs.""" cm = MagicMock() cm.status = 200 cm.code = 200 cm.read.side_effect = [b'content\n\n--8<-- "https://test.com/myfile2.md"', b'other'] cm.headers = {'content-length': '8'} cm.__enter__.return_value = cm mock_urlopen.return_value = cm self.check_markdown( R''' --8<-- "https://test.com/myfile.md" ''', '''content
other
''', True ) @patch('urllib.request.urlopen') def test_url_nested_duplicatqe(self, mock_urlopen): """Test nested duplicate file.""" cm = MagicMock() cm.status = 200 cm.code = 200 cm.read.side_effect = [b'content\n\n--8<-- "https://test.com/myfile.md"', b'other'] cm.headers = {'content-length': '8'} cm.__enter__.return_value = cm mock_urlopen.return_value = cm self.check_markdown( R''' --8<-- "https://test.com/myfile.md" ''', '''content
''', True ) @patch('urllib.request.urlopen') def test_url_nested_file(self, mock_urlopen): """Test nested file in URL.""" cm = MagicMock() cm.status = 200 cm.code = 200 cm.read.return_value = b'content\n\n--8<-- "b.txt"' cm.headers = {'content-length': '8'} cm.__enter__.return_value = cm mock_urlopen.return_value = cm self.check_markdown( R''' --8<-- "https://test.com/myfile.md" ''', '''content
''', True ) @patch('urllib.request.urlopen') def test_url_lines(self, mock_urlopen): """Test specifying specific lines in a URL.""" with open('tests/test_extensions/_snippets/lines.txt', 'rb') as f: content = f.read() length = len(content) cm = MagicMock() cm.status = 200 cm.code = 200 cm.read.return_value = content cm.headers = {'content-length': length} cm.__enter__.return_value = cm mock_urlopen.return_value = cm self.check_markdown( R''' --8<-- "https://test.com/myfile.md:4:6" ''', '''Content resides on various lines. If we use line specifiers, we can select any number of lines we want.
''', True ) @patch('urllib.request.urlopen') def test_missing(self, mock_urlopen): """Test missing URL.""" cm = MagicMock() cm.status = 404 cm.code = 404 cm.read.return_value = b'' cm.headers = {'content-length': '0'} cm.__enter__.return_value = cm mock_urlopen.return_value = cm self.check_markdown( R''' --8<-- "https://test.com/myfile.md" ''', '', True ) @patch('urllib.request.urlopen') def test_missing_content_length(self, mock_urlopen): """Test missing content length header.""" cm = MagicMock() cm.status = 200 cm.code = 200 cm.read.return_value = b'' cm.headers = {} cm.__enter__.return_value = cm mock_urlopen.return_value = cm self.check_markdown( R''' --8<-- "https://test.com/myfile.md" ''', ''' ''', True ) @patch('urllib.request.urlopen') def test_missing_content_length_too_big(self, mock_urlopen): """Test content length too big.""" cm = MagicMock() cm.status = 200 cm.code = 200 cm.read.return_value = b'' cm.headers = {'content-length': str(1024 * 1024 * 48)} cm.__enter__.return_value = cm mock_urlopen.return_value = cm with self.assertRaises(ValueError): self.check_markdown( R''' --8<-- "https://test.com/myfile.md" ''', ''' ''', True ) @patch('urllib.request.urlopen') def test_content_too_big_no_content_length(self, mock_urlopen): """Test content length too big.""" cm = MagicMock() cm.status = 200 cm.code = 200 cm.read = lambda count: b"-" * (1024 * 1024 * 48) cm.__enter__.return_value = cm mock_urlopen.return_value = cm with self.assertRaises(ValueError): self.check_markdown( R''' --8<-- "https://test.com/myfile.md" ''', ''' ''', True ) @patch('urllib.request.urlopen') def test_content_length_zero(self, mock_urlopen): """Test empty content.""" cm = MagicMock() cm.status = 200 cm.code = 200 cm.read.return_value = b'' cm.headers = {'content-length': '0'} cm.__enter__.return_value = cm mock_urlopen.return_value = cm self.check_markdown( R''' --8<-- "https://test.com/myfile.md" ''', '', True ) @patch('urllib.request.urlopen') def test_url_sections(self, mock_urlopen): """Test specifying a section in a URL.""" with open('tests/test_extensions/_snippets/section.txt', 'rb') as f: content = f.read() length = len(content) cm = MagicMock() cm.status = 200 cm.code = 200 cm.read.return_value = content cm.headers = {'content-length': length} cm.__enter__.return_value = cm mock_urlopen.return_value = cm self.check_markdown( R''' --8<-- "https://test.com/myfile.md:html-section" ''', '''content
def some_method(self, param):
"""Docstring."""
return param
contents
''', True ) class TestURLSnippetsMissing(util.MdCase): """Test snippet URL cases with missing URL and 'check paths'.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': [os.path.join(BASE, '_snippets')], 'url_download': True, 'url_max_size': 0, 'check_paths': True } } @patch('urllib.request.urlopen') def test_missing(self, mock_urlopen): """Test missing URL.""" cm = MagicMock() cm.status = 404 cm.code = 404 cm.read.return_value = b'' cm.headers = {'content-length': '0'} cm.__enter__.return_value = cm mock_urlopen.return_value = cm with self.assertRaises(SnippetMissingError): self.check_markdown( R''' --8<-- "https://test.com/myfile.md" ''', '', True ) class TestURLSnippetsRetry(util.MdCase): """Test snippet URL retry cases.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': [os.path.join(BASE, '_snippets')], 'url_download': True, 'check_paths': True } } @patch('urllib.request.urlopen') @patch('time.sleep') def test_successful_retry(self, mock_sleep, mock_urlopen): """Test successful retry after 429.""" cm = MagicMock() cm.status = 200 cm.code = 200 cm.read.return_value = b'content\n' cm.headers = {'content-length': '8'} cm.__enter__.return_value = cm cm.__exit__.return_value = None # Mock __exit__ mock_urlopen.side_effect = [ urllib.error.HTTPError('http://example.com', 429, 'Too Many Requests', {}, None), urllib.error.HTTPError('http://example.com', 429, 'Too Many Requests', {}, None), cm ] self.check_markdown( R''' --8<-- "http://example.com" ''', '''content
''', True ) mock_sleep.assert_any_call(2) mock_sleep.assert_any_call(4) @patch('urllib.request.urlopen') @patch('time.sleep') def test_exhaust_retries(self, mock_sleep, mock_urlopen): """Test exhausting all retries.""" mock_urlopen.side_effect = [ urllib.error.HTTPError('http://example.com', 429, 'Too Many Requests', {}, None), urllib.error.HTTPError('http://example.com', 429, 'Too Many Requests', {}, None), urllib.error.HTTPError('http://example.com', 429, 'Too Many Requests', {}, None), urllib.error.HTTPError('http://example.com', 429, 'Too Many Requests', {}, None), ] with self.assertRaises(SnippetMissingError) as cm: self.md.convert( R''' --8<-- "http://example.com" ''' ) self.assertIn("Cannot download snippet 'http://example.com' (HTTP Error 429)", str(cm.exception)) mock_sleep.assert_any_call(2) mock_sleep.assert_any_call(4) mock_sleep.assert_any_call(6) class TestURLSnippetsRetryCustomBackoff(util.MdCase): """Test snippet URL retry cases with custom backoff.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': [os.path.join(BASE, '_snippets')], 'url_download': True, 'backoff_factor': 1.5, 'check_paths': True } } @patch('urllib.request.urlopen') @patch('time.sleep') def test_custom_backoff(self, mock_sleep, mock_urlopen): """Test custom backoff factor.""" cm = MagicMock() cm.status = 200 cm.code = 200 cm.read.return_value = b'content\n' cm.headers = {'content-length': '8'} cm.__enter__.return_value = cm cm.__exit__.return_value = None # Mock __exit__ mock_urlopen.side_effect = [ urllib.error.HTTPError('http://example.com', 429, 'Too Many Requests', {}, None), cm ] self.check_markdown( R''' --8<-- "http://example.com" ''', '''content
''', True ) mock_sleep.assert_called_once_with(1.5) class TestURLSnippetsRetryCustomRetries(util.MdCase): """Test snippet URL retry cases with custom retries.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': [os.path.join(BASE, '_snippets')], 'url_download': True, 'max_retries': 2, 'check_paths': True } } @patch('urllib.request.urlopen') @patch('time.sleep') def test_custom_max_retries(self, mock_sleep, mock_urlopen): """Test custom max retries.""" mock_urlopen.side_effect = [ urllib.error.HTTPError('http://example.com', 429, 'Too Many Requests', {}, None), urllib.error.HTTPError('http://example.com', 429, 'Too Many Requests', {}, None), urllib.error.HTTPError('http://example.com', 429, 'Too Many Requests', {}, None), ] with self.assertRaises(SnippetMissingError) as cm: self.md.convert( R''' --8<-- "http://example.com" ''' ) self.assertIn("Cannot download snippet 'http://example.com' (HTTP Error 429)", str(cm.exception)) mock_sleep.assert_any_call(2) mock_sleep.assert_any_call(4)