diff --git a/.travis.yml b/.travis.yml
index 0bfc4ef..a298393 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,15 +1,18 @@
language: python
python:
- - 2.7
+ - 2.7
+ - 3.4
+ - 3.5
+ - 3.6
sudo: false
-env:
- - TOX_ENV=lint
- - TOX_ENV=py27
- - TOX_ENV=py34
+matrix:
+ include:
+ - python: 2.7
+ script: tox -e lint
install:
- - pip install tox
+ - pip install tox-travis
script:
- - tox -e $TOX_ENV
+ - tox
notifications:
slack:
rooms:
diff --git a/readthedocs_ext/_static/searchtools.js_t b/readthedocs_ext/_static/searchtools.js_t
deleted file mode 100644
index 895516c..0000000
--- a/readthedocs_ext/_static/searchtools.js_t
+++ /dev/null
@@ -1,440 +0,0 @@
-/*
- * searchtools.js_t
- * ~~~~~~~~~~~~~~~~
- *
- * Sphinx JavaScript utilities for the full-text search.
- *
- * :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
- * :license: BSD, see LICENSE for details.
- *
- */
-
-{% if search_language_stemming_code %}
-/* Non-minified version JS is _stemmer.js if file is provided */ {% endif -%}
-{{ search_language_stemming_code|safe }}
-
-{% if search_scorer_tool %}
-{{ search_scorer_tool|safe }}
-{% else %}
-/**
- * Simple result scoring code.
- */
-var Scorer = {
- // Implement the following function to further tweak the score for each result
- // The function takes a result array [filename, title, anchor, descr, score]
- // and returns the new score.
- /*
- score: function(result) {
- return result[4];
- },
- */
-
- // query matches the full name of an object
- objNameMatch: 11,
- // or matches in the last dotted part of the object name
- objPartialMatch: 6,
- // Additive scores depending on the priority of the object
- objPrio: {0: 15, // used to be importantResults
- 1: 5, // used to be objectResults
- 2: -5}, // used to be unimportantResults
- // Used when the priority is not in the mapping.
- objPrioDefault: 0,
-
- // query found in title
- title: 15,
- // query found in terms
- term: 5
-};
-{% endif %}
-
-/**
- * Search Module
- */
-var Search = {
-
- _index : null,
- _queued_query : null,
- _pulse_status : -1,
-
- init : function() {
- var params = $.getQueryParameters();
- if (params.q) {
- var query = params.q[0];
- $('input[name="q"]')[0].value = query;
- this.performSearch(query);
- }
- },
-
- loadIndex : function(url) {
- $.ajax({type: "GET", url: url, data: null,
- dataType: "script", cache: true,
- complete: function(jqxhr, textstatus) {
- if (textstatus != "success") {
- document.getElementById("searchindexloader").src = url;
- }
- }});
- },
-
- setIndex : function(index) {
- var q;
- this._index = index;
- if ((q = this._queued_query) !== null) {
- this._queued_query = null;
- Search.query(q);
- }
- },
-
- hasIndex : function() {
- return this._index !== null;
- },
-
- deferQuery : function(query) {
- this._queued_query = query;
- },
-
- stopPulse : function() {
- this._pulse_status = 0;
- },
-
- startPulse : function() {
- if (this._pulse_status >= 0)
- return;
- function pulse() {
- var i;
- Search._pulse_status = (Search._pulse_status + 1) % 4;
- var dotString = '';
- for (i = 0; i < Search._pulse_status; i++)
- dotString += '.';
- Search.dots.text(dotString);
- if (Search._pulse_status > -1)
- window.setTimeout(pulse, 500);
- }
- pulse();
- },
-
- /**
- * perform a search for something (or wait until index is loaded)
- */
- performSearch : function(query) {
- // create the required interface elements
- this.out = $('#search-results');
- this.title = $('
' + _('Searching') + '
').appendTo(this.out);
- this.dots = $('').appendTo(this.title);
- this.status = $('').appendTo(this.out);
- this.output = $('').appendTo(this.out);
-
- $('#search-progress').text(_('Preparing search...'));
- this.startPulse();
-
- // index already loaded, the browser was quick!
- if (this.hasIndex())
- this.query(query);
- else
- this.deferQuery(query);
- },
-
- /**
- * execute search (requires search index to be loaded)
- */
- query : function(query) {
- var i;
- var stopwords = {{ search_language_stop_words }};
-
- // stem the searchterms and add them to the correct list
- var stemmer = new Stemmer();
- var searchterms = [];
- var excluded = [];
- var hlterms = [];
- var tmp = query.split(/\s+/);
- var objectterms = [];
- for (i = 0; i < tmp.length; i++) {
- if (tmp[i] !== "") {
- objectterms.push(tmp[i].toLowerCase());
- }
-
- if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) ||
- tmp[i] === "") {
- // skip this "word"
- continue;
- }
- // stem the word
- var word = stemmer.stemWord(tmp[i].toLowerCase());
- var toAppend;
- // select the correct list
- if (word[0] == '-') {
- toAppend = excluded;
- word = word.substr(1);
- }
- else {
- toAppend = searchterms;
- hlterms.push(tmp[i].toLowerCase());
- }
- // only add if not already in the list
- if (!$u.contains(toAppend, word))
- toAppend.push(word);
- }
- var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
-
- // console.debug('SEARCH: searching for:');
- // console.info('required: ', searchterms);
- // console.info('excluded: ', excluded);
-
- // prepare search
- var terms = this._index.terms;
- var titleterms = this._index.titleterms;
-
- // array of [filename, title, anchor, descr, score]
- var results = [];
- $('#search-progress').empty();
-
- // lookup as object
- for (i = 0; i < objectterms.length; i++) {
- var others = [].concat(objectterms.slice(0, i),
- objectterms.slice(i+1, objectterms.length));
- results = results.concat(this.performObjectSearch(objectterms[i], others));
- }
-
- // lookup as search terms in fulltext
- results = results.concat(this.performTermsSearch(searchterms, excluded, terms, Scorer.term))
- .concat(this.performTermsSearch(searchterms, excluded, titleterms, Scorer.title));
-
- // let the scorer override scores with a custom scoring function
- if (Scorer.score) {
- for (i = 0; i < results.length; i++)
- results[i][4] = Scorer.score(results[i]);
- }
-
- // now sort the results by score (in opposite order of appearance, since the
- // display function below uses pop() to retrieve items) and then
- // alphabetically
- results.sort(function(a, b) {
- var left = a[4];
- var right = b[4];
- if (left > right) {
- return 1;
- } else if (left < right) {
- return -1;
- } else {
- // same score: sort alphabetically
- left = a[1].toLowerCase();
- right = b[1].toLowerCase();
- return (left > right) ? -1 : ((left < right) ? 1 : 0);
- }
- });
-
- // for debugging
- //Search.lastresults = results.slice(); // a copy
- //console.info('search results:', Search.lastresults);
-
- // print the results
- var resultCount = results.length;
- function displayNextItem() {
- // results left, load the summary and display it
- if (results.length) {
- var item = results.pop();
- var listItem = $('');
- if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') {
- // dirhtml builder
- var dirname = item[0] + '/';
- if (dirname.match(/\/index\/$/)) {
- dirname = dirname.substring(0, dirname.length-6);
- } else if (dirname == 'index/') {
- dirname = '';
- }
- listItem.append($('').attr('href',
- DOCUMENTATION_OPTIONS.URL_ROOT + dirname +
- highlightstring + item[2]).html(item[1]));
- } else {
- // normal html builders
- listItem.append($('').attr('href',
- item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
- highlightstring + item[2]).html(item[1]));
- }
- if (item[3]) {
- listItem.append($(' (' + item[3] + ')'));
- Search.output.append(listItem);
- listItem.slideDown(5, function() {
- displayNextItem();
- });
- } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
- $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[0] + '.txt',
- dataType: "text",
- complete: function(jqxhr, textstatus) {
- var data = jqxhr.responseText;
- if (data !== '' && data !== undefined) {
- listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
- }
- Search.output.append(listItem);
- listItem.slideDown(5, function() {
- displayNextItem();
- });
- }});
- } else {
- // no source available, just display title
- Search.output.append(listItem);
- listItem.slideDown(5, function() {
- displayNextItem();
- });
- }
- }
- // search finished, update title and status message
- else {
- Search.stopPulse();
- Search.title.text(_('Search Results'));
- if (!resultCount)
- Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.'));
- else
- Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
- Search.status.fadeIn(500);
- }
- }
- displayNextItem();
- },
-
- /**
- * search for object names
- */
- performObjectSearch : function(object, otherterms) {
- var filenames = this._index.filenames;
- var objects = this._index.objects;
- var objnames = this._index.objnames;
- var titles = this._index.titles;
-
- var i;
- var results = [];
-
- for (var prefix in objects) {
- for (var name in objects[prefix]) {
- var fullname = (prefix ? prefix + '.' : '') + name;
- if (fullname.toLowerCase().indexOf(object) > -1) {
- var score = 0;
- var parts = fullname.split('.');
- // check for different match types: exact matches of full name or
- // "last name" (i.e. last dotted part)
- if (fullname == object || parts[parts.length - 1] == object) {
- score += Scorer.objNameMatch;
- // matches in last name
- } else if (parts[parts.length - 1].indexOf(object) > -1) {
- score += Scorer.objPartialMatch;
- }
- var match = objects[prefix][name];
- var objname = objnames[match[1]][2];
- var title = titles[match[0]];
- // If more than one term searched for, we require other words to be
- // found in the name/title/description
- if (otherterms.length > 0) {
- var haystack = (prefix + ' ' + name + ' ' +
- objname + ' ' + title).toLowerCase();
- var allfound = true;
- for (i = 0; i < otherterms.length; i++) {
- if (haystack.indexOf(otherterms[i]) == -1) {
- allfound = false;
- break;
- }
- }
- if (!allfound) {
- continue;
- }
- }
- var descr = objname + _(', in ') + title;
-
- var anchor = match[3];
- if (anchor === '')
- anchor = fullname;
- else if (anchor == '-')
- anchor = objnames[match[1]][1] + '-' + fullname;
- // add custom score for some objects according to scorer
- if (Scorer.objPrio.hasOwnProperty(match[2])) {
- score += Scorer.objPrio[match[2]];
- } else {
- score += Scorer.objPrioDefault;
- }
- results.push([filenames[match[0]], fullname, '#'+anchor, descr, score]);
- }
- }
- }
-
- return results;
- },
-
- /**
- * search for full-text terms in the index
- */
- performTermsSearch : function(searchterms, excluded, terms, score) {
- var filenames = this._index.filenames;
- var titles = this._index.titles;
-
- var i, j, file, files;
- var fileMap = {};
- var results = [];
-
- // perform the search on the required terms
- for (i = 0; i < searchterms.length; i++) {
- var word = searchterms[i];
- // no match but word was a required one
- if ((files = terms[word]) === undefined)
- break;
- if (files.length === undefined) {
- files = [files];
- }
- // create the mapping
- for (j = 0; j < files.length; j++) {
- file = files[j];
- if (file in fileMap)
- fileMap[file].push(word);
- else
- fileMap[file] = [word];
- }
- }
-
- // now check if the files don't contain excluded terms
- for (file in fileMap) {
- var valid = true;
-
- // check if all requirements are matched
- if (fileMap[file].length != searchterms.length)
- continue;
-
- // ensure that none of the excluded terms is in the search result
- for (i = 0; i < excluded.length; i++) {
- if (terms[excluded[i]] == file ||
- $u.contains(terms[excluded[i]] || [], file)) {
- valid = false;
- break;
- }
- }
-
- // if we have still a valid result we can add it to the result list
- if (valid) {
- results.push([filenames[file], titles[file], '', null, score]);
- }
- }
- return results;
- },
-
- /**
- * helper function to return a node containing the
- * search summary for a given text. keywords is a list
- * of stemmed words, hlwords is the list of normal, unstemmed
- * words. the first one is used to find the occurrence, the
- * latter for highlighting it.
- */
- makeSearchSummary : function(text, keywords, hlwords) {
- var textLower = text.toLowerCase();
- var start = 0;
- $.each(keywords, function() {
- var i = textLower.indexOf(this.toLowerCase());
- if (i > -1)
- start = i;
- });
- start = Math.max(start - 120, 0);
- var excerpt = ((start > 0) ? '...' : '') +
- $.trim(text.substr(start, 240)) +
- ((start + 240 - text.length) ? '...' : '');
- var rv = $('').text(excerpt);
- $.each(hlwords, function() {
- rv = rv.highlightText(this, 'highlighted');
- });
- return rv;
- }
-};
diff --git a/readthedocs_ext/comments/backend.py b/readthedocs_ext/comments/backend.py
index 55cbf39..db9e816 100644
--- a/readthedocs_ext/comments/backend.py
+++ b/readthedocs_ext/comments/backend.py
@@ -37,39 +37,35 @@ def get_comments(self, node):
data = {'node': node}
self._add_server_data(data)
r = requests.get(url, params=data)
- if r.status_code is 200:
+ if r.status_code == 200:
return r.json()
- else:
- return False
+ return False
def get_project_metadata(self, project):
url = self.url.replace('/websupport', '') + "/api/v2/comments/"
data = {'project': project}
r = requests.get(url, params=data)
- if r.status_code is 200:
+ if r.status_code == 200:
return r.json()
- else:
- return False
+ return False
def get_metadata(self, docname, moderator=None):
url = self.url + "/_get_metadata"
data = {'page': docname}
self._add_server_data(data)
r = requests.get(url, params=data)
- if r.status_code is 200:
+ if r.status_code == 200:
return r.json()
- else:
- return False
+ return False
def has_node(self, id):
url = self.url + "/_has_node"
data = {'node_id': id, }
self._add_server_data(data)
r = requests.get(url, params=data)
- if r.status_code is 200:
+ if r.status_code == 200:
return r.json()['exists']
- else:
- return False
+ return False
def add_node(self, id, document, source):
url = self.url + "/_add_node"
diff --git a/readthedocs_ext/comments/builder.py b/readthedocs_ext/comments/builder.py
index f390017..e21e1ac 100644
--- a/readthedocs_ext/comments/builder.py
+++ b/readthedocs_ext/comments/builder.py
@@ -5,6 +5,7 @@
from sphinx.builders.html import StandaloneHTMLBuilder, DirectoryHTMLBuilder
from . import backend, translator
+from ..mixins import BuilderMixin
def finalize_comment_media(app):
@@ -37,7 +38,22 @@ def finalize_comment_media(app):
builder.css_files.append('_static/jquery.pageslide.css')
-class ReadtheDocsBuilderComments(StandaloneHTMLBuilder):
+class CommentsBuilderMixin(BuilderMixin):
+
+ static_override_files = [
+ 'sphinxweb.css',
+ 'jquery.pageslide.css',
+ 'jquery.pageslide.js',
+ ]
+
+ def get_static_override_context(self):
+ ctx = super(CommentsBuilderMixin, self).get_static_override_context()
+ ctx['websupport2_base_url'] = self.config.websupport2_base_url
+ ctx['websupport2_static_url'] = self.config.websupport2_static_url
+ return ctx
+
+
+class ReadtheDocsBuilderComments(CommentsBuilderMixin, StandaloneHTMLBuilder):
"""
Comment Builders.
@@ -50,13 +66,12 @@ class ReadtheDocsBuilderComments(StandaloneHTMLBuilder):
def init(self):
StandaloneHTMLBuilder.init(self)
- finalize_comment_media(self)
def init_translator_class(self):
self.translator_class = translator.UUIDTranslator
-class ReadtheDocsDirectoryHTMLBuilderComments(DirectoryHTMLBuilder):
+class ReadtheDocsDirectoryHTMLBuilderComments(CommentsBuilderMixin, DirectoryHTMLBuilder):
""" Adds specific media files to script_files and css_files. """
name = 'readthedocsdirhtml-comments'
diff --git a/readthedocs_ext/mixins.py b/readthedocs_ext/mixins.py
new file mode 100644
index 0000000..d3d90c4
--- /dev/null
+++ b/readthedocs_ext/mixins.py
@@ -0,0 +1,60 @@
+import os
+
+import sphinx
+from sphinx.util.console import bold
+
+if sphinx.version_info < (1, 5):
+ # ``copy_static_entry`` was deprecated in Sphinx 1.5a1
+ from sphinx.util import copy_static_entry
+else:
+ from sphinx.util.fileutil import copy_asset
+
+
+class BuilderMixin(object): # pylint: disable=old-style-class
+
+ """Builder mixin class for copying and templating extra static files
+
+ Adds additional script and stylesheet files to the output static files path.
+ Template static files are provided a custom context and then copied to the
+ new path.
+ """
+
+ static_override_files = []
+
+ def get_static_override_context(self):
+ return self.globalcontext.copy()
+
+ def copy_static_override_files(self):
+ self.app.info(bold('copying static override files... '), nonl=True)
+ for filename in self.static_override_files:
+ path_dest = os.path.join(self.outdir, '_static')
+ path_src = os.path.join(
+ os.path.abspath(os.path.dirname(__file__)),
+ '_static',
+ filename
+ )
+ ctx = self.get_static_override_context()
+ if sphinx.version_info < (1, 5):
+ copy_static_entry(
+ path_src,
+ path_dest,
+ self,
+ context=ctx,
+ )
+ else:
+ copy_asset(
+ path_src,
+ path_dest,
+ context=ctx,
+ renderer=self.templates
+ )
+ self.app.info('done')
+
+ def copy_static_files(self):
+ """Copy override files after initial static pass
+
+ This overrides the base builder ``copy_static_files`` method to inject
+ custom static files.
+ """
+ super(BuilderMixin, self).copy_static_files()
+ self.copy_static_override_files()
diff --git a/readthedocs_ext/readthedocs.py b/readthedocs_ext/readthedocs.py
index 2b3cc26..ede7c88 100644
--- a/readthedocs_ext/readthedocs.py
+++ b/readthedocs_ext/readthedocs.py
@@ -1,17 +1,22 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import
+
+import codecs
import os
+import re
import types
+import sphinx
+from sphinx import package_dir
from sphinx.builders.html import StandaloneHTMLBuilder, DirectoryHTMLBuilder, SingleFileHTMLBuilder
-from sphinx.util import copy_static_entry
from sphinx.util.console import bold
from .comments.builder import (finalize_comment_media, ReadtheDocsBuilderComments,
ReadtheDocsDirectoryHTMLBuilderComments)
from .comments.directive import CommentConfigurationDirective
from .embed import EmbedDirective
+from .mixins import BuilderMixin
MEDIA_MAPPING = {
"_static/jquery.js": "%sjavascript/jquery/jquery-2.0.3.min.js",
@@ -19,12 +24,6 @@
"_static/doctools.js": "%sjavascript/doctools.js",
}
-STATIC_FILES = [
- 'sphinxweb.css',
- 'jquery.pageslide.css',
- 'jquery.pageslide.js',
-]
-
def finalize_media(app):
""" Point media files at our media server. """
@@ -114,74 +113,84 @@ def rtd_render(self, template, render_context):
app.builder.templates)
-def copy_media(app, exception):
- """ Move our dynamically generated files after build. """
- if app.builder.name in ['readthedocs', 'readthedocsdirhtml'] and not exception:
- for file in ['readthedocs-dynamic-include.js_t', 'readthedocs-data.js_t',
- 'searchtools.js_t']:
- app.info(bold('Copying %s... ' % file), nonl=True)
- dest_dir = os.path.join(app.builder.outdir, '_static')
- source = os.path.join(
- os.path.abspath(os.path.dirname(__file__)),
- '_static',
- file
- )
- try:
- ctx = app.builder.globalcontext
- except AttributeError:
- ctx = {}
- if app.builder.indexer is not None:
- ctx.update(app.builder.indexer.context_for_searchtool())
- copy_static_entry(source, dest_dir, app.builder, ctx)
- app.info('done')
-
- if 'comments' in app.builder.name and not exception:
- for file in STATIC_FILES:
- app.info(bold('Copying %s... ' % file), nonl=True)
- dest_dir = os.path.join(app.builder.outdir, '_static')
- source = os.path.join(
- os.path.abspath(os.path.dirname(__file__)),
- '_static',
- file
- )
- try:
- ctx = app.builder.globalcontext
- except AttributeError:
- ctx = {}
- ctx['websupport2_base_url'] = app.builder.config.websupport2_base_url
- ctx['websupport2_static_url'] = app.builder.config.websupport2_static_url
- copy_static_entry(source, dest_dir, app.builder, ctx)
- app.info('done')
+class HtmlBuilderMixin(BuilderMixin):
+ static_override_files = [
+ 'readthedocs-dynamic-include.js_t',
+ 'readthedocs-data.js_t',
+ # We patch searchtools and copy it with a special handler
+ # 'searchtools.js_t'
+ ]
-class ReadtheDocsBuilder(StandaloneHTMLBuilder):
+ REPLACEMENT_TEXT = '/* Search initialization removed for Read the Docs */'
+ REPLACEMENT_PATTERN = re.compile(
+ r'''
+ ^\$\(document\).ready\(function\s*\(\)\s*{(?:\n|\r\n?)
+ \s*Search.init\(\);(?:\n|\r\n?)
+ \}\);
+ ''',
+ (re.MULTILINE | re.VERBOSE)
+ )
+
+ def get_static_override_context(self):
+ ctx = super(HtmlBuilderMixin, self).get_static_override_context()
+ if self.indexer is not None:
+ ctx.update(self.indexer.context_for_searchtool())
+ return ctx
+
+ def copy_static_override_files(self):
+ super(HtmlBuilderMixin, self).copy_static_override_files()
+ self._copy_searchtools()
+
+ def _copy_searchtools(self, renderer=None):
+ """Copy and patch searchtools
+
+ This uses the included Sphinx version's searchtools, but patches it to
+ remove automatic initialization. This is a fork of
+ ``sphinx.util.fileutil.copy_asset``
+ """
+ self.app.info(bold('copying searchtools... '), nonl=True)
+
+ path_src = os.path.join(package_dir, 'themes', 'basic', 'static',
+ 'searchtools.js_t')
+ if os.path.exists(path_src):
+ path_dest = os.path.join(self.outdir, '_static', 'searchtools.js')
+ if renderer is None:
+ # Sphinx 1.4 used the renderer from the existing builder, but
+ # the pattern for Sphinx 1.5 is to pass in a renderer separate
+ # from the builder. This supports both patterns for future
+ # compatibility
+ if sphinx.version_info < (1, 5):
+ renderer = self.templates
+ else:
+ from sphinx.util.template import SphinxRenderer
+ renderer = SphinxRenderer()
+ with codecs.open(path_src, 'r', encoding='utf-8') as h_src:
+ with codecs.open(path_dest, 'w', encoding='utf-8') as h_dest:
+ data = h_src.read()
+ data = self.REPLACEMENT_PATTERN.sub(self.REPLACEMENT_TEXT, data)
+ h_dest.write(renderer.render_string(
+ data,
+ self.get_static_override_context()
+ ))
+ else:
+ self.app.warn('Missing searchtools.js_t')
+ self.app.info('done')
- """
- Adds specific media files to script_files and css_files.
- """
- name = 'readthedocs'
+class ReadtheDocsBuilder(HtmlBuilderMixin, StandaloneHTMLBuilder):
+ name = 'readthedocs'
-class ReadtheDocsDirectoryHTMLBuilder(DirectoryHTMLBuilder):
- """
- Adds specific media files to script_files and css_files.
- """
+class ReadtheDocsDirectoryHTMLBuilder(HtmlBuilderMixin, DirectoryHTMLBuilder):
name = 'readthedocsdirhtml'
-class ReadtheDocsSingleFileHTMLBuilder(SingleFileHTMLBuilder):
- """
- Adds specific media files to script_files and css_files.
- """
+class ReadtheDocsSingleFileHTMLBuilder(BuilderMixin, SingleFileHTMLBuilder):
name = 'readthedocssinglehtml'
-class ReadtheDocsSingleFileHTMLBuilderLocalMedia(SingleFileHTMLBuilder):
-
- """
- Adds specific media files to script_files and css_files.
- """
+class ReadtheDocsSingleFileHTMLBuilderLocalMedia(BuilderMixin, SingleFileHTMLBuilder):
name = 'readthedocssinglehtmllocalmedia'
@@ -193,7 +202,6 @@ def setup(app):
app.connect('builder-inited', finalize_media)
app.connect('builder-inited', finalize_comment_media)
app.connect('html-page-context', update_body)
- app.connect('build-finished', copy_media)
# Comments
# app.connect('env-updated', add_comments_to_doctree)
diff --git a/requirements.txt b/requirements.txt
deleted file mode 100644
index b24ab50..0000000
--- a/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-sphinx==1.3.4
-pytest==2.8.5
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/pyexample/conf.py b/tests/pyexample/conf.py
index 9ad6817..62cf157 100644
--- a/tests/pyexample/conf.py
+++ b/tests/pyexample/conf.py
@@ -1,5 +1,10 @@
# -*- coding: utf-8 -*-
+import os
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
+
extensions = ['readthedocs_ext.readthedocs']
templates_path = ['_templates']
diff --git a/tests/test_integration.py b/tests/test_integration.py
index 8213e49..df78889 100644
--- a/tests/test_integration.py
+++ b/tests/test_integration.py
@@ -1,30 +1,15 @@
-import os
-import shutil
import unittest
-import io
-from sphinx.application import Sphinx
+from readthedocs_ext.readthedocs import HtmlBuilderMixin
+
+from .util import sphinx_build, build_output
class LanguageIntegrationTests(unittest.TestCase):
def _run_test(self, test_dir, test_file, test_string, builder='html'):
- os.chdir('tests/{0}'.format(test_dir))
- try:
- app = Sphinx(
- srcdir='.',
- confdir='.',
- outdir='_build/%s' % builder,
- doctreedir='_build/.doctrees',
- buildername='%s' % builder,
- )
- app.build(force_all=True)
- with io.open(test_file, encoding="utf-8") as fin:
- text = fin.read().strip()
- self.assertIn(test_string, text)
- finally:
- shutil.rmtree('_build')
- os.chdir('../..')
+ with build_output(test_dir, test_file, builder) as data:
+ self.assertIn(test_string, data)
class IntegrationTests(LanguageIntegrationTests):
@@ -53,3 +38,21 @@ def test_included_js(self):
builder='readthedocs',
)
+ def test_replacement_pattern(self):
+ pattern = HtmlBuilderMixin.REPLACEMENT_PATTERN
+ src = "$(document).ready(function() {\n Search.init();\n});"
+ self.assertRegexpMatches(src, pattern)
+ # Minor changes to spacing, just to ensure rule is correct. This should
+ # never happen as this block of code is 10 years old
+ src = "$(document).ready(function () {\n Search.init();\n});"
+ self.assertRegexpMatches(src, pattern)
+
+ def test_searchtools_is_patched(self):
+ with build_output('pyexample', '_build/readthedocs/_static/searchtools.js',
+ builder='readthedocs') as data:
+ self.assertNotIn('Search.init();', data)
+ self.assertNotRegexpMatches(
+ data,
+ HtmlBuilderMixin.REPLACEMENT_PATTERN
+ )
+ self.assertIn(HtmlBuilderMixin.REPLACEMENT_TEXT, data)
diff --git a/tests/test_mixins.py b/tests/test_mixins.py
new file mode 100644
index 0000000..1a2d143
--- /dev/null
+++ b/tests/test_mixins.py
@@ -0,0 +1,31 @@
+import unittest
+
+import sphinx
+
+from readthedocs_ext.readthedocs import HtmlBuilderMixin
+
+from .util import sphinx_build
+
+
+class MixinTests(unittest.TestCase):
+
+ def test_html_builder_context_contains_overrides(self):
+ with sphinx_build('pyexample', 'readthedocs') as app:
+ self.assertIn(
+ 'search_scorer_tool',
+ app.builder.get_static_override_context(),
+ )
+
+ def test_htmldir_builder_context_contains_overrides(self):
+ with sphinx_build('pyexample', 'readthedocsdirhtml') as app:
+ self.assertIn(
+ 'search_scorer_tool',
+ app.builder.get_static_override_context(),
+ )
+
+ def test_comments_builder_context_contains_overrides(self):
+ with sphinx_build('pyexample', 'readthedocs-comments') as app:
+ self.assertIn(
+ 'websupport2_base_url',
+ app.builder.get_static_override_context(),
+ )
diff --git a/tests/util.py b/tests/util.py
new file mode 100644
index 0000000..f041fbd
--- /dev/null
+++ b/tests/util.py
@@ -0,0 +1,32 @@
+import os
+import shutil
+import codecs
+from contextlib import contextmanager
+
+from sphinx.application import Sphinx
+
+
+@contextmanager
+def sphinx_build(test_dir, builder='html'):
+ os.chdir('tests/{0}'.format(test_dir))
+ try:
+ app = Sphinx(
+ srcdir='.',
+ confdir='.',
+ outdir='_build/{0}'.format(builder),
+ doctreedir='_build/.doctrees',
+ buildername=builder,
+ )
+ app.build(force_all=True)
+ yield app
+ finally:
+ shutil.rmtree('_build')
+ os.chdir('../..')
+
+
+@contextmanager
+def build_output(src, path, builder='html'):
+ with sphinx_build(src, builder):
+ with codecs.open(path, 'r', 'utf-8') as h:
+ data = h.read().strip()
+ yield data
diff --git a/tox.ini b/tox.ini
index e47de19..03915c0 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,16 +1,25 @@
[tox]
-envlist = py27,py34,lint
+envlist =
+ py{27,34,35,36}-sphinx{13,14,15}
+ lint
[testenv]
setenv =
LANG=C
-deps = -r{toxinidir}/requirements.txt
+deps =
+ .
+ pytest
+ mock
+ sphinx13: Sphinx<1.4
+ sphinx14: Sphinx<1.5
+ sphinx15: Sphinx<1.6
commands =
py.test {posargs}
[testenv:lint]
deps =
- -r{toxinidir}/requirements.txt
+ .
+ sphinx
prospector
commands =
prospector \