desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Generate the pages on the disk'
def generate_pages(self, writer):
write = partial(writer.write_file, relative_urls=self.settings[u'RELATIVE_URLS']) self.generate_articles(write) self.generate_period_archives(write) self.generate_direct_templates(write) self.generate_tags(write) self.generate_categories(write) self.generate_authors(write) self.generate_...
'Add the articles into the shared context'
def generate_context(self):
all_articles = [] all_drafts = [] for f in self.get_files(self.settings[u'ARTICLE_PATHS'], exclude=self.settings[u'ARTICLE_EXCLUDES']): article = self.get_cached_data(f, None) if (article is None): try: article = self.readers.read_file(base_path=self.path, path=f,...
'Copy all the paths from source to destination'
def _copy_paths(self, paths, source, destination, output_path, final_path=None):
for path in paths: if final_path: copy(os.path.join(source, path), os.path.join(output_path, destination, final_path), self.settings[u'IGNORE_FILES']) else: copy(os.path.join(source, path), os.path.join(output_path, destination, path), self.settings[u'IGNORE_FILES'])
'Guess at the mime type for the specified file.'
def guess_type(self, path):
mimetype = srvmod.SimpleHTTPRequestHandler.guess_type(self, path) if ((mimetype == u'application/octet-stream') and magic_from_file): mimetype = magic_from_file(path, mime=True) return mimetype
'Open a file to write some content to it. Exit if we have already written to that file, unless one (and no more than one) of the writes has the override parameter set to True.'
def _open_w(self, filename, encoding, override=False):
if (filename in self._overridden_files): if override: raise RuntimeError((u'File %s is set to be overridden twice' % filename)) else: logger.info(u'Skipping %s', filename) filename = os.devnull elif (filename in self._written_files): ...
'Generate a feed with the list of articles provided Return the feed. If no path or output_path is specified, just return the feed object. :param elements: the articles to put on the feed. :param context: the context to get the feed metadata. :param path: the path to output. :param feed_type: the feed type to use (atom ...
def write_feed(self, elements, context, path=None, feed_type=u'atom', override_output=False, feed_title=None):
if (not is_selected_for_writing(self.settings, path)): return self.site_url = context.get(u'SITEURL', path_to_url(get_relative_path(path))) self.feed_domain = context.get(u'FEED_DOMAIN') self.feed_url = u'{}/{}'.format(self.feed_domain, path) feed = self._create_new_feed(feed_type, feed_titl...
'Render the template and write the file. :param name: name of the file to output :param template: template to use to generate the content :param context: dict to pass to the templates. :param relative_urls: use relative urls or absolutes ones :param paginated: dict of article list to paginate - must have the same lengt...
def write_file(self, name, template, context, relative_urls=False, paginated=None, override_output=False, **kwargs):
if ((name is False) or (name == u'') or (not is_selected_for_writing(self.settings, os.path.join(self.output_path, name)))): return elif (not name): return def _write_file(template, localcontext, output_path, name, override): u'Render the template write the file.' ...
'No-op parser'
def read(self, source_path):
content = None metadata = {} return (content, metadata)
'Return the dict containing document metadata'
def _parse_metadata(self, document):
formatted_fields = self.settings[u'FORMATTED_FIELDS'] output = {} for docinfo in document.traverse(docutils.nodes.docinfo): for element in docinfo.children: if (element.tagname == u'field'): (name_elem, body_elem) = element.children name = name_elem.astext...
'Parses restructured text'
def read(self, source_path):
pub = self._get_publisher(source_path) parts = pub.writer.parts content = parts.get(u'body') metadata = self._parse_metadata(pub.document) metadata.setdefault(u'title', parts.get(u'title')) return (content, metadata)
'Return the dict containing document metadata'
def _parse_metadata(self, meta):
formatted_fields = self.settings[u'FORMATTED_FIELDS'] output = {} for (name, value) in meta.items(): name = name.lower() if (name in formatted_fields): formatted_values = u'\n'.join(value) self._md.reset() formatted = self._md.convert(formatted_values) ...
'Parse content and metadata of markdown files'
def read(self, source_path):
self._source_path = source_path self._md = Markdown(**self.settings[u'MARKDOWN']) with pelican_open(source_path) as text: content = self._md.convert(text) if hasattr(self._md, u'Meta'): metadata = self._parse_metadata(self._md.Meta) else: metadata = {} return (content, me...
'Parse content and metadata of HTML files'
def read(self, filename):
with pelican_open(filename) as content: parser = self._HTMLParser(self.settings, filename) parser.feed(content) parser.close() metadata = {} for k in parser.metadata: metadata[k] = self.process_metadata(k, parser.metadata[k]) return (parser.body, metadata)
'Return a content object parsed with the given format.'
def read_file(self, base_path, path, content_class=Page, fmt=None, context=None, preread_signal=None, preread_sender=None, context_signal=None, context_sender=None):
path = os.path.abspath(os.path.join(base_path, path)) source_path = posixize_path(os.path.relpath(path, base_path)) logger.debug(u'Read file %s -> %s', source_path, content_class.__name__) if (not fmt): (_, ext) = os.path.splitext(os.path.basename(path)) fmt = ext[1:] if ...
'Returns a Page object for the given 1-based page number.'
def page(self, number):
bottom = ((number - 1) * self.per_page) top = (bottom + self.per_page) if ((top + self.orphans) >= self.count): top = self.count return Page(self.name, self.object_list[bottom:top], number, self, self.settings)
'Returns the total number of objects, across all pages.'
def _get_count(self):
if (self._count is None): self._count = len(self.object_list) return self._count
'Returns the total number of pages.'
def _get_num_pages(self):
if (self._num_pages is None): hits = max(1, (self.count - self.orphans)) self._num_pages = int(ceil((hits / (float(self.per_page) or 1)))) return self._num_pages
'Returns a 1-based range of pages for iterating through within a template for loop.'
def _get_page_range(self):
return list(range(1, (self.num_pages + 1)))
'Returns the 1-based index of the first object on this page, relative to total objects in the paginator.'
def start_index(self):
if (self.paginator.count == 0): return 0 return ((self.paginator.per_page * (self.number - 1)) + 1)
'Returns the 1-based index of the last object on this page, relative to total objects found (hits).'
def end_index(self):
if (self.number == self.paginator.num_pages): return self.paginator.count return (self.number * self.paginator.per_page)
'Returns URL information as defined in settings. Similar to URLWrapper._from_settings, but specialized to deal with pagination logic.'
def _from_settings(self, key):
rule = None for p in self.settings[u'PAGINATION_PATTERNS']: if (p.min_page <= self.number): rule = p if (not rule): return u'' prop_value = getattr(rule, key) if (not isinstance(prop_value, six.string_types)): logger.warning(u'%s is set to %s', key, pr...
'Load the specified cache within CACHE_PATH in settings only if *load_policy* is True, May use gzip if GZIP_CACHE ins settings is True. Sets caching policy according to *caching_policy*.'
def __init__(self, settings, cache_name, caching_policy, load_policy):
self.settings = settings self._cache_path = os.path.join(self.settings[u'CACHE_PATH'], cache_name) self._cache_data_policy = caching_policy if self.settings[u'GZIP_CACHE']: import gzip self._cache_open = gzip.open else: self._cache_open = open if load_policy: try:...
'Cache data for given file'
def cache_data(self, filename, data):
if self._cache_data_policy: self._cache[filename] = data
'Get cached data for the given file if no data is cached, return the default object'
def get_cached_data(self, filename, default=None):
return self._cache.get(filename, default)
'Save the updated cache'
def save_cache(self):
if self._cache_data_policy: try: mkdir_p(self.settings[u'CACHE_PATH']) with self._cache_open(self._cache_path, u'wb') as fhandle: pickle.dump(self._cache, fhandle) except (IOError, OSError, pickle.PicklingError) as err: logger.warning(u'Could no...
'This sublcass additionally sets filestamp function and base path for filestamping operations'
def __init__(self, settings, cache_name, caching_policy, load_policy):
super(FileStampDataCacher, self).__init__(settings, cache_name, caching_policy, load_policy) method = self.settings[u'CHECK_MODIFIED_METHOD'] if (method == u'mtime'): self._filestamp_func = os.path.getmtime else: try: hash_func = getattr(hashlib, method) def files...
'Cache stamp and data for the given file'
def cache_data(self, filename, data):
stamp = self._get_file_stamp(filename) super(FileStampDataCacher, self).cache_data(filename, (stamp, data))
'Check if the given file has been modified since the previous build. depending on CHECK_MODIFIED_METHOD a float may be returned for \'mtime\', a hash for a function name in the hashlib module or an empty bytes string otherwise'
def _get_file_stamp(self, filename):
try: return self._filestamp_func(filename) except (IOError, OSError, TypeError) as err: logger.warning(u'Cannot get modification stamp for %s\n DCTB %s', filename, err) return u''
'Get the cached data for the given filename if the file has not been modified. If no record exists or file has been modified, return default. Modification is checked by comparing the cached and current file stamp.'
def get_cached_data(self, filename, default=None):
(stamp, data) = super(FileStampDataCacher, self).get_cached_data(filename, (None, default)) if (stamp != self._get_file_stamp(filename)): return default return data
'Identify the best known class of the generator instance The class'
def __init__(self, generator):
self.generator = generator self.generators_info.update(generator.settings.get('I18N_GENERATORS_INFO', {})) for cls in generator.__class__.__mro__: if (cls in self.generators_info): self.info = self.generators_info[cls] break else: self.info = {}
'Iterator over lists of content translations'
def translations_lists(self):
return (getattr(self.generator, name) for name in self.info.get('translations_lists', []))
'Iterator over pairs of normal and hidden contents'
def contents_list_pairs(self):
return (tuple((getattr(self.generator, name) for name in names)) for names in self.info.get('contents_lists', []))
'Function for transforming content to a hidden version'
def hiding_function(self):
hiding_func = self.info.get('hiding_func', (lambda x: x)) return hiding_func
'Get the policy for untranslated content'
def untranslated_policy(self, default):
return self.generator.settings.get(self.info.get('policy', None), default)
'Iterator over all contents'
def all_contents(self):
translations_iterator = chain(*self.translations_lists()) return chain(translations_iterator, *(pair[i] for pair in self.contents_list_pairs() for i in (0, 1)))
'Test that the locale is restored after exiting context'
def test_locale_restored(self):
orig_locale = locale.setlocale(locale.LC_ALL) with i18ns.temporary_locale(): locale.setlocale(locale.LC_ALL, 'C') self.assertEqual(locale.setlocale(locale.LC_ALL), 'C') self.assertEqual(locale.setlocale(locale.LC_ALL), orig_locale)
'Test that the temporary locale is set'
def test_temp_locale_set(self):
with i18ns.temporary_locale('C'): self.assertEqual(locale.setlocale(locale.LC_ALL), 'C')
'Prepare default settings'
def setUp(self):
self.settings = get_settings()
'Test that we get class given as an object'
def test_get_pelican_cls_class(self):
self.settings['PELICAN_CLASS'] = object cls = i18ns.get_pelican_cls(self.settings) self.assertIs(cls, object)
'Test that we get correct class given by string'
def test_get_pelican_cls_str(self):
cls = i18ns.get_pelican_cls(self.settings) self.assertIs(cls, Pelican)
'Generate some sample siteurls'
def setUp(self):
self.siteurl = 'http://example.com' i18ns._SITE_DB['en'] = self.siteurl i18ns._SITE_DB['de'] = (self.siteurl + '/de')
'Remove sites from db'
def tearDown(self):
i18ns._SITE_DB.clear()
'Test getting the path within a site'
def test_get_site_path(self):
self.assertEqual(i18ns.get_site_path(self.siteurl), '/') self.assertEqual(i18ns.get_site_path((self.siteurl + '/de')), '/de')
'Test getting relative paths between sites'
def test_relpath_to_site(self):
self.assertEqual(i18ns.relpath_to_site('en', 'de'), 'de') self.assertEqual(i18ns.relpath_to_site('de', 'en'), '..')
'Test return on missing required signal'
def test_return_on_missing_signal(self):
i18ns._SIGNAL_HANDLERS_DB['tmp_sig'] = None i18ns.register() self.assertNotIn(id(i18ns.save_generator), i18ns.signals.generator_init.receivers)
'Test registration of all signal handlers'
def test_registration(self):
i18ns.register() for (sig_name, handler) in i18ns._SIGNAL_HANDLERS_DB.items(): sig = getattr(i18ns.signals, sig_name) self.assertIn(id(handler), sig.receivers) sig.disconnect(handler)
'Create temporary output and cache folders'
def setUp(self):
self.temp_path = mkdtemp(prefix='pelicantests.') self.temp_cache = mkdtemp(prefix='pelican_cache.')
'Remove output and cache folders'
def tearDown(self):
rmtree(self.temp_path) rmtree(self.temp_cache)
'Test generation of sites with the plugin Compare with recorded output via ``git diff``. To generate output for comparison run the command ``pelican -o test_data/output -s test_data/pelicanconf.py test_data/content`` Remember to remove the output/ folder before that.'
def test_sites_generation(self):
base_path = os.path.dirname(os.path.abspath(__file__)) base_path = os.path.join(base_path, 'test_data') content_path = os.path.join(base_path, 'content') output_path = os.path.join(base_path, 'output') settings_path = os.path.join(base_path, 'pelicanconf.py') settings = read_settings(path=settin...
'Parse content and metadata of asciidoc files'
def read(self, source_path):
from cStringIO import StringIO with pelican_open(source_path) as source: text = StringIO(source.encode('utf8')) content = StringIO() ad = AsciiDocAPI() options = self.settings.get('ASCIIDOC_OPTIONS', []) options = (self.default_options + options) for o in options: ad.options(...
'Shortcut for append method.'
def __call__(self, name, value=None):
self.append(name, value)
'Locate and import asciidoc.py. Initialize instance attributes.'
def __init__(self, asciidoc_py=None):
self.options = Options() self.attributes = {} self.messages = [] cmd = os.environ.get('ASCIIDOC_PY') if cmd: if (not os.path.isfile(cmd)): raise AsciiDocError(('missing ASCIIDOC_PY file: %s' % cmd)) elif asciidoc_py: cmd = asciidoc_py if (not os.path....
'Import asciidoc module (script or compiled .pyc). See http://groups.google.com/group/asciidoc/browse_frm/thread/66e7b59d12cd2f91 for an explanation of why a seemingly straight-forward job turned out quite complicated.'
def __import_asciidoc(self, reload=False):
if (os.path.splitext(self.cmd)[1] in ['.py', '.pyc']): sys.path.insert(0, os.path.dirname(self.cmd)) try: if reload: import __builtin__ __builtin__.reload(self.asciidoc) else: import asciidoc self.asciidoc = asci...
'Compile infile to outfile using backend format. infile can outfile can be file path strings or file like objects.'
def execute(self, infile, outfile=None, backend=None):
self.messages = [] opts = Options(self.options.values) if (outfile is not None): opts('--out-file', outfile) if (backend is not None): opts('--backend', backend) for (k, v) in self.attributes.items(): if ((v == '') or (k[(-1)] in '!@')): s = k elif (v is N...
'@param code code for icon'
def __init__(self, code):
if (not isinstance(code, int)): code = int(code) self.code = code
'render identicon to PIL.Image @param size identicon patchsize. (image size is 3 * [size]) @return PIL.Image'
def render(self, size):
(middle, corner, side, foreColor, backColor) = self.decode(self.code) size = int(size) image = Image.new('RGB', ((size * 3), (size * 3))) draw = ImageDraw.Draw(image) draw.rectangle((0, 0, image.size[0], image.size[1]), fill=0) kwds = {'draw': draw, 'size': size, 'foreColor': foreColor, 'backCol...
'@param size patch size'
def drawPatch(self, pos, turn, invert, type, draw, size, foreColor, backColor):
path = self.PATH_SET[type] if (not path): invert = (not invert) path = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)] patch = ImagePath.Path(path) if invert: (foreColor, backColor) = (backColor, foreColor) mat = ((Matrix2D.rotateSquare(turn, pivot=(0.5, 0.5)) * ...
':param path: Path to check :returns: True if path is managed by git'
def is_file_managed_by_git(self, path):
(status, _stdout, _stderr) = self.git.execute(['git', 'ls-files', path, '--error-unmatch'], with_extended_output=True, with_exceptions=False) return (status == 0)
'Does a file have local changes not yet committed :returns: True if file has local changes'
def is_file_modified(self, path):
(status, _stdout, _stderr) = self.git.execute(['git', 'diff', '--quiet', 'HEAD', path], with_extended_output=True, with_exceptions=False) return (status != 0)
'Get all commits including path following the file through renames :param path: Path which we will find commits for :returns: Sequence of commit objects. Newest to oldest'
def get_commits_following(self, path):
return [commit for (commit, _) in self.get_commits_and_names_iter(path)]
'Get all commits including a given path following renames'
def get_commits_and_names_iter(self, path):
log_result = self.git.log('--pretty=%H', '--follow', '--name-only', '--', path).splitlines() for (commit_sha, _, filename) in grouper(log_result, 3): (yield (self.repo.commit(commit_sha), filename))
'Get all commits including path :param path: Path which we will find commits for :param bool follow: If True we will follow path through renames :returns: Sequence of commit objects. Newest to oldest'
def get_commits(self, path, follow=False):
if follow: return self.get_commits_following(path) else: return self._get_commits(path)
'Get all commits including path without following renames :param path: Path which we will find commits for :returns: Sequence of commit objects. Newest to oldest'
def _get_commits(self, path):
return self.repo.commits(path=path)
'Get datetime of commit comitted_date'
@staticmethod def get_commit_date(commit, tz_name):
return set_date_tzinfo(datetime.fromtimestamp(mktime(commit.committed_date)), tz_name=tz_name)
'Get all commits including path without following renames :param path: Path which we will find commits for :returns: Sequence of commit objects. Newest to oldest .. NOTE :: If this fails it could be that your gitpython version is out of sync with the git binary on your distro. Make sure you use the correct gitpython ve...
def _get_commits(self, path):
return list(self.repo.iter_commits(paths=path))
'Get datetime of commit comitted_date'
@staticmethod def get_commit_date(commit, tz_name):
return set_date_tzinfo(datetime.fromtimestamp(commit.committed_date), tz_name=tz_name)
'Is committed'
@memoized def is_committed(self):
return (len(self.get_commits()) > 0)
'Has content been modified since last commit'
@memoized def is_modified(self):
return self.git.is_file_modified(self.content.source_path)
'Is content stored in a file managed by git'
@memoized def is_managed_by_git(self):
return self.git.is_file_managed_by_git(self.content.source_path)
'Get all commits involving this filename :returns: List of commits newest to oldest'
@memoized def get_commits(self):
if (not self.is_managed_by_git()): return [] return self.git.get_commits(self.content.source_path, self.follow)
'Get oldest commit involving this file :returns: Oldest commit'
@memoized def get_oldest_commit(self):
return self.git.get_commits(self.content.source_path, self.follow)[(-1)]
'Get oldest commit involving this file :returns: Newest commit'
@memoized def get_newest_commit(self):
return self.git.get_commits(self.content.source_path, follow=False)[0]
'Get the original filename of this content. Implies follow'
@memoized def get_oldest_filename(self):
commit_and_name_iter = self.git.get_commits_and_names_iter(self.content.source_path) (_commit, name) = commit_and_name_iter.next() return name
'Get datetime of oldest commit involving this file :returns: Datetime of oldest commit'
@memoized def get_oldest_commit_date(self):
oldest_commit = self.get_oldest_commit() return self.git.get_commit_date(oldest_commit, self.tz_name)
'Get datetime of newest commit involving this file :returns: Datetime of newest commit'
@memoized def get_newest_commit_date(self):
newest_commit = self.get_newest_commit() return self.git.get_commit_date(newest_commit, self.tz_name)
'Setup context'
def generate_context(self):
self.permalink_output_path = os.path.join(self.output_path, self.settings['PERMALINK_PATH']) self.permalink_id_metadata_key = self.settings['PERMALINK_ID_METADATA_KEY']
'Generate redirect files'
def generate_output(self, writer=None):
logger.info('Generating permalink files in %r', self.permalink_output_path) clean_output_dir(self.permalink_output_path, []) mkdir_p(self.permalink_output_path) for content in itertools.chain(self.context['articles'], self.context['pages']): for permalink_id in content.get_permalink_...
'Parse content and metadata of an rdf file'
def read(self, source_path):
logger.debug(('Loading graph described in ' + source_path)) graph = rdflib.Graph() graph.load(source_path) meta = {} queries = [f for f in listdir(self.settings['VOC_QUERIES_PATH']) if (isfile(join(self.settings['VOC_QUERIES_PATH'], f)) and f.endswith('.sparql'))] for query_path in q...
'Process the metadata dict, lowercasing the keys and textilizing the value of the \'summary\' key (if present). Keys that share the same lowercased form will be overridden in some arbitrary order.'
def _parse_metadata(self, meta):
output = {} for (name, value) in meta.items(): name = name.lower() if (name == u'summary'): value = textile(value) output[name] = self.process_metadata(name, value) return output
'Parse content and metadata of textile files.'
def read(self, source_path):
with pelican_open(source_path) as text: parts = text.split(u'----', 1) if (len(parts) == 2): headerlines = parts[0].splitlines() headerpairs = map((lambda l: l.split(u':', 1)), headerlines) headerdict = {pair[0]: pair[1].strip() for pair in headerpairs if (len(pai...
'Construct a Link from an SRE_Match. :param context: The shared context between generators. :param content_object: The associated pelican.contents.Content. :param match: An SRE_Match obtained by applying the regex to my content.'
def __init__(self, context, content_object, match):
self.context = context self.content_object = content_object self.markup = match.group('markup') self.quote = match.group('quote') self.cmd = match.group('cmd') self.__url = urlparse(match.group('url')) self.path = self.__url.path
'Separates out <div class="math"> from the parent tag <p>. Anything in between is put into its own parent tag of <p>'
def correct_html(self, root, children, div_math, insert_idx, text):
current_idx = 0 for idx in div_math: el = markdown.util.etree.Element('p') el.text = text el.extend(children[current_idx:idx]) if ((len(el) != 0) or (el.text and (not el.text.isspace()))): root.insert(insert_idx, el) insert_idx += 1 text = children...
'Searches for <div class="math"> that are children in <p> tags and corrects the invalid HTML that results'
def run(self, root):
math_tag_class = self.pelican_mathjax_extension.getConfig('math_tag_class') for parent in root: div_math = [] children = list(parent) for div in parent.findall('div'): if (div.get('class') == math_tag_class): div_math.append(children.index(div)) if (no...
'Decorator to register a new include tag'
@classmethod def register(cls, tag):
def dec(func): if (tag in _LiquidTagsPreprocessor._tags): warnings.warn(("Enhanced Markdown: overriding tag '%s'" % tag)) _LiquidTagsPreprocessor._tags[tag] = func return func return dec
'Create temporary output and cache folders'
def setUp(self):
self.temp_path = mkdtemp(prefix='pelicantests.') self.temp_cache = mkdtemp(prefix='pelican_cache.') os.chdir(TEST_DATA_DIR)
'Remove output and cache folders'
def tearDown(self):
rmtree(self.temp_path) rmtree(self.temp_cache) os.chdir(PLUGIN_DIR)
'Test generation of site with the plugin.'
@pytest.mark.skipif((IPYTHON_VERSION >= 3), reason='output must be created with ipython version 2') def test_generate_with_ipython3(self):
base_path = os.path.dirname(os.path.abspath(__file__)) base_path = os.path.join(base_path, 'test_data') content_path = os.path.join(base_path, 'content') output_path = os.path.join(base_path, 'output') settings_path = os.path.join(base_path, 'pelicanconf.py') settings = read_settings(path=settin...
'Test generation of site with the plugin.'
@pytest.mark.skipif((IPYTHON_VERSION < 3), reason='output must be created with ipython version 3') def test_generate_with_ipython2(self):
base_path = os.path.dirname(os.path.abspath(__file__)) base_path = os.path.join(base_path, 'test_data') content_path = os.path.join(base_path, 'content') output_path = os.path.join(base_path, 'output') settings_path = os.path.join(base_path, 'pelicanconf.py') settings = read_settings(path=settin...
'Parse content and metadata of creole files'
def read(self, source_path):
self._metadata = {} with pelican_open(source_path) as text: content = creole2html(text, macros={'header': self._parse_header_macro, 'code': self._parse_code_macro}) return (content, self._metadata)
'returns a list of html snippets fetched from github actitivy feed'
def fetch(self):
entries = [] for activity in self.activities[u'entries']: entries.append([element for element in [activity[u'title'], activity[u'content'][0][u'value']]]) return entries[0:self.max_entries]
'Check the presence of `css_file` in `html_file`.'
def check_link_tag(self, css_file, html_file):
link_tag = '<link rel="stylesheet" href="{css_file}">'.format(css_file=css_file) html = open(html_file).read() self.assertRegexpMatches(html, link_tag)
'Parse content and metadata of markdown files. Rendering them as jinja templates first.'
def read(self, source_path):
self._source_path = source_path self._md = Markdown(extensions=self.settings['MARKDOWN']['extensions']) with pelican_open(source_path) as text: text = self.env.from_string(text).render() content = self._md.convert(text) metadata = self._parse_metadata(self._md.Meta) return (content, ...
'Given a filename, resize and save the image per the specification into out_path :param in_path: path to image file to save. Must be supported by PIL :param out_path: path to the directory root for the outputted thumbnails to be stored :return: None'
def resize_file_to(self, in_path, out_path, keep_filename=False):
if keep_filename: filename = path.join(out_path, path.basename(in_path)) else: filename = path.join(out_path, self.get_thumbnail_name(in_path)) out_path = path.dirname(filename) if (not path.exists(out_path)): os.makedirs(out_path) if (not path.exists(filename)): try:...
'Test a file that is in the root of img_path.'
def testRoot(self):
r = _resizer('square', '100', self.img_path) new_name = r.get_thumbnail_name(self.path('sample_image.jpg')) self.assertEqual('sample_image_square.jpg', new_name)
'Test a file that is in a sub-directory of img_path.'
def testSubdir(self):
r = _resizer('square', '100', self.img_path) new_name = r.get_thumbnail_name(self.path('subdir', 'sample_image.jpg')) self.assertEqual('subdir/sample_image_square.jpg', new_name)
'Parse content and metadata of markdown files'
def read(self, filename):
QUIET = self.settings.get('RMD_READER_KNITR_QUIET', True) ENCODING = self.settings.get('RMD_READER_KNITR_ENCODING', 'UTF-8') CLEANUP = self.settings.get('RMD_READER_CLEANUP', True) RENAME_PLOT = self.settings.get('RMD_READER_RENAME_PLOT', 'chunklabel') if (type(RENAME_PLOT) is bool): logger....
'Include a file as part of the content of this reST file.'
def run(self):
if (not self.state.document.settings.file_insertion_enabled): raise self.warning((u'"%s" directive disabled.' % self.name)) source = self.state_machine.input_lines.source(((self.lineno - self.state_machine.input_offset) - 1)) source_dir = os.path.dirname(os.path.abspath(source)) path = dir...
'API is in compatibility mode, but we call GetStatus on a tweet that was written in extended mode. The tweet in question is exactly 140 characters and attaches a photo.'
@responses.activate def test_extended_in_compat_mode(self):
with open(u'testdata/3.2/extended_tweet_in_compat_mode.json') as f: resp_data = f.read() status = twitter.Status.NewFromJsonDict(json.loads(resp_data)) self.assertTrue(status) self.assertEqual(status.id, 782737772490600448) self.assertEqual(status.text, u'has more details about t...
'API is in extended mode, and we call GetStatus on a tweet that was written in extended mode. The tweet in question is exactly 140 characters and attaches a photo.'
@responses.activate def test_extended_in_extended_mode(self):
with open(u'testdata/3.2/extended_tweet_in_extended_mode.json') as f: resp_data = f.read() status = twitter.Status.NewFromJsonDict(json.loads(resp_data)) self.assertTrue(status) self.assertEqual(status.id, 782737772490600448) self.assertEqual(status.full_text, u'has more details abo...
'Test the twitter.User constructor'
def testInit(self):
twitter.User(id=673483, name='DeWitt', screen_name='dewitt', description=u'Indeterminate things', url='https://twitter.com/dewitt', profile_image_url='https://twitter.com/system/user/profile_image/673483/normal/me.jpg', status=self._GetSampleStatus())