desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Test getting a refreshed token from original token works
No date/time modifications are neccessary because it is assumed
that this operation will take less than 300 seconds.'
| def test_refresh_jwt(self):
| client = APIClient(enforce_csrf_checks=True)
orig_token = self.get_token()
orig_token_decoded = utils.jwt_decode_handler(orig_token)
expected_orig_iat = timegm(datetime.utcnow().utctimetuple())
orig_iat = orig_token_decoded['orig_iat']
self.assertLessEqual((orig_iat - expected_orig_iat), 1)
... |
'Test that token can\'t be refreshed after token refresh limit'
| def test_refresh_jwt_after_refresh_expiration(self):
| client = APIClient(enforce_csrf_checks=True)
orig_iat = ((datetime.utcnow() - api_settings.JWT_REFRESH_EXPIRATION_DELTA) - timedelta(seconds=5))
token = self.create_token(self.user, exp=(datetime.utcnow() + timedelta(hours=1)), orig_iat=orig_iat)
response = client.post('/auth-token-refresh/', {'token': ... |
'Ensure POSTing form over JWT auth with correct credentials
passes and does not require CSRF'
| def test_post_form_passing_jwt_auth(self):
| payload = utils.jwt_payload_handler(self.user)
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post('/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
'Ensure POSTing JSON over JWT auth with correct credentials
passes and does not require CSRF'
| def test_post_json_passing_jwt_auth(self):
| payload = utils.jwt_payload_handler(self.user)
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post('/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
'Ensure POSTing form over JWT auth without correct credentials fails'
| def test_post_form_failing_jwt_auth(self):
| response = self.csrf_client.post('/jwt/', {'example': 'example'})
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"')
|
'Ensure POSTing json over JWT auth without correct credentials fails'
| def test_post_json_failing_jwt_auth(self):
| response = self.csrf_client.post('/jwt/', {'example': 'example'}, format='json')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response['WWW-Authenticate'], 'JWT realm="api"')
|
'Ensure POSTing over JWT auth without credentials fails'
| def test_post_no_jwt_header_failing_jwt_auth(self):
| auth = 'JWT'
response = self.csrf_client.post('/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth, format='json')
msg = 'Invalid Authorization header. No credentials provided.'
self.assertEqual(response.data['detail'], msg)
self.assertEqual(response.status_code, status.HTTP_401_U... |
'Ensure POSTing over JWT auth without correct credentials fails'
| def test_post_invalid_jwt_header_failing_jwt_auth(self):
| auth = 'JWT abc abc'
response = self.csrf_client.post('/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth, format='json')
msg = 'Invalid Authorization header. Credentials string should not contain spaces.'
self.assertEqual(response.data['detail'], msg)
self.assertE... |
'Ensure POSTing over JWT auth with expired token fails'
| def test_post_expired_token_failing_jwt_auth(self):
| payload = utils.jwt_payload_handler(self.user)
payload['exp'] = 1
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post('/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth, format='json')
msg = 'Signature has expired.'
self.as... |
'Ensure changin secret key on USER level makes tokens invalid'
| @override_settings(AUTH_USER_MODEL='tests.CustomUser')
def test_post_form_failing_jwt_auth_changed_user_secret_key(self):
| api_settings.JWT_GET_USER_SECRET_KEY = get_jwt_secret
tmp_user = CustomUser.objects.create(email='b@example.com')
payload = utils.jwt_payload_handler(tmp_user)
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post('/jwt/', {'example': 'examp... |
'Ensure POSTing over JWT auth with invalid token fails'
| def test_post_invalid_token_failing_jwt_auth(self):
| auth = 'JWT abc123'
response = self.csrf_client.post('/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth, format='json')
msg = 'Error decoding signature.'
self.assertEqual(response.data['detail'], msg)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assert... |
'Ensure POSTing over JWT auth with correct credentials
passes and does not require CSRF when OAuth2Authentication
has priority on authentication_classes'
| @unittest.skipUnless(oauth2_provider, DJANGO_OAUTH2_PROVIDER_NOT_INSTALLED)
def test_post_passing_jwt_auth_with_oauth2_priority(self):
| payload = utils.jwt_payload_handler(self.user)
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post('/oauth2-jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK, respo... |
'Ensure POSTing over OAuth2 with correct credentials
passes and does not require CSRF when JSONWebTokenAuthentication
has priority on authentication_classes'
| @unittest.skipUnless(oauth2_provider, DJANGO_OAUTH2_PROVIDER_NOT_INSTALLED)
def test_post_passing_oauth2_with_jwt_auth_priority(self):
| Client = oauth2_provider.oauth2.models.Client
AccessToken = oauth2_provider.oauth2.models.AccessToken
oauth2_client = Client.objects.create(user=self.user, client_type=0)
access_token = AccessToken.objects.create(user=self.user, client=oauth2_client)
auth = 'Bearer {0}'.format(access_token.token)... |
'Ensure POSTing json over JWT auth with invalid payload fails'
| def test_post_form_passing_jwt_invalid_payload(self):
| payload = dict(email=None)
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
response = self.csrf_client.post('/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
msg = 'Invalid payload.'
self.assertEqual(response.data['detail'], msg)
self.assertEqual(respon... |
'Ensure using a different setting for `JWT_AUTH_HEADER_PREFIX` and
with correct credentials passes.'
| def test_different_auth_header_prefix(self):
| api_settings.JWT_AUTH_HEADER_PREFIX = 'Bearer'
payload = utils.jwt_payload_handler(self.user)
token = utils.jwt_encode_handler(payload)
auth = 'Bearer {0}'.format(token)
response = self.csrf_client.post('/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth, format='json')
self.assertEqual(... |
'Ensure using a different setting for `JWT_AUTH_HEADER_PREFIX` and
POSTing form over JWT auth without correct credentials fails and
generated correct WWW-Authenticate header'
| def test_post_form_failing_jwt_auth_different_auth_header_prefix(self):
| api_settings.JWT_AUTH_HEADER_PREFIX = 'Bearer'
response = self.csrf_client.post('/jwt/', {'example': 'example'})
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response['WWW-Authenticate'], 'Bearer realm="api"')
api_settings.JWT_AUTH_HEADER_PREFIX = DEFAULTS... |
'Returns True if login is possible; False if the provided credentials
are incorrect, or the user is inactive.'
| def login(self, **credentials):
| response = self.post('/api-token-auth/', credentials, format='json')
if (response.status_code == status.HTTP_200_OK):
self.credentials(HTTP_AUTHORIZATION='{0} {1}'.format(api_settings.JWT_AUTH_HEADER_PREFIX, response.data['token']))
return True
else:
return False
|
'Dynamically add the USERNAME_FIELD to self.fields.'
| def __init__(self, *args, **kwargs):
| super(JSONWebTokenSerializer, self).__init__(*args, **kwargs)
self.fields[self.username_field] = serializers.CharField()
self.fields['password'] = PasswordField(write_only=True)
|
'Returns a two-tuple of `User` and token if a valid signature has been
supplied using JWT-based authentication. Otherwise returns `None`.'
| def authenticate(self, request):
| jwt_value = self.get_jwt_value(request)
if (jwt_value is None):
return None
try:
payload = jwt_decode_handler(jwt_value)
except jwt.ExpiredSignature:
msg = _('Signature has expired.')
raise exceptions.AuthenticationFailed(msg)
except jwt.DecodeError:
msg... |
'Returns an active user that matches the payload\'s user id and email.'
| def authenticate_credentials(self, payload):
| User = get_user_model()
username = jwt_get_username_from_payload(payload)
if (not username):
msg = _('Invalid payload.')
raise exceptions.AuthenticationFailed(msg)
try:
user = User.objects.get_by_natural_key(username)
except User.DoesNotExist:
msg = _('Invalid s... |
'Return a string to be used as the value of the `WWW-Authenticate`
header in a `401 Unauthenticated` response, or `None` if the
authentication scheme should return `403 Permission Denied` responses.'
| def authenticate_header(self, request):
| return '{0} realm="{1}"'.format(api_settings.JWT_AUTH_HEADER_PREFIX, self.www_authenticate_realm)
|
'Extra context provided to the serializer class.'
| def get_serializer_context(self):
| return {'request': self.request, 'view': self}
|
'Return the class to use for the serializer.
Defaults to using `self.serializer_class`.
You may want to override this if you need to provide different
serializations depending on the incoming request.
(Eg. admins get full serialization, others get basic serialization)'
| def get_serializer_class(self):
| assert (self.serializer_class is not None), ("'%s' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method." % self.__class__.__name__)
return self.serializer_class
|
'Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.'
| def get_serializer(self, *args, **kwargs):
| serializer_class = self.get_serializer_class()
kwargs['context'] = self.get_serializer_context()
return serializer_class(*args, **kwargs)
|
'prefix traceback info for better representation'
| def formatException(self, ei):
| s = super(BaseFormatter, self).formatException(ei)
s = str(u'\n').join(((str(u' | ') + line) for line in s.splitlines()))
s = str(u' |___\n{}').format(s)
return s
|
'NOOP: overridden by subclasses'
| def _get_levelname(self, name):
| return name
|
'properly decode an arg for Py2 if it\'s Exception
localized systems have errors in native language if locale is set
so convert the message to unicode with the correct encoding'
| def _decode_arg(self, arg):
| if isinstance(arg, Exception):
text = (str(u'%s: %s') % (arg.__class__.__name__, arg))
if six.PY2:
text = text.decode(self._exc_encoding)
return text
else:
return arg
|
'Returns URL information as defined in settings.
When get_page_name=True returns URL without anything after {slug} e.g.
if in settings: CATEGORY_URL="cat/{slug}.html" this returns
"cat/{slug}" Useful for pagination.'
| def _from_settings(self, key, get_page_name=False):
| setting = (u'%s_%s' % (self.__class__.__name__.upper(), key))
value = self.settings[setting]
if (not isinstance(value, six.string_types)):
logger.warning(u'%s is set to %s', setting, value)
return value
elif get_page_name:
return os.path.splitext(value)[0].format(**se... |
'Uses our custom strftime if supposed to be *safe*'
| def strftime(self, fmt, safe=True):
| if safe:
return strftime(self, fmt)
else:
return super(SafeDatetime, self).strftime(fmt)
|
'Support instance methods.'
| def __get__(self, obj, objtype):
| return partial(self.__call__, obj)
|
'Test mandatory properties are set.'
| def _has_valid_mandatory_properties(self):
| for prop in self.mandatory_properties:
if (not hasattr(self, prop)):
logger.error(u"Skipping %s: could not find information about '%s'", self, prop)
return False
return True
|
'Return true if save_as doesn\'t write outside output path, false
otherwise.'
| def _has_valid_save_as(self):
| try:
output_path = self.settings[u'OUTPUT_PATH']
except KeyError:
return True
try:
sanitised_join(output_path, self.save_as)
except RuntimeError:
logger.error(u'Skipping %s: file %r would be written outside output path', self, self.save_as)
... |
'Validate Content'
| def is_valid(self):
| return all([self._has_valid_mandatory_properties(), self._has_valid_save_as(), self._has_valid_status()])
|
'Returns the URL, formatted with the proper values'
| @property
def url_format(self):
| metadata = copy.copy(self.metadata)
path = self.metadata.get(u'path', self.get_relative_source_path())
metadata.update({u'path': path_to_url(path), u'slug': getattr(self, u'slug', u''), u'lang': getattr(self, u'lang', u'en'), u'date': getattr(self, u'date', SafeDatetime.now()), u'author': (self.author.slug ... |
'Update the content attribute.
Change all the relative paths of the content to relative paths
suitable for the output content.
:param content: content resource that will be passed to the templates.
:param siteurl: siteurl which is locally generated by the writer in
case of RELATIVE_URLS.'
| def _update_content(self, content, siteurl):
| if (not content):
return content
instrasite_link_regex = self.settings[u'INTRASITE_LINK_REGEX']
regex = u'\n (?P<markup><[^\\>]+ # match tag with all url-value attributes\n ... |
'Returns the summary of an article.
This is based on the summary metadata if set, otherwise truncate the
content.'
| @memoized
def get_summary(self, siteurl):
| if hasattr(self, u'_summary'):
return self._update_content(self._summary, siteurl)
if (self.settings[u'SUMMARY_MAX_LENGTH'] is None):
return self.content
return truncate_html_words(self.content, self.settings[u'SUMMARY_MAX_LENGTH'])
|
'deprecated function to access summary'
| def _get_summary(self):
| logger.warning(u'_get_summary() has been deprecated since 3.6.4. Use the summary decorator instead')
return self.summary
|
'Dummy function'
| @summary.setter
def summary(self, value):
| pass
|
'Return the relative path (from the content path) to the given
source_path.
If no source path is specified, use the source path of this
content object.'
| def get_relative_source_path(self, source_path=None):
| if (not source_path):
source_path = self.source_path
if (source_path is None):
return None
return posixize_path(os.path.relpath(os.path.abspath(os.path.join(self.settings[u'PATH'], source_path)), os.path.abspath(self.settings[u'PATH'])))
|
'Override our output directory with that of the given content object.'
| def attach_to(self, content):
| linking_source_dir = os.path.dirname(content.source_path)
tail_path = os.path.relpath(self.source_path, linking_source_dir)
if tail_path.startswith((os.pardir + os.sep)):
tail_path = os.path.basename(tail_path)
new_save_as = os.path.join(os.path.dirname(content.save_as), tail_path)
new_url =... |
'Pelican initialisation
Performs some checks on the environment before doing anything else.'
| def __init__(self, settings):
| self.settings = settings
self._handle_deprecation()
self.path = settings[u'PATH']
self.theme = settings[u'THEME']
self.output_path = settings[u'OUTPUT_PATH']
self.ignore_files = settings[u'IGNORE_FILES']
self.delete_outputdir = settings[u'DELETE_OUTPUT_DIRECTORY']
self.output_retention =... |
'Run the generators and return'
| def run(self):
| start_time = time.time()
context = self.settings.copy()
context[u'filenames'] = {}
context[u'localsiteurl'] = self.settings[u'SITEURL']
generators = [cls(context=context, settings=self.settings, path=self.path, theme=self.theme, output_path=self.output_path) for cls in self.get_generator_classes()]
... |
'Test that generation with fr_FR.UTF-8 locale works'
| @unittest.skipUnless((locale_available(u'fr_FR.UTF-8') or locale_available(u'French')), u'French locale needed')
def test_custom_locale_generation_works(self):
| if (sys.platform == u'win32'):
our_locale = str(u'French')
else:
our_locale = str(u'fr_FR.UTF-8')
settings = read_settings(path=SAMPLE_FR_CONFIG, override={u'PATH': INPUT_PATH, u'OUTPUT_PATH': self.temp_path, u'CACHE_PATH': self.temp_cache, u'LOCALE': our_locale})
pelican = Pelican(setti... |
'Test that only the selected files are written'
| def test_write_only_selected(self):
| settings = read_settings(path=None, override={u'PATH': INPUT_PATH, u'OUTPUT_PATH': self.temp_path, u'CACHE_PATH': self.temp_cache, u'WRITE_SELECTED': [os.path.join(self.temp_path, u'oh-yeah.html'), os.path.join(self.temp_path, u'categories.html')], u'LOCALE': locale.normalize(u'en_US')})
pelican = Pelican(setti... |
'Test that a warning is issued if MD_EXTENSIONS is used'
| def test_md_extensions_deprecation(self):
| settings = read_settings(path=None, override={u'PATH': INPUT_PATH, u'OUTPUT_PATH': self.temp_path, u'CACHE_PATH': self.temp_cache, u'MD_EXTENSIONS': {}})
pelican = Pelican(settings=settings)
mute(True)(pelican.run)()
self.assertLogCountEqual(count=1, msg=u'MD_EXTENSIONS is deprecated use MAR... |
'calling ._get_summary() should issue a warning'
| def test_summary_get_summary_warning(self):
| page_kwargs = self._copy_page_kwargs()
page = Page(**page_kwargs)
self.assertEqual(page.summary, TEST_SUMMARY)
self.assertEqual(page._get_summary(), TEST_SUMMARY)
self.assertLogCountEqual(count=1, msg=u'_get_summary\\(\\) has been deprecated since 3\\.6\\.4\\. Use the summary... |
'Test article with multiple authors.'
| def test_multiple_authors(self):
| args = self.page_kwargs.copy()
content = Page(**args)
assert (content.authors == [content.author])
args[u'metadata'].pop(u'author')
args[u'metadata'][u'authors'] = [Author(u'First Author', DEFAULT_CONFIG), Author(u'Second Author', DEFAULT_CONFIG)]
content = Page(**args)
assert content.... |
'attach_to() overrides a static file\'s save_as and url.'
| def test_attach_to_same_dir(self):
| page = Page(content=u'fake page', metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'fakepage.md'))
self.static.attach_to(page)
expected_save_as = os.path.join(u'outpages', u'foo.jpg')
self.assertEqual(self.static.save_as, expected_save_as)
self.assertEqu... |
'attach_to() preserves dirs inside the linking document dir.'
| def test_attach_to_parent_dir(self):
| page = Page(content=u'fake page', metadata={u'title': u'fakepage'}, settings=self.settings, source_path=u'fakepage.md')
self.static.attach_to(page)
expected_save_as = os.path.join(u'outpages', u'dir', u'foo.jpg')
self.assertEqual(self.static.save_as, expected_save_as)
self.assertEqual(self.static... |
'attach_to() ignores dirs outside the linking document dir.'
| def test_attach_to_other_dir(self):
| page = Page(content=u'fake page', metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'otherdir', u'fakepage.md'))
self.static.attach_to(page)
expected_save_as = os.path.join(u'outpages', u'foo.jpg')
self.assertEqual(self.static.save_as, expected_save_as)
s... |
'attach_to() does nothing when called a second time.'
| def test_attach_to_ignores_subsequent_calls(self):
| page = Page(content=u'fake page', metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'fakepage.md'))
self.static.attach_to(page)
otherdir_settings = self.settings.copy()
otherdir_settings.update(dict(PAGE_SAVE_AS=os.path.join(u'otherpages', u'{slug}.html'), PA... |
'attach_to() does nothing if the save_as was already referenced.
(For example, by a {filename} link an a document processed earlier.)'
| def test_attach_to_does_nothing_after_save_as_referenced(self):
| original_save_as = self.static.save_as
page = Page(content=u'fake page', metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'fakepage.md'))
self.static.attach_to(page)
self.assertEqual(self.static.save_as, original_save_as)
self.assertEqual(self.static.url... |
'attach_to() does nothing if the url was already referenced.
(For example, by a {filename} link an a document processed earlier.)'
| def test_attach_to_does_nothing_after_url_referenced(self):
| original_url = self.static.url
page = Page(content=u'fake page', metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'fakepage.md'))
self.static.attach_to(page)
self.assertEqual(self.static.save_as, self.static.source_path)
self.assertEqual(self.static.url,... |
'attach_to() does not override paths that were overridden elsewhere.
(For example, by the user with EXTRA_PATH_METADATA)'
| def test_attach_to_does_not_override_an_override(self):
| customstatic = Static(content=None, metadata=dict(save_as=u'customfoo.jpg', url=u'customfoo.jpg'), settings=self.settings, source_path=os.path.join(u'dir', u'foo.jpg'), context=self.settings.copy())
page = Page(content=u'fake page', metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.pat... |
'{attach} link syntax triggers output path override & url replacement.'
| def test_attach_link_syntax(self):
| html = u'<a href="{attach}../foo.jpg">link</a>'
page = Page(content=html, metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'otherdir', u'fakepage.md'), context=self.context)
content = page.get_content(u'')
self.assertNotEqual(content, html, u'{attach} lin... |
'{tag} link syntax triggers url replacement.'
| def test_tag_link_syntax(self):
| html = u'<a href="{tag}foo">link</a>'
page = Page(content=html, metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'otherdir', u'fakepage.md'), context=self.context)
content = page.get_content(u'')
self.assertNotEqual(content, html)
|
'{category} link syntax triggers url replacement.'
| def test_category_link_syntax(self):
| html = u'<a href="{category}foo">link</a>'
page = Page(content=html, metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'otherdir', u'fakepage.md'), context=self.context)
content = page.get_content(u'')
self.assertNotEqual(content, html)
|
'{author} link syntax triggers url replacement.'
| def test_author_link_syntax(self):
| html = u'<a href="{author}foo">link</a>'
page = Page(content=html, metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'otherdir', u'fakepage.md'), context=self.context)
content = page.get_content(u'')
self.assertNotEqual(content, html)
|
'{index} link syntax triggers url replacement.'
| def test_index_link_syntax(self):
| html = u'<a href="{index}">link</a>'
page = Page(content=html, metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'otherdir', u'fakepage.md'), context=self.context)
content = page.get_content(u'')
self.assertNotEqual(content, html)
expected_html = ((u'<a ... |
'{unknown} link syntax should trigger warning.'
| def test_unknown_link_syntax(self):
| html = u'<a href="{unknown}foo">link</a>'
page = Page(content=html, metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'otherdir', u'fakepage.md'), context=self.context)
content = page.get_content(u'')
self.assertEqual(content, html)
self.assertLogCountEqu... |
'{filename} link to unknown file should trigger warning.'
| def test_link_to_unknown_file(self):
| html = u'<a href="{filename}foo">link</a>'
page = Page(content=html, metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'otherdir', u'fakepage.md'), context=self.context)
content = page.get_content(u'')
self.assertEqual(content, html)
self.assertLogCountEq... |
'{index} link syntax triggers url replacement
with spaces around the equal sign.'
| def test_index_link_syntax_with_spaces(self):
| html = u'<a href = "{index}">link</a>'
page = Page(content=html, metadata={u'title': u'fakepage'}, settings=self.settings, source_path=os.path.join(u'dir', u'otherdir', u'fakepage.md'), context=self.context)
content = page.get_content(u'')
self.assertNotEqual(content, html)
expected_html = ... |
'Test that cached and uncached content is same in generator level'
| def test_generator_caching(self):
| settings = self._get_cache_enabled_settings()
settings[u'CONTENT_CACHING_LAYER'] = u'generator'
settings[u'PAGE_PATHS'] = [u'TestPages']
settings[u'DEFAULT_DATE'] = (1970, 1, 1)
settings[u'READERS'] = {u'asc': None}
def sorted_titles(items):
return sorted((item.title for item in items))
... |
'Test that cached and uncached content is same in reader level'
| def test_reader_caching(self):
| settings = self._get_cache_enabled_settings()
settings[u'CONTENT_CACHING_LAYER'] = u'reader'
settings[u'PAGE_PATHS'] = [u'TestPages']
settings[u'DEFAULT_DATE'] = (1970, 1, 1)
settings[u'READERS'] = {u'asc': None}
def sorted_titles(items):
return sorted((item.title for item in items))
... |
'Test Article objects caching at the generator level'
| @unittest.skipUnless(MagicMock, u'Needs Mock module')
def test_article_object_caching(self):
| settings = self._get_cache_enabled_settings()
settings[u'CONTENT_CACHING_LAYER'] = u'generator'
settings[u'DEFAULT_DATE'] = (1970, 1, 1)
settings[u'READERS'] = {u'asc': None}
generator = ArticlesGenerator(context=settings.copy(), settings=settings, path=CONTENT_DIR, theme=settings[u'THEME'], output_... |
'Test raw article content caching at the reader level'
| @unittest.skipUnless(MagicMock, u'Needs Mock module')
def test_article_reader_content_caching(self):
| settings = self._get_cache_enabled_settings()
settings[u'READERS'] = {u'asc': None}
generator = ArticlesGenerator(context=settings.copy(), settings=settings, path=CONTENT_DIR, theme=settings[u'THEME'], output_path=None)
generator.generate_context()
self.assertTrue(hasattr(generator.readers, u'_cache... |
'Test that all the articles are read again when not loading cache
used in --ignore-cache or autoreload mode'
| @unittest.skipUnless(MagicMock, u'Needs Mock module')
def test_article_ignore_cache(self):
| settings = self._get_cache_enabled_settings()
settings[u'READERS'] = {u'asc': None}
generator = ArticlesGenerator(context=settings.copy(), settings=settings, path=CONTENT_DIR, theme=settings[u'THEME'], output_path=None)
generator.readers.read_file = MagicMock()
generator.generate_context()
self.... |
'Test Page objects caching at the generator level'
| @unittest.skipUnless(MagicMock, u'Needs Mock module')
def test_page_object_caching(self):
| settings = self._get_cache_enabled_settings()
settings[u'CONTENT_CACHING_LAYER'] = u'generator'
settings[u'PAGE_PATHS'] = [u'TestPages']
settings[u'READERS'] = {u'asc': None}
generator = PagesGenerator(context=settings.copy(), settings=settings, path=CUR_DIR, theme=settings[u'THEME'], output_path=No... |
'Test raw page content caching at the reader level'
| @unittest.skipUnless(MagicMock, u'Needs Mock module')
def test_page_reader_content_caching(self):
| settings = self._get_cache_enabled_settings()
settings[u'PAGE_PATHS'] = [u'TestPages']
settings[u'READERS'] = {u'asc': None}
generator = PagesGenerator(context=settings.copy(), settings=settings, path=CUR_DIR, theme=settings[u'THEME'], output_path=None)
generator.generate_context()
self.assertTr... |
'Test that all the pages are read again when not loading cache
used in --ignore_cache or autoreload mode'
| @unittest.skipUnless(MagicMock, u'Needs Mock module')
def test_page_ignore_cache(self):
| settings = self._get_cache_enabled_settings()
settings[u'PAGE_PATHS'] = [u'TestPages']
settings[u'READERS'] = {u'asc': None}
generator = PagesGenerator(context=settings.copy(), settings=settings, path=CUR_DIR, theme=settings[u'THEME'], output_path=None)
generator.readers.read_file = MagicMock()
... |
'Test that Generator.get_files() properly excludes directories.'
| def test_get_files_exclude(self):
| generator = Generator(context=self.settings.copy(), settings=self.settings, path=os.path.join(CUR_DIR, u'nested_content'), theme=self.settings[u'THEME'], output_path=None)
filepaths = generator.get_files(paths=[u'maindir'])
found_files = {os.path.basename(f) for f in filepaths}
expected_files = {u'maind... |
'Test that setting the JINJA_ENVIRONMENT
properly gets set from the settings config'
| def test_custom_jinja_environment(self):
| settings = get_settings()
comment_start_string = u'abc'
comment_end_string = u'/abc'
settings[u'JINJA_ENVIRONMENT'] = {u'comment_start_string': comment_start_string, u'comment_end_string': comment_end_string}
generator = Generator(settings.copy(), settings, CUR_DIR, settings[u'THEME'], None)
sel... |
'Custom template articles get the field but standard/unset are None'
| def test_per_article_template(self):
| custom_template = [u'Article with template', u'published', u'Default', u'custom']
standard_template = [u'This is a super article !', u'published', u'Yeah', u'article']
self.assertIn(custom_template, self.articles)
self.assertIn(standard_template, self.articles)
|
'Test that the context of a generated period_archive is passed
\'period\' : a tuple of year, month, day according to the time period'
| @unittest.skipUnless(MagicMock, u'Needs Mock module')
def test_period_in_timeperiod_archive(self):
| old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str(u'C'))
settings = get_settings(filenames={})
settings[u'YEAR_ARCHIVE_SAVE_AS'] = u'posts/{date:%Y}/index.html'
settings[u'CACHE_PATH'] = self.temp_cache
generator = ArticlesGenerator(context=settings, settings=setti... |
'Attempt to load a non-existent template'
| def test_nonexistent_template(self):
| settings = get_settings(filenames={})
generator = ArticlesGenerator(context=settings, settings=settings, path=None, theme=settings[u'THEME'], output_path=None)
self.assertRaises(Exception, generator.get_template, u'not_a_template')
|
'Check authors generation.'
| def test_generate_authors(self):
| authors = [author.name for (author, _) in self.generator.authors]
authors_expected = sorted([u'Alexis M\xe9taireau', u'Author, First', u'Author, Second', u'First Author', u'Second Author'])
self.assertEqual(sorted(authors), authors_expected)
authors = [author.slug for (author, _) in self.... |
'Test to ensure links of the form {tag}tagname and {category}catname
are generated correctly on pages'
| def test_tag_and_category_links_on_generated_pages(self):
| settings = get_settings(filenames={})
settings[u'PAGE_PATHS'] = [u'TestPages']
settings[u'CACHE_PATH'] = self.temp_cache
settings[u'DEFAULT_DATE'] = (1970, 1, 1)
generator = PagesGenerator(context=settings.copy(), settings=settings, path=CUR_DIR, theme=settings[u'THEME'], output_path=None)
gener... |
'Test that StaticGenerator respects STATIC_EXCLUDES.'
| def test_static_excludes(self):
| settings = get_settings(STATIC_EXCLUDES=[u'subdir'], PATH=self.content_path, STATIC_PATHS=[u''], filenames={})
context = settings.copy()
StaticGenerator(context=context, settings=settings, path=settings[u'PATH'], output_path=self.temp_output, theme=settings[u'THEME']).generate_context()
staticnames = [o... |
'Test that StaticGenerator respects STATIC_EXCLUDE_SOURCES.'
| def test_static_exclude_sources(self):
| settings = get_settings(STATIC_EXCLUDE_SOURCES=True, PATH=self.content_path, PAGE_PATHS=[u''], STATIC_PATHS=[u''], CACHE_CONTENT=False, filenames={})
context = settings.copy()
for generator_class in (PagesGenerator, StaticGenerator):
generator_class(context=context, settings=settings, path=settings[... |
'Check that we recognise pages in wordpress, as opposed to posts'
| def test_recognise_page_kind(self):
| self.assertTrue(self.posts)
pages_data = []
for (title, content, fname, date, author, categ, tags, status, kind, format) in self.posts:
if (kind == u'page'):
pages_data.append((title, fname))
self.assertEqual(2, len(pages_data))
self.assertEqual((u'Page', u'contact'), pages_data[... |
'Check that given an empty string we return an empty string.'
| def test_decode_wp_content_returns_empty(self):
| self.assertEqual(decode_wp_content(u''), u'')
|
'Check that we can decode a wordpress content string.'
| def test_decode_wp_content(self):
| with open(WORDPRESS_ENCODED_CONTENT_SAMPLE, u'r') as encoded_file:
encoded_content = encoded_file.read()
with open(WORDPRESS_DECODED_CONTENT_SAMPLE, u'r') as decoded_file:
decoded_content = decoded_file.read()
self.assertEqual(decode_wp_content(encoded_content, br=False), dec... |
'Return the template by name.
Use self.theme to get the templates to use, and return a list of
templates ready to use with Jinja2.'
| def get_template(self, name):
| if (name not in self._templates):
try:
self._templates[name] = self.env.get_template((name + u'.html'))
except TemplateNotFound:
raise PelicanTemplateNotFound(u'[templates] unable to load {}.html from {}'.format(name, self._templates_path))
return self._... |
'Inclusion logic for .get_files(), returns True/False
:param path: the path which might be including
:param extensions: the list of allowed extensions, or False if all
extensions are allowed'
| def _include_path(self, path, extensions=None):
| if (extensions is None):
extensions = tuple(self.readers.extensions)
basename = os.path.basename(path)
ignores = self.settings[u'IGNORE_FILES']
if any((fnmatch.fnmatch(basename, ignore) for ignore in ignores)):
return False
ext = os.path.splitext(basename)[1][1:]
if ((extensions ... |
'Return a list of files to use, based on rules
:param paths: the list pf paths to search (relative to self.path)
:param exclude: the list of path to exclude
:param extensions: the list of allowed extensions (if False, all
extensions are allowed)'
| def get_files(self, paths, exclude=[], extensions=None):
| if isinstance(paths, six.string_types):
paths = [paths]
exclusions_by_dirpath = {}
for e in exclude:
(parent_path, subdir) = os.path.split(os.path.join(self.path, e))
exclusions_by_dirpath.setdefault(parent_path, set()).add(subdir)
files = []
ignores = self.settings[u'IGNORE_... |
'Record a source file path that a Generator found and processed.
Store a reference to its Content object, for url lookups later.'
| def add_source_path(self, content):
| location = content.get_relative_source_path()
self.context[u'filenames'][location] = content
|
'Record a source file path that a Generator failed to process.
(For example, one that was missing mandatory metadata.)
The path argument is expected to be relative to self.path.'
| def _add_failed_source_path(self, path):
| self.context[u'filenames'][posixize_path(os.path.normpath(path))] = None
|
'Return True if path was supposed to be used as a source file.
(This includes all source files that have been found by generators
before this method is called, even if they failed to process.)
The path argument is expected to be relative to self.path.'
| def _is_potential_source_path(self, path):
| return (posixize_path(os.path.normpath(path)) in self.context[u'filenames'])
|
'Update the context with the given items from the currrent
processor.'
| def _update_context(self, items):
| for item in items:
value = getattr(self, item)
if hasattr(value, u'items'):
value = list(value.items())
self.context[item] = value
|
'Initialize the generator, then set up caching
note the multiple inheritance structure'
| def __init__(self, *args, **kwargs):
| cls_name = self.__class__.__name__
Generator.__init__(self, readers_cache_name=(cls_name + u'-Readers'), *args, **kwargs)
cache_this_level = (self.settings[u'CONTENT_CACHING_LAYER'] == u'generator')
caching_policy = (cache_this_level and self.settings[u'CACHE_CONTENT'])
load_policy = (cache_this_lev... |
'Get filestamp for path relative to generator.path'
| def _get_file_stamp(self, filename):
| filename = os.path.join(self.path, filename)
return super(CachingGenerator, self)._get_file_stamp(filename)
|
'initialize properties'
| def __init__(self, *args, **kwargs):
| self.articles = []
self.translations = []
self.dates = {}
self.tags = defaultdict(list)
self.categories = defaultdict(list)
self.related_posts = []
self.authors = defaultdict(list)
self.drafts = []
self.drafts_translations = []
super(ArticlesGenerator, self).__init__(*args, **kwa... |
'Generate the feeds from the current context, and output files.'
| def generate_feeds(self, writer):
| if self.settings.get(u'FEED_ATOM'):
writer.write_feed(self.articles, self.context, self.settings[u'FEED_ATOM'])
if self.settings.get(u'FEED_RSS'):
writer.write_feed(self.articles, self.context, self.settings[u'FEED_RSS'], feed_type=u'rss')
if (self.settings.get(u'FEED_ALL_ATOM') or self.sett... |
'Generate the articles.'
| def generate_articles(self, write):
| for article in chain(self.translations, self.articles):
signals.article_generator_write_article.send(self, content=article)
write(article.save_as, self.get_template(article.template), self.context, article=article, category=article.category, override_output=hasattr(article, u'override_save_as'), blo... |
'Generate per-year, per-month, and per-day archives.'
| def generate_period_archives(self, write):
| try:
template = self.get_template(u'period_archives')
except PelicanTemplateNotFound:
template = self.get_template(u'archives')
period_save_as = {u'year': self.settings[u'YEAR_ARCHIVE_SAVE_AS'], u'month': self.settings[u'MONTH_ARCHIVE_SAVE_AS'], u'day': self.settings[u'DAY_ARCHIVE_SAVE_AS']}... |
'Generate direct templates pages'
| def generate_direct_templates(self, write):
| PAGINATED_TEMPLATES = self.settings[u'PAGINATED_DIRECT_TEMPLATES']
for template in self.settings[u'DIRECT_TEMPLATES']:
paginated = {}
if (template in PAGINATED_TEMPLATES):
paginated = {u'articles': self.articles, u'dates': self.dates}
save_as = self.settings.get((u'%s_SAVE_AS... |
'Generate Tags pages.'
| def generate_tags(self, write):
| tag_template = self.get_template(u'tag')
for (tag, articles) in self.tags.items():
articles.sort(key=attrgetter(u'date'), reverse=True)
dates = [article for article in self.dates if (article in articles)]
write(tag.save_as, tag_template, self.context, tag=tag, articles=articles, dates=da... |
'Generate category pages.'
| def generate_categories(self, write):
| category_template = self.get_template(u'category')
for (cat, articles) in self.categories:
articles.sort(key=attrgetter(u'date'), reverse=True)
dates = [article for article in self.dates if (article in articles)]
write(cat.save_as, category_template, self.context, category=cat, articles=... |
'Generate Author pages.'
| def generate_authors(self, write):
| author_template = self.get_template(u'author')
for (aut, articles) in self.authors:
articles.sort(key=attrgetter(u'date'), reverse=True)
dates = [article for article in self.dates if (article in articles)]
write(aut.save_as, author_template, self.context, author=aut, articles=articles, d... |
'Generate drafts pages.'
| def generate_drafts(self, write):
| for draft in chain(self.drafts_translations, self.drafts):
write(draft.save_as, self.get_template(draft.template), self.context, article=draft, category=draft.category, override_output=hasattr(draft, u'override_save_as'), blog=True, all_articles=self.articles)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.