repo
stringclasses 856
values | pull_number
int64 3
127k
| instance_id
stringlengths 12
58
| issue_numbers
sequencelengths 1
5
| base_commit
stringlengths 40
40
| patch
stringlengths 67
1.54M
| test_patch
stringlengths 0
107M
| problem_statement
stringlengths 3
307k
| hints_text
stringlengths 0
908k
| created_at
timestamp[s] |
---|---|---|---|---|---|---|---|---|---|
ckan/ckan | 4,510 | ckan__ckan-4510 | [
"4498"
] | 7e58df9c9cb3dac412cab834b41d9443f3abe313 | diff --git a/ckan/views/group.py b/ckan/views/group.py
--- a/ckan/views/group.py
+++ b/ckan/views/group.py
@@ -178,6 +178,8 @@ def index(group_type, is_organization):
sort_by = request.params.get(u'sort')
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.q = q
g.sort_by_selected = sort_by
@@ -228,6 +230,11 @@ def index(group_type, is_organization):
extra_vars["page"].items = page_results
extra_vars["group_type"] = group_type
+
+ # TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
+ g.page = extra_vars["page"]
return base.render(_index_template(group_type), extra_vars)
@@ -246,6 +253,8 @@ def _read(id, limit, group_type):
q = request.params.get(u'q', u'')
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.q = q
# Search within group
@@ -322,6 +331,8 @@ def pager_url(q=None, page=None):
search_extras[param] = value
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.fields = fields
g.fields_grouped = fields_grouped
@@ -368,6 +379,8 @@ def pager_url(q=None, page=None):
items_per_page=limit)
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.group_dict['package_count'] = query['count']
extra_vars["search_facets"] = g.search_facets = query['search_facets']
@@ -386,7 +399,9 @@ def pager_url(q=None, page=None):
extra_vars["query_error"] = True
extra_vars["page"] = h.Page(collection=[])
- # TODO: Rempve
+ # TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.facet_titles = facets
g.page = extra_vars["page"]
@@ -451,6 +466,8 @@ def read(group_type, is_organization, id=None, limit=20):
id=group_dict['name'])
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.q = q
g.group_dict = group_dict
g.group = group
@@ -493,6 +510,8 @@ def activity(id, group_type, is_organization, offset=0):
base.abort(400, error.message)
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.group_activity_stream = extra_vars["group_activity_stream"]
g.group_dict = group_dict
@@ -510,6 +529,8 @@ def about(id, group_type, is_organization):
_setup_template_variables(context, {u'id': id}, group_type=group_type)
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.group_dict = group_dict
g.group_type = group_type
@@ -540,7 +561,9 @@ def members(id, group_type, is_organization):
_(u'User %r not authorized to edit members of %s') %
(g.user, id))
- # TODO:Remove
+ # TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.members = members
g.group_dict = group_dict
@@ -577,6 +600,8 @@ def member_delete(id, group_type, is_organization):
user_dict = _action(u'group_show')(context, {u'id': user_id})
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.user_dict = user_dict
g.user_id = user_id
g.group_id = id
@@ -611,6 +636,8 @@ def history(id, group_type, is_organization):
error = \
_(u'Select two revisions before doing the comparison.')
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.error = error
else:
params[u'diff_entity'] = u'group'
@@ -674,9 +701,12 @@ def history(id, group_type, is_organization):
return feed.writeString(u'utf-8')
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.group_dict = group_dict
g.group_revisions = group_revisions
g.group = group
+
extra_vars = {
u"group_dict": group_dict,
u"group_revisions": group_revisions,
@@ -739,6 +769,8 @@ def followers(id, group_type, is_organization):
base.abort(403, _(u'Unauthorized to view followers %s') % u'')
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.group_dict = group_dict
g.followers = followers
@@ -757,6 +789,8 @@ def admins(id, group_type, is_organization):
admins = authz.get_group_or_org_admin_ids(id)
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.group_dict = group_dict
g.admins = admins
@@ -805,6 +839,8 @@ def get(self, id, group_type, is_organization):
# If no action then just show the datasets
limit = 500
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.group_dict = group_dict
g.group = group
extra_vars = _read(id, limit, group_type)
@@ -842,6 +878,8 @@ def post(self, id, group_type, is_organization, data=None):
raise Exception(u'Must be an organization')
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.group_dict = group_dict
g.group = group
@@ -958,6 +996,8 @@ def get(self, group_type, is_organization,
_group_form(group_type=group_type), extra_vars)
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.form = form
extra_vars["form"] = form
@@ -1042,6 +1082,8 @@ def get(self, id, group_type, is_organization,
form = base.render(_group_form(group_type), extra_vars)
# TODO: Remove
+ # ckan 2.9: Adding variables that were removed from c object for
+ # compatibility with templates in existing extensions
g.grouptitle = grouptitle
g.groupname = groupname
g.data = data
| Backwards compatibility of templates using "c"
### CKAN Version if known (or site URL)
Current master
### Please describe the expected behaviour
It should be possible to use the same template from 2.8 in the current master, without having to deal with missing variables in `c`.
### Please describe the actual behaviour
I have an extension that overrides the `organization/index.html` page, it is based on the template from CKAN 2.8.1. Therefore some variables from `c` are used, e.g.:
```
<h2><span class="result-count">{{ c.page.item_count }}</span></h2>
```
In CKAN 2.8.1 this works perfectly, but when [running my tests on the current master, it fails](https://travis-ci.org/opendata-swiss/ckanext-switzerland/jobs/441573420#L1332):
```
UndefinedError: 'werkzeug.local.LocalProxy object' has no attribute 'page'
```
### What steps can be taken to reproduce the issue?
1. Override the organization/index.html template and access `c.page` in the template
2. Try to render the template using the latest master
| I think this "error" was introduced in #4143, since the group view does not expose the old variables in `g`. Now I'm not sure if the goal is actually to be able to use a 2.8 template 1:1 in the current master.
A simple workaround would be to start the template with:
```
{% if c.page %}
{% set page = c.page %}
{% endif %}
```
And then simply use `page` in this template. I'm just not sure if this is what you want.
Shouldn't there be at least one release that supports both worlds?
cc @amercader @tino097
Thanks @metaodi, it looks that i need to add the `page` to `g` variable as it was done [here](https://github.com/tino097/ckan/blob/5d051d01edea0e82ac1a1cab3e5870890bd9793f/ckan/views/group.py#L179).
This is not an error. Makes perfect sense in a reusable extension or one that needs to be compatible with multiple ckan versions, but if we add a block like the one you suggest to ckan it will be dead, untested code.
ckan's templates are bundled with ckan so they don't need to be compatible with multiple versions. Changes to the templates are also not covered by the deprecate-for-one-version pattern we have for plugin interfaces because the surface exposed for extensions is just too large.
@wardi I think this is a misunderstanding, my block was an example of what I could add to **my template** to make it work with multiple versions of CKAN. I was just not sure if the current idea is to force me as an extension author to add such a block to my code or if I can expect the variables to still be available in `c`.
@metaodi my mistake, I apologise! I think we have have added some `c` backwards compatibility fixes like the one @tino097 linked.
A better comment with the code would be great though. e.g.
```python
# ckan 2.9: Adding variables that were removed from c object for
# compatibility with templates in existing extensions
```
@tino097 will create a PR adding the missing vars to `c` so please flag any other var that we might have missed.
Going forward the plan is to keep existing vars in `c` for a few versions but not use them in core templates. This will allow existing extensions to keep working.
All these was mentioned on previous issues and PRs but obviously it needs to be in a more prominent documentation. This is planned to be in the Flask migration for extensions documentation. | 2018-10-18T10:58:43 |
|
ckan/ckan | 4,523 | ckan__ckan-4523 | [
"4522"
] | e716704ad85a94c4391d08b8d996c017cb539743 | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -1689,6 +1689,8 @@ def package_search(context, data_dict):
:param fq: any filter queries to apply. Note: ``+site_id:{ckan_site_id}``
is added to this string prior to the query being executed.
:type fq: string
+ :param fq_list: additional filter queries to apply.
+ :type fq_list: list of strings
:param sort: sorting of the search results. Optional. Default:
``'relevance asc, metadata_modified desc'``. As per the solr
documentation, this is a comma-separated string of field names and
| fq_list documentation
### CKAN Version if known (or site URL)
2.8.1
### Please describe the expected behaviour
`fq_list` can be set as value of `data_dict` and it is used by [ckan/lib/search/query.py](https://github.com/ckan/ckan/blob/b9e45e2723d4abd70fa72b16ec4a0bebc795c56b/ckan/lib/search/query.py#L327).
'package_search` function in [ckan/logic/action/get.py](https://github.com/ckan/ckan/blob/b9e45e2723d4abd70fa72b16ec4a0bebc795c56b/ckan/logic/action/get.py#L1671) does not mention it in its docstring as possible param.
### Please describe the actual behaviour
`fq_list` should be documented. CKAN uses it only for its CLI at the moment, but other extensions could take advantage of it (I am using it to collapse datasets in combination with ckanext-datasetversions, in order to show just the most recent ones by default).
| 2018-10-25T14:40:34 |
||
ckan/ckan | 4,525 | ckan__ckan-4525 | [
"4247"
] | e716704ad85a94c4391d08b8d996c017cb539743 | diff --git a/ckan/views/__init__.py b/ckan/views/__init__.py
--- a/ckan/views/__init__.py
+++ b/ckan/views/__init__.py
@@ -117,8 +117,11 @@ def identify_user():
if authenticators:
for item in authenticators:
item.identify()
- if g.user:
- break
+ try:
+ if g.user:
+ break
+ except AttributeError:
+ continue
# We haven't identified the user so try the default methods
if not getattr(g, u'user', None):
| '_Globals' has no attribute 'user' : exception when using an IAuthenticator on CKAN 2.8.0
I'm putting together a new deployment based on the new CKAN v2.8.0 release. I'm using ckanext-ldap as an authenticator, though it looks like this bug would apply to any authenticator plugin.
This exact setup worked fine on CKAN v2.7.3.
### CKAN Version if known (or site URL)
CKAN v 2.8.0
ckanext-ldap @ `ckan-upgrade-2.8.0a`
### Please describe the expected behaviour
If the IAuthenticator plugin cannot authenticate the user, it does not set `g.user`, and CKAN should run the default authenticator.
### Please describe the actual behaviour
If the IAuthenticator plugin cannot authenticate the user, it does not set `g.user`, and CKAN tries to lookup `g.user` and crashes with traceback:
```
Traceback (most recent call last):
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1610, in full_dispatch_request
rv = self.preprocess_request()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1831, in preprocess_request
rv = func()
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 281, in ckan_before_request
identify_user()
File "/usr/lib/ckan/venv/src/ckan/ckan/views/__init__.py", line 101, in identify_user
if g.user:
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 334, in __getattr__
return getattr(app_globals.app_globals, name)
AttributeError: '_Globals' object has no attribute 'user'
```
### What steps can be taken to reproduce the issue?
* Install CKAN v2.8.0 as per documented instructions
* Install a plugin that implements IAuthenticator (In this case I am using the ckanext-ldap plugin in the 2.8.0 branch), that may not be able to authenticate the user, so may not set `g.user`.
* Run CKAN normally
* Attempt to load any page.
What is odd is that this section of code at `identify_user` in `ckan/views/__init__.py` has not changed between v2.7.3 and v2.8.0. And the way the authenticator plugin handles/sets `g.user` has not changed either. I'm guessing this is caused by a change in the way the _Globals object behaves when it cannot find an attribute.
| 2018-10-26T07:35:28 |
||
ckan/ckan | 4,574 | ckan__ckan-4574 | [
"4247"
] | d64b1c096590e2d8c0320aa377fe4a276fb3a89f | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -48,7 +48,7 @@
import ckan.plugins as p
import ckan
-from ckan.common import _, ungettext, c, request, session, json
+from ckan.common import _, ungettext, c, g, request, session, json
from markupsafe import Markup, escape
@@ -1154,8 +1154,10 @@ def sorted_extras(package_extras, auto_clean=False, subs=None, exclude=None):
@core_helper
def check_access(action, data_dict=None):
+ if not getattr(g, u'user', None):
+ g.user = ''
context = {'model': model,
- 'user': c.user}
+ 'user': g.user}
if not data_dict:
data_dict = {}
try:
| '_Globals' has no attribute 'user' : exception when using an IAuthenticator on CKAN 2.8.0
I'm putting together a new deployment based on the new CKAN v2.8.0 release. I'm using ckanext-ldap as an authenticator, though it looks like this bug would apply to any authenticator plugin.
This exact setup worked fine on CKAN v2.7.3.
### CKAN Version if known (or site URL)
CKAN v 2.8.0
ckanext-ldap @ `ckan-upgrade-2.8.0a`
### Please describe the expected behaviour
If the IAuthenticator plugin cannot authenticate the user, it does not set `g.user`, and CKAN should run the default authenticator.
### Please describe the actual behaviour
If the IAuthenticator plugin cannot authenticate the user, it does not set `g.user`, and CKAN tries to lookup `g.user` and crashes with traceback:
```
Traceback (most recent call last):
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1610, in full_dispatch_request
rv = self.preprocess_request()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1831, in preprocess_request
rv = func()
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 281, in ckan_before_request
identify_user()
File "/usr/lib/ckan/venv/src/ckan/ckan/views/__init__.py", line 101, in identify_user
if g.user:
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 334, in __getattr__
return getattr(app_globals.app_globals, name)
AttributeError: '_Globals' object has no attribute 'user'
```
### What steps can be taken to reproduce the issue?
* Install CKAN v2.8.0 as per documented instructions
* Install a plugin that implements IAuthenticator (In this case I am using the ckanext-ldap plugin in the 2.8.0 branch), that may not be able to authenticate the user, so may not set `g.user`.
* Run CKAN normally
* Attempt to load any page.
What is odd is that this section of code at `identify_user` in `ckan/views/__init__.py` has not changed between v2.7.3 and v2.8.0. And the way the authenticator plugin handles/sets `g.user` has not changed either. I'm guessing this is caused by a change in the way the _Globals object behaves when it cannot find an attribute.
| For the record, issue also occurs with _ckanext-saml2_ extension.
I propose to reopen this bug. I still have the very same error, but with a bit different Traceback.
The page loads correctly 4 times out of 5, if I am logged or not.
It does not happen if I run CKAN locally. I am using the very same container image on another server, where I do have this error. I checked multiple times, and the container has the patch that has been merged.
I use ckan-ldap, and the version I use has a patch too for this issue.
```
Traceback (most recent call last):
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1518, in handle_user_exception
return handler(e)
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 453, in error_handler
return base.render(u'error_document_template.html', extra_vars), 500
File "/usr/lib/ckan/venv/src/ckan/ckan/lib/base.py", line 128, in render
return flask_render_template(template_name, **extra_vars)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/templating.py", line 134, in render_template
context, ctx.app)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/templating.py", line 116, in _render
rv = template.render(context)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/jinja2/environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/error_document_template.html", line 1, in top-level template code
{% extends "page.html" %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/page.html", line 1, in top-level template code
{% extends "base.html" %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/base.html", line 101, in top-level template code
{%- block page %}{% endblock -%}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/page.html", line 14, in block "page"
{%- block header %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/page.html", line 15, in block "header"
{% include "header.html" %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/header.html", line 1, in top-level template code
{% block header_wrapper %} {% block header_account %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/header.html", line 1, in block "header_wrapper"
{% block header_wrapper %} {% block header_account %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/header.html", line 4, in block "header_account"
{% block header_account_container_content %} {% if c.userobj %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/header.html", line 51, in block "header_account_container_content"
{% block header_account_notlogged %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/header.html", line 53, in block "header_account_notlogged"
{% if h.check_access('user_create') %}
File "/usr/lib/ckan/venv/src/ckan/ckan/lib/helpers.py", line 1158, in check_access
'user': c.user}
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 368, in __getattr__
return getattr(app_globals.app_globals, name)
AttributeError: '_Globals' object has no attribute 'user'
----------------------------------------
Exception happened during processing of request from ('10.255.0.2', 51782)
Traceback (most recent call last):
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/httpserver.py", line 1068, in process_request_in_thread
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 331, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.7/SocketServer.py", line 652, in __init__
self.handle()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/httpserver.py", line 442, in handle
BaseHTTPRequestHandler.handle(self)
File "/usr/lib/python2.7/BaseHTTPServer.py", line 340, in handle
self.handle_one_request()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/httpserver.py", line 437, in handle_one_request
self.wsgi_execute()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/httpserver.py", line 287, in wsgi_execute
self.wsgi_start_response)
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/__init__.py", line 203, in __call__
return self.apps[app_name](environ, start_response)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/repoze/who/middleware.py", line 86, in __call__
app_iter = app(environ, wrapper.wrap_start_response)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/dec.py", line 147, in __call__
resp = self.call_func(req, *args, **self.kwargs)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/dec.py", line 208, in call_func
return self.func(req, *args, **kwargs)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/fanstatic/publisher.py", line 234, in __call__
return request.get_response(self.app)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/request.py", line 1053, in get_response
application, catch_exc_info=False)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/request.py", line 1022, in call_application
app_iter = application(self.environ, start_response)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/dec.py", line 147, in __call__
resp = self.call_func(req, *args, **self.kwargs)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/dec.py", line 208, in call_func
return self.func(req, *args, **kwargs)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/fanstatic/injector.py", line 54, in __call__
response = request.get_response(self.app)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/request.py", line 1053, in get_response
application, catch_exc_info=False)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/request.py", line 1022, in call_application
app_iter = application(self.environ, start_response)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/beaker/middleware.py", line 156, in __call__
return self.wrap_app(environ, session_start_response)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1547, in handle_exception
return self.finalize_request(handler(e), from_error_handler=True)
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 453, in error_handler
return base.render(u'error_document_template.html', extra_vars), 500
File "/usr/lib/ckan/venv/src/ckan/ckan/lib/base.py", line 128, in render
return flask_render_template(template_name, **extra_vars)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/templating.py", line 134, in render_template
context, ctx.app)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/templating.py", line 116, in _render
rv = template.render(context)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/jinja2/environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/error_document_template.html", line 1, in top-level template code
{% extends "page.html" %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/page.html", line 1, in top-level template code
{% extends "base.html" %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/base.html", line 101, in top-level template code
{%- block page %}{% endblock -%}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/page.html", line 14, in block "page"
{%- block header %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/page.html", line 15, in block "header"
{% include "header.html" %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/header.html", line 1, in top-level template code
{% block header_wrapper %} {% block header_account %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/header.html", line 1, in block "header_wrapper"
{% block header_wrapper %} {% block header_account %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/header.html", line 4, in block "header_account"
{% block header_account_container_content %} {% if c.userobj %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/header.html", line 51, in block "header_account_container_content"
{% block header_account_notlogged %}
File "/usr/lib/ckan/venv/src/ckan/ckan/templates/header.html", line 53, in block "header_account_notlogged"
{% if h.check_access('user_create') %}
File "/usr/lib/ckan/venv/src/ckan/ckan/lib/helpers.py", line 1158, in check_access
'user': c.user}
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 368, in __getattr__
return getattr(app_globals.app_globals, name)
```
Adding this code at the beginning of `check_access` fixes the issue for me:
```
if not getattr(c, u'user', None):
c.user = None
``` | 2018-12-06T11:54:46 |
|
ckan/ckan | 4,595 | ckan__ckan-4595 | [
"4594"
] | 8f0cb749f5c016468de2831173b11c041c4234f7 | diff --git a/ckan/model/license.py b/ckan/model/license.py
--- a/ckan/model/license.py
+++ b/ckan/model/license.py
@@ -6,7 +6,7 @@
from ckan.common import config
from paste.deploy.converters import asbool
-from six import text_type
+from six import text_type, string_types
from ckan.common import _, json
import ckan.lib.maintain as maintain
@@ -126,6 +126,11 @@ def load_licenses(self, license_url):
except Exception as inst:
msg = "Couldn't read response from licenses service %r: %s" % (response_body, inst)
raise Exception(inst)
+ for license in license_data:
+ if isinstance(license, string_types):
+ license = license_data[license]
+ if license.get('title'):
+ license['title'] = _(license['title'])
self._create_license_list(license_data, license_url)
def _create_license_list(self, license_data, license_url=''):
| diff --git a/ckan/tests/model/licenses.v1 b/ckan/tests/model/licenses.v1
--- a/ckan/tests/model/licenses.v1
+++ b/ckan/tests/model/licenses.v1
@@ -13,5 +13,19 @@
"domain_software": "False",
"id": "cc-by"
-}
+},
+ {
+ "domain_content": true,
+ "domain_data": false,
+ "domain_software": false,
+ "family": "",
+ "id": "other-open",
+ "is_generic": true,
+ "maintainer": "",
+ "od_conformance": "approved",
+ "osd_conformance": "not reviewed",
+ "status": "active",
+ "title": "Other (Open)",
+ "url": ""
+ }
]
diff --git a/ckan/tests/model/licenses.v2 b/ckan/tests/model/licenses.v2
--- a/ckan/tests/model/licenses.v2
+++ b/ckan/tests/model/licenses.v2
@@ -12,6 +12,19 @@
"status": "active",
"title": "Creative Commons Attribution 4.0",
"url": "https://creativecommons.org/licenses/by/4.0/"
-
+},
+"other-open": {
+ "domain_content": true,
+ "domain_data": false,
+ "domain_software": false,
+ "family": "",
+ "id": "other-open",
+ "is_generic": true,
+ "maintainer": "",
+ "od_conformance": "approved",
+ "osd_conformance": "not reviewed",
+ "status": "active",
+ "title": "Other (Open)",
+ "url": ""
}
}
diff --git a/ckan/tests/model/test_license.py b/ckan/tests/model/test_license.py
--- a/ckan/tests/model/test_license.py
+++ b/ckan/tests/model/test_license.py
@@ -6,7 +6,11 @@
from ckan.common import config
from ckan.model.license import LicenseRegister
-from ckan.tests import helpers
+from ckan.tests import helpers, factories
+
+assert_in = helpers.assert_in
+
+this_dir = os.path.dirname(os.path.realpath(__file__))
class TestLicenseRegister(object):
@@ -24,11 +28,8 @@ def test_default_register_has_basic_properties_of_a_license(self):
assert_equal(license.isopen(), True)
assert_equal(license.title, 'Creative Commons Attribution')
+ @helpers.change_config('licenses_group_url', 'file:///%s/licenses.v1' % this_dir)
def test_import_v1_style_register(self):
- this_dir = os.path.dirname(os.path.realpath(__file__))
- # v1 is used by CKAN so far
- register_filepath = '%s/licenses.v1' % this_dir
- config['licenses_group_url'] = 'file:///%s' % register_filepath
reg = LicenseRegister()
license = reg['cc-by']
@@ -37,11 +38,9 @@ def test_import_v1_style_register(self):
assert_equal(license.isopen(), True)
assert_equal(license.title, 'Creative Commons Attribution')
+ # v2 is used by http://licenses.opendefinition.org in recent times
+ @helpers.change_config('licenses_group_url', 'file:///%s/licenses.v2' % this_dir)
def test_import_v2_style_register(self):
- this_dir = os.path.dirname(os.path.realpath(__file__))
- # v2 is used by http://licenses.opendefinition.org in recent times
- register_filepath = '%s/licenses.v2' % this_dir
- config['licenses_group_url'] = 'file:///%s' % register_filepath
reg = LicenseRegister()
license = reg['CC-BY-4.0']
@@ -50,6 +49,26 @@ def test_import_v2_style_register(self):
assert_equal(license.isopen(), True)
assert_equal(license.title, 'Creative Commons Attribution 4.0')
+ @helpers.change_config('licenses_group_url', 'file:///%s/licenses.v1' % this_dir)
+ @helpers.change_config('ckan.locale_default', 'ca')
+ def test_import_v1_style_register_i18n(self):
+
+ sysadmin = factories.Sysadmin()
+ app = helpers._get_test_app()
+
+ resp = app.get('/dataset/new', extra_environ={'REMOTE_USER': str(sysadmin['name'])})
+ assert_in('Altres (Oberta)', resp.body)
+
+ @helpers.change_config('licenses_group_url', 'file:///%s/licenses.v2' % this_dir)
+ @helpers.change_config('ckan.locale_default', 'ca')
+ def test_import_v2_style_register_i18n(self):
+
+ sysadmin = factories.Sysadmin()
+ app = helpers._get_test_app()
+
+ resp = app.get('/dataset/new', extra_environ={'REMOTE_USER': str(sysadmin['name'])})
+ assert_in('Altres (Oberta)', resp.body)
+
class TestLicense:
def test_access_via_attribute(self):
| Titles from licenses from a custom file are not translated
Looks like this:

Should look like this:

| 2018-12-18T10:38:35 |
|
ckan/ckan | 4,601 | ckan__ckan-4601 | [
"3994"
] | 8f0cb749f5c016468de2831173b11c041c4234f7 | diff --git a/ckan/lib/jobs.py b/ckan/lib/jobs.py
--- a/ckan/lib/jobs.py
+++ b/ckan/lib/jobs.py
@@ -36,6 +36,7 @@
log = logging.getLogger(__name__)
DEFAULT_QUEUE_NAME = u'default'
+DEFAULT_JOB_TIMEOUT = config.get(u'ckan.jobs.timeout', 180)
# RQ job queues. Do not use this directly, use ``get_queue`` instead.
_queues = {}
@@ -123,7 +124,8 @@ def get_queue(name=DEFAULT_QUEUE_NAME):
return queue
-def enqueue(fn, args=None, kwargs=None, title=None, queue=DEFAULT_QUEUE_NAME):
+def enqueue(fn, args=None, kwargs=None, title=None, queue=DEFAULT_QUEUE_NAME,
+ timeout=DEFAULT_JOB_TIMEOUT):
u'''
Enqueue a job to be run in the background.
@@ -141,6 +143,9 @@ def enqueue(fn, args=None, kwargs=None, title=None, queue=DEFAULT_QUEUE_NAME):
:param string queue: Name of the queue. If not given then the
default queue is used.
+ :param integer timeout: The timeout, in seconds, to be passed
+ to the background job via rq.
+
:returns: The enqueued job.
:rtype: ``rq.job.Job``
'''
@@ -148,7 +153,8 @@ def enqueue(fn, args=None, kwargs=None, title=None, queue=DEFAULT_QUEUE_NAME):
args = []
if kwargs is None:
kwargs = {}
- job = get_queue(queue).enqueue_call(func=fn, args=args, kwargs=kwargs)
+ job = get_queue(queue).enqueue_call(func=fn, args=args, kwargs=kwargs,
+ timeout=timeout)
job.meta[u'title'] = title
job.save()
msg = u'Added background job {}'.format(job.id)
| diff --git a/ckan/tests/lib/test_jobs.py b/ckan/tests/lib/test_jobs.py
--- a/ckan/tests/lib/test_jobs.py
+++ b/ckan/tests/lib/test_jobs.py
@@ -74,6 +74,18 @@ def test_enqueue_queue(self):
assert_equal(all_jobs[1].origin,
jobs.add_queue_name_prefix(u'my_queue'))
+ def test_enqueue_timeout(self):
+ self.enqueue()
+ self.enqueue(timeout=0)
+ self.enqueue(timeout=-1)
+ self.enqueue(timeout=3600)
+ all_jobs = self.all_jobs()
+ assert_equal(len(all_jobs), 4)
+ assert_equal(all_jobs[0].timeout, 180)
+ assert_equal(all_jobs[1].timeout, 180)
+ assert_equal(all_jobs[2].timeout, -1)
+ assert_equal(all_jobs[3].timeout, 3600)
+
class TestGetAllQueues(RQTestBase):
| JobTimeoutException: Job exceeded maximum timeout value (180 seconds)
### CKAN Version if known (or site URL)
CKAN 2.7
### Please describe the expected behaviour
expected behavior is to be able to configure background jobs timeout
### Please describe the actual behaviour
There should be a way to extend the timeout
### What steps can be taken to reproduce the issue?
1. I created a background job following the ckan documentation [docs](http://docs.ckan.org/en/latest/maintaining/background-tasks.html)
2. Tried to pass `timeout=3600` as a parameter
3. Throws the following error:
```
(default) samuel@ckan:~$ paster --plugin=ckanext-gather2_integration gather2_integration load-data --config=/etc/ckan/default/development.ini
2018-01-23 10:52:41,374 DEBUG [ckanext.validation.plugin] Validation tables exist
Loading gather2 data
Traceback (most recent call last):
File "/usr/lib/ckan/default/bin/paster", line 11, in <module>
sys.exit(run())
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run
invoke(command, command_name, options, args[1:])
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke
exit_code = runner.run(args)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run
result = self.command()
File "/usr/lib/ckan/default/src/ckanext-gather2_integration/ckanext/gather2_integration/commands.py", line 47, in command
self.run_load_data()
File "/usr/lib/ckan/default/src/ckanext-gather2_integration/ckanext/gather2_integration/commands.py", line 59, in run_load_data
get_action(u'gather2_integration_run')({'load-data':'true'})
File "/usr/lib/ckan/default/src/ckan/ckan/logic/__init__.py", line 457, in wrapped
result = _action(context, data_dict, **kw)
File "/usr/lib/ckan/default/src/ckanext-gather2_integration/ckanext/gather2_integration/logic.py", line 20, in gather2_integration_run
enqueue_job(run_gather2_integration,[], timeout=3600)
File "/usr/lib/ckan/default/src/ckanext-gather2_integration/ckanext/gather2_integration/logic.py", line 13, in enqueue_job
return t.enqueue_job(*args, **kwargs)
TypeError: enqueue() got an unexpected keyword argument 'timeout'
```
4. Without the parameter it defaults to 180 seconds with the following error:
```
r = requests.get(url, headers=headers)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/requests/api.py", line 70, in get
return request('get', url, params=params, **kwargs)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/requests/api.py", line 56, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/requests/sessions.py", line 488, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/requests/sessions.py", line 609, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/requests/adapters.py", line 423, in send
timeout=timeout
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 345, in _make_request
self._validate_conn(conn)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 844, in _validate_conn
conn.connect()
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/requests/packages/urllib3/connection.py", line 326, in connect
ssl_context=context)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/requests/packages/urllib3/util/ssl_.py", line 324, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/requests/packages/urllib3/contrib/pyopenssl.py", line 436, in wrap_socket
cnx.do_handshake()
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/OpenSSL/SSL.py", line 1715, in do_handshake
result = _lib.SSL_do_handshake(self._ssl)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/rq/timeouts.py", line 51, in handle_death_penalty
'value ({0} seconds)'.format(self._timeout))
JobTimeoutException: Job exceeded maximum timeout value (180 seconds)
```
5. I need help.
| Yes, it looks like we aren't passing the timeout value through to RQ's enqueue_call in https://github.com/ckan/ckan/blob/master/ckan/lib/jobs.py#L126
Should be a very small change, would you mind submitting a PR?
Sure.
Another possibility would be to add a configuration option to globally specify these timeouts.

@wardi Good idea: A default timeout that is configurable via the INI and can be overridden using a parameter while enqueuing a job.
@torfsen Makes sense to do it that way. Should have the PR ready when I have a minute today. Thanks
@s-chand thanks! I've also been bitten by this
Just been bitten by this one whilst using [ckanext-rq](https://github.com/ckan/ckanext-rq) and found this existing issue. It seems to have gone pretty stale since the start of the year, did anyone submit anything to resolve this in the end (to either here or to [ckanext-rq](https://github.com/ckan/ckanext-rq))? From looking around it doesn't look like it but thought it was worth making sure before I look at submitting a PR for it.
@jrdh AFAIK there hasn't been any work on this issue, so feel free to submit a PR. You can probably reuse most of the code for a PR against CKAN for a similar one against ckanext-rq.
:+1: thanks @torfsen, and yeah that's what I would expect too. | 2018-12-21T15:45:22 |
ckan/ckan | 4,623 | ckan__ckan-4623 | [
"4611"
] | a342792b97d95623bce739d8ce9030dc45fee220 | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -1,6 +1,7 @@
# encoding: utf-8
import os
+import sys
import re
import time
import inspect
@@ -41,6 +42,7 @@
import ckan.lib.plugins as lib_plugins
import logging
+from logging.handlers import SMTPHandler
log = logging.getLogger(__name__)
@@ -442,6 +444,7 @@ def _register_error_handler(app):
u'''Register error handler'''
def error_handler(e):
+ log.error(e, exc_info=sys.exc_info)
if isinstance(e, HTTPException):
extra_vars = {u'code': [e.code], u'content': e.description}
# TODO: Remove
@@ -456,3 +459,37 @@ def error_handler(e):
app.register_error_handler(code, error_handler)
if not app.debug and not app.testing:
app.register_error_handler(Exception, error_handler)
+ if config.get('email_to'):
+ _setup_error_mail_handler(app)
+
+
+def _setup_error_mail_handler(app):
+
+ class ContextualFilter(logging.Filter):
+ def filter(self, log_record):
+ log_record.url = request.path
+ log_record.method = request.method
+ log_record.ip = request.environ.get("REMOTE_ADDR")
+ log_record.headers = request.headers
+ return True
+
+ mailhost = tuple(config.get('smtp.server', 'localhost').split(":"))
+ mail_handler = SMTPHandler(
+ mailhost=mailhost,
+ fromaddr=config.get('error_email_from'),
+ toaddrs=[config.get('email_to')],
+ subject='Application Error'
+ )
+
+ mail_handler.setFormatter(logging.Formatter('''
+Time: %(asctime)s
+URL: %(url)s
+Method: %(method)s
+IP: %(ip)s
+Headers: %(headers)s
+
+'''))
+
+ context_provider = ContextualFilter()
+ app.logger.addFilter(context_provider)
+ app.logger.addHandler(mail_handler)
| Error emails are not sent in flask routes
### CKAN Version if known (or site URL)
2.8, master
### Please describe the expected behaviour
When some route generates an error and error emails are configured, stacktrace and other info are expected to be mailed in specified email address.
### Please describe the actual behaviour
If the route is migrated to flask, the error email is never sent. Most likely due to the that mailing is based on pylons error middleware https://docs.pylonsproject.org/projects/pylons-webframework/en/latest/modules/middleware.html#pylons.middleware.ErrorHandler
### What steps can be taken to reproduce the issue?
Configure error emails.
Insert syntax error to route migrated to flask. For example view/user.py.
Error page is generated, email is not sent.
| Yes, this was an internal Pylons feature so we lost it during the migration. It seems pretty easy to add an [email log handler](http://flask.pocoo.org/docs/1.0/logging/#email-errors-to-admins) that would replace this functionality. And perhaps there is an already existing Flask plugin that wraps this.
Marking as Good for Contribution in case @Zharktas or someone else wants to work on it. | 2019-01-17T11:15:43 |
|
ckan/ckan | 4,630 | ckan__ckan-4630 | [
"4629"
] | 5d7a4985f283b1d424c4a1ce3252eedb35f76e83 | diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py
--- a/ckan/logic/validators.py
+++ b/ckan/logic/validators.py
@@ -690,18 +690,19 @@ def url_validator(key, data, errors, context):
import urlparse
import string
- model = context['model']
- session = context['session']
-
url = data.get(key, None)
if not url:
return
- pieces = urlparse.urlparse(url)
- if all([pieces.scheme, pieces.netloc]) and \
- set(pieces.netloc) <= set(string.letters + string.digits + '-.') and \
- pieces.scheme in ['http', 'https']:
- return
+ try:
+ pieces = urlparse.urlparse(url)
+ if all([pieces.scheme, pieces.netloc]) and \
+ set(pieces.netloc) <= set(string.letters + string.digits + '-.') and \
+ pieces.scheme in ['http', 'https']:
+ return
+ except ValueError:
+ # url is invalid
+ pass
errors[key].append(_('Please provide a valid URL'))
| diff --git a/ckan/tests/logic/test_validators.py b/ckan/tests/logic/test_validators.py
--- a/ckan/tests/logic/test_validators.py
+++ b/ckan/tests/logic/test_validators.py
@@ -611,4 +611,31 @@ def call_validator(*args, **kwargs):
errors[key] = []
call_validator(key, {key: password}, errors, None)
+
+class TestUrlValidator(object):
+
+ def test_ok(self):
+ urls = ['http://example.com', 'https://example.com', 'https://example.com/path?test=1&key=2']
+ key = ('url',)
+
+ @t.does_not_modify_errors_dict
+ def call_validator(*args, **kwargs):
+ return validators.url_validator(*args, **kwargs)
+ for url in urls:
+ errors = factories.validator_errors_dict()
+ errors[key] = []
+ call_validator(key, {key: url}, errors, None)
+
+ def test_invalid(self):
+ urls = ['ftp://example.com', 'test123', 'https://example.com]']
+ key = ('url',)
+
+ @adds_message_to_errors_dict('Please provide a valid URL')
+ def call_validator(*args, **kwargs):
+ return validators.url_validator(*args, **kwargs)
+ for url in urls:
+ errors = factories.validator_errors_dict()
+ errors[key] = []
+ call_validator(key, {key: url}, errors, None)
+
# TODO: Need to test when you are not providing owner_org and the validator queries for the dataset with package_show
| url_validator fails for invalid URLs
### CKAN Version if known (or site URL)
CKAN 2.7, CKAN 2.8, master
### Please describe the expected behaviour
`url_validator` validates if a field contains a URL or not.
### Please describe the actual behaviour
The `url_validator` fails if certain invalid URLs are provided, e.g. `https://example.com]`.
The problem is, that `urlparse` raises a `ValueError` which is not caught in `url_validator`.
### What steps can be taken to reproduce the issue?
1. Add the `url_validator` to a field
2. Provide the value `https://example.com]`
3. Server error with `ValueError: Invalid IPv6 URL` in logfile
I'm working on a PR to fix this issue.
| 2019-01-23T13:20:51 |
|
ckan/ckan | 4,657 | ckan__ckan-4657 | [
"4431"
] | 93ac068499a422c67bb90aed92ca071cb5061cc8 | diff --git a/ckan/config/middleware/pylons_app.py b/ckan/config/middleware/pylons_app.py
--- a/ckan/config/middleware/pylons_app.py
+++ b/ckan/config/middleware/pylons_app.py
@@ -138,10 +138,7 @@ def make_pylons_stack(conf, full_stack=True, static_files=True,
)
# Establish the Registry for this application
- # The RegistryManager includes code to pop
- # registry values after the stream has completed,
- # so we need to prevent this with `streaming` set to True.
- app = RegistryManager(app, streaming=True)
+ app = RegistryManager(app, streaming=False)
if asbool(static_files):
# Serve static files
| exception after upgrade to 2.8.1 - Popped wrong app context
After upgrade from 2.7 to 2.8.1 - I'm seeing some exceptions in a production server log, couldn't reproduce the error locally
### CKAN Version if known (or site URL)
2.8.1
### Please describe the expected behaviour
no exception (or less cryptic exception..)
### Please describe the actual behaviour
exception -
```
-------------------------------------------------------------
Error - <type 'exceptions.AssertionError'>: Popped wrong app context. (<flask.ctx.AppContext object at 0x7f3ac4b90b10> instead of <flask.ctx.AppContext object at 0x7f3ac4b90690>)
URL: http://www.odata.org.il/organization/hatzlacha?license_id=cc-by&tags=%D7%94%D7%AA%D7%A4%D7%A8%D7%A6%D7%95%D7%AA+%D7%9C%D7%9E%D7%A7%D7%95%D7%9D+%D7%9E%D7%92%D7%95%D7%A8%D7%99%D7%9D&organization=hatzlacha&res_format=DOC&tags=%D7%A2%D7%99%D7%9B%D7%95%D7%91+%D7%94%D7%9C%D7%99%D7%9B%D7%99%D7%9D
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/weberror/errormiddleware.py', line 171 in __call__
app_iter = self.application(environ, sr_checker)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/fanstatic/publisher.py', line 234 in __call__
return request.get_response(self.app)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
application, catch_exc_info=False)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
app_iter = application(self.environ, start_response)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/fanstatic/injector.py', line 54 in __call__
response = request.get_response(self.app)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
application, catch_exc_info=False)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
app_iter = application(self.environ, start_response)
File '/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/pylons_app.py', line 265 in inner
result = application(environ, start_response)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/beaker/middleware.py', line 73 in __call__
return self.app(environ, start_response)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/beaker/middleware.py', line 156 in __call__
return self.wrap_app(environ, session_start_response)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/routes/middleware.py', line 131 in __call__
response = self.app(environ, start_response)
File '/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/common_middleware.py', line 30 in __call__
return self.app(environ, start_response)
File '/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/common_middleware.py', line 56 in __call__
return self.app(environ, start_response)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 125 in __call__
response = self.dispatch(controller, environ, start_response)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 324 in dispatch
return controller(environ, start_response)
File '/usr/lib/ckan/venv/src/ckan/ckan/lib/base.py', line 240 in __call__
res = WSGIController.__call__(self, environ, start_response)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 221 in __call__
response = self._dispatch_call()
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 172 in _dispatch_call
response = self._inspect_call(func)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 107 in _inspect_call
result = self._perform_call(func, args)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 60 in _perform_call
return func(**args)
File '/usr/lib/ckan/venv/src/ckan/ckan/controllers/group.py', line 230 in read
extra_vars={'group_type': group_type})
File '/usr/lib/ckan/venv/src/ckan/ckan/lib/base.py', line 125 in render
return cached_template(template_name, renderer)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/pylons/templating.py', line 249 in cached_template
return render_func()
File '/usr/lib/ckan/venv/src/ckan/ckan/lib/base.py', line 162 in render_template
return render_jinja2(template_name, globs)
File '/usr/lib/ckan/venv/src/ckan/ckan/lib/base.py', line 94 in render_jinja2
return template.render(**extra_vars)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/jinja2/environment.py', line 989 in render
return self.environment.handle_exception(exc_info, True)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/jinja2/environment.py', line 754 in handle_exception
reraise(exc_type, exc_value, tb)
File '/usr/lib/ckan/venv/src/ckan/ckan/templates/organization/read.html', line 1 in top-level template code
{% extends "organization/read_base.html" %}
File '/usr/lib/ckan/venv/src/ckan/ckan/templates/organization/read_base.html', line 1 in top-level template code
{% extends "page.html" %}
File '/usr/lib/ckan/venv/src/ckan/ckan/templates/page.html', line 1 in top-level template code
{% extends "base.html" %}
File '/ckanext-odata_org_il/ckanext/odata_org_il/templates/base.html', line 1 in top-level template code
{% ckan_extends %}
File '/usr/lib/ckan/venv/src/ckan/ckan/templates/base.html', line 101 in top-level template code
{%- block page %}{% endblock -%}
File '/usr/lib/ckan/venv/src/ckan/ckan/templates/page.html', line 125 in block "page"
{%- block footer %}
File '/usr/lib/ckan/venv/src/ckan/ckan/templates/page.html', line 126 in block "footer"
{% include "footer.html" %}
File '/ckanext-odata_org_il/ckanext/odata_org_il/templates/footer.html', line 3 in top-level template code
{% block footer_content %}
File '/ckanext-odata_org_il/ckanext/odata_org_il/templates/footer.html', line 32 in block "footer_content"
{% block footer_lang %}
File '/ckanext-odata_org_il/ckanext/odata_org_il/templates/footer.html', line 33 in block "footer_lang"
{% snippet "snippets/language_selector.html" %}
File '/usr/lib/ckan/venv/src/ckan/ckan/lib/jinja_extensions.py', line 268 in _call
return base.render_snippet(args[0], **kwargs)
File '/usr/lib/ckan/venv/src/ckan/ckan/lib/base.py', line 84 in render_snippet
output = render(template_name, extra_vars=kw)
File '/usr/lib/ckan/venv/src/ckan/ckan/lib/base.py', line 125 in render
return cached_template(template_name, renderer)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/pylons/templating.py', line 249 in cached_template
return render_func()
File '/usr/lib/ckan/venv/src/ckan/ckan/lib/base.py', line 162 in render_template
return render_jinja2(template_name, globs)
File '/usr/lib/ckan/venv/src/ckan/ckan/lib/base.py', line 94 in render_jinja2
return template.render(**extra_vars)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/jinja2/environment.py', line 989 in render
return self.environment.handle_exception(exc_info, True)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/jinja2/environment.py', line 754 in handle_exception
reraise(exc_type, exc_value, tb)
File '/usr/lib/ckan/venv/src/ckan/ckan/templates/snippets/language_selector.html', line 2 in top-level template code
<form class="form-inline form-select lang-select" action="{% url_for controller='util', action='redirect' %}" data-module="select-switch" method="POST">
File '/usr/lib/ckan/venv/src/ckan/ckan/lib/jinja_extensions.py', line 297 in _call
return h.url_for(*args, **kwargs)
File '/usr/lib/ckan/venv/src/ckan/ckan/lib/helpers.py', line 326 in url_for
_auto_flask_context.pop()
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/ctx.py', line 376 in pop
app_ctx.pop(exc)
File '/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/ctx.py', line 193 in pop
% (rv, self)
AssertionError: Popped wrong app context. (<flask.ctx.AppContext object at 0x7f3ac4b90b10> instead of <flask.ctx.AppContext object at 0x7f3ac4b90690>)
CGI Variables
-------------
CKAN_CURRENT_URL: '/organization/hatzlacha?license_id%3Dcc-by%26tags%3D%25D7%2594%25D7%25AA%25D7%25A4%25D7%25A8%25D7%25A6%25D7%2595%25D7%25AA%2B%25D7%259C%25D7%259E%25D7%25A7%25D7%2595%25D7%259D%2B%25D7%259E%25D7%2592%25D7%2595%25D7%25A8%25D7%2599%25D7%259D%26organization%3Dhatzlacha%26res_format%3DDOC%26tags%3D%25D7%25A2%25D7%2599%25D7%259B%25D7%2595%25D7%2591%2B%25D7%2594%25D7%259C%25D7%2599%25D7%259B%25D7%2599%25D7%259D'
CKAN_LANG: 'he'
CKAN_LANG_IS_DEFAULT: True
CONTENT_LENGTH: '0'
HTTP_ACCEPT: '*/*'
HTTP_ACCEPT_ENCODING: 'gzip'
HTTP_CF_CONNECTING_IP: ' --- '
HTTP_CF_IPCOUNTRY: 'US'
HTTP_CF_RAY: '450eef3ef9fa5afd-HEL'
HTTP_CF_VISITOR: '{"scheme":"https"}'
HTTP_HOST: 'www.odata.org.il'
HTTP_USER_AGENT: ' --- '
HTTP_X_FORWARDED_FOR: ' --- '
HTTP_X_FORWARDED_HOST: 'www.odata.org.il'
HTTP_X_FORWARDED_PORT: '443'
HTTP_X_FORWARDED_PROTO: 'https'
HTTP_X_FORWARDED_SERVER: 'traefik-77ccf967dc-4dfwt'
HTTP_X_REAL_IP: '10.132.0.5'
PATH_INFO: '/organization/hatzlacha'
QUERY_STRING: 'license_id=cc-by&tags=%D7%94%D7%AA%D7%A4%D7%A8%D7%A6%D7%95%D7%AA+%D7%9C%D7%9E%D7%A7%D7%95%D7%9D+%D7%9E%D7%92%D7%95%D7%A8%D7%99%D7%9D&organization=hatzlacha&res_format=DOC&tags=%D7%A2%D7%99%D7%9B%D7%95%D7%91+%D7%94%D7%9C%D7%99%D7%9B%D7%99%D7%9D'
REMOTE_ADDR: '10.20.1.228'
REQUEST_METHOD: 'GET'
SERVER_NAME: '0.0.0.0'
SERVER_PORT: '5000'
SERVER_PROTOCOL: 'HTTP/1.1'
WSGI Variables
--------------
__no_cache__: True
application: <fanstatic.publisher.Delegator object at 0x7f3ac38876d0>
beaker.cache: <beaker.cache.CacheManager object at 0x7f3ac3887690>
beaker.get_session: <bound method SessionMiddleware._get_session of <beaker.middleware.SessionMiddleware object at 0x7f3ac38875d0>>
beaker.session: {'_accessed_time': 1535377065.228329, '_creation_time': 1535377065.228329}
ckan.app: 'pylons_app'
fanstatic.needed: <fanstatic.core.NeededResources object at 0x7f3aa9ff7450>
paste.cookies: (<SimpleCookie: >, '')
paste.httpserver.thread_pool: <paste.httpserver.ThreadPool object at 0x7f3ac4b8e910>
paste.parsed_dict_querystring: (MultiDict([('license_id', 'cc-by'), ('tags', '\xd7\x94\xd7\xaa\xd7\xa4\xd7\xa8\xd7\xa6\xd7\x95\xd7\xaa \xd7\x9c\xd7\x9e\xd7\xa7\xd7\x95\xd7\x9d \xd7\x9e\xd7\x92\xd7\x95\xd7\xa8\xd7\x99\xd7\x9d'), ('organization', 'hatzlacha'), ('res_format', 'DOC'), ('tags', '\xd7\xa2\xd7\x99\xd7\x9b\xd7\x95\xd7\x91 \xd7\x94\xd7\x9c\xd7\x99\xd7\x9b\xd7\x99\xd7\x9d')]), 'license_id=cc-by&tags=%D7%94%D7%AA%D7%A4%D7%A8%D7%A6%D7%95%D7%AA+%D7%9C%D7%9E%D7%A7%D7%95%D7%9D+%D7%9E%D7%92%D7%95%D7%A8%D7%99%D7%9D&organization=hatzlacha&res_format=DOC&tags=%D7%A2%D7%99%D7%9B%D7%95%D7%91+%D7%94%D7%9C%D7%99%D7%9B%D7%99%D7%9D')
paste.parsed_querystring: ([('license_id', 'cc-by'), ('tags', '\xd7\x94\xd7\xaa\xd7\xa4\xd7\xa8\xd7\xa6\xd7\x95\xd7\xaa \xd7\x9c\xd7\x9e\xd7\xa7\xd7\x95\xd7\x9d \xd7\x9e\xd7\x92\xd7\x95\xd7\xa8\xd7\x99\xd7\x9d'), ('organization', 'hatzlacha'), ('res_format', 'DOC'), ('tags', '\xd7\xa2\xd7\x99\xd7\x9b\xd7\x95\xd7\x91 \xd7\x94\xd7\x9c\xd7\x99\xd7\x9b\xd7\x99\xd7\x9d')], 'license_id=cc-by&tags=%D7%94%D7%AA%D7%A4%D7%A8%D7%A6%D7%95%D7%AA+%D7%9C%D7%9E%D7%A7%D7%95%D7%9D+%D7%9E%D7%92%D7%95%D7%A8%D7%99%D7%9D&organization=hatzlacha&res_format=DOC&tags=%D7%A2%D7%99%D7%9B%D7%95%D7%91+%D7%94%D7%9C%D7%99%D7%9B%D7%99%D7%9D')
paste.registry: <paste.registry.Registry object at 0x7f3ac3f14450>
paste.throw_errors: True
pylons.action_method: <bound method OrganizationController.read of <ckan.controllers.organization.OrganizationController object at 0x7f3aa8826b10>>
pylons.controller: <ckan.controllers.organization.OrganizationController object at 0x7f3aa8826b10>
pylons.environ_config: {'session': 'beaker.session', 'cache': 'beaker.cache'}
pylons.pylons: <pylons.util.PylonsContext object at 0x7f3aa8826d50>
pylons.routes_dict: {'action': u'read', 'controller': u'organization', 'id': u'hatzlacha'}
repoze.who.api: <repoze.who.api.API object at 0x7f3ac37da0d0>
repoze.who.logger: <logging.Logger object at 0x7f3ac3887890>
repoze.who.plugins: {'ckan.lib.authenticator:UsernamePasswordAuthenticator': <ckan.lib.authenticator.UsernamePasswordAuthenticator object at 0x7f3ac3acd090>, 'friendlyform': <FriendlyFormPlugin 139890367716112>, 'auth_tkt': <CkanAuthTktCookiePlugin 139890367715984>}
routes.route: <routes.route.Route object at 0x7f3ac4b13f10>
routes.url: <routes.util.URLGenerator object at 0x7f3ac40d9690>
webob._parsed_query_vars: (GET([('license_id', 'cc-by'), ('tags', '\xd7\x94\xd7\xaa\xd7\xa4\xd7\xa8\xd7\xa6\xd7\x95\xd7\xaa \xd7\x9c\xd7\x9e\xd7\xa7\xd7\x95\xd7\x9d \xd7\x9e\xd7\x92\xd7\x95\xd7\xa8\xd7\x99\xd7\x9d'), ('organization', 'hatzlacha'), ('res_format', 'DOC'), ('tags', '\xd7\xa2\xd7\x99\xd7\x9b\xd7\x95\xd7\x91 \xd7\x94\xd7\x9c\xd7\x99\xd7\x9b\xd7\x99\xd7\x9d')]), 'license_id=cc-by&tags=%D7%94%D7%AA%D7%A4%D7%A8%D7%A6%D7%95%D7%AA+%D7%9C%D7%9E%D7%A7%D7%95%D7%9D+%D7%9E%D7%92%D7%95%D7%A8%D7%99%D7%9D&organization=hatzlacha&res_format=DOC&tags=%D7%A2%D7%99%D7%9B%D7%95%D7%91+%D7%94%D7%9C%D7%99%D7%9B%D7%99%D7%9D')
webob.adhoc_attrs: {'response': <Response at 0x7f3aa9ff7990 200 OK>, 'language': 'en-us'}
wsgi process: 'Multithreaded'
wsgiorg.routing_args: (<routes.util.URLGenerator object at 0x7f3ac40d9690>, {'action': u'read', 'controller': u'organization', 'id': u'hatzlacha'})
------------------------------------------------------------
```
### What steps can be taken to reproduce the issue?
I'm just seeing those exception in the server logs, couldn't reproduce locally
| seems to be solved by switching to gunicorn to serve wsgi (used paster serve before)
still interesting to understand why it happens
Same error here, but I'm using Apache instead of Nginx. Could you give me more information about the solution adopted?
Install Gunicorn
```
pip install gunicorn
```
Start the server using Gunicorn
```
gunicorn --paste /path/to/ckan.ini
```
When I launch the application, it asks me to install each CKAN module, including the plugins that I have enabled. I already have an instance of CKAN installed with these plugins working perfectly, running on Apache. Is it necessary to reinstall everything?
Thx
Probably you are running gunicorn from a different Python virtualenv then your CKAN instance - causing it to not recognize the installed plugins.
Thanks @OriHoch, I have managed to configure CKAN with gunicorn but due to its complexity (I have not configured it completely, there are things that do not work correctly), I think I'm not able to replace Apache or Nginx for this in my production environment.
@amercader, Do you plan to take a fix for this bug soon?
Thx.
This is also happening with an upgrade to 2.8.2. I can provide a full error log with debug output, if needed. To see how we're deploying, folks can refer to our Ansible playbook:
https://github.com/City-of-Bloomington/ckan-deploy
This seems to be related to problems with multithreading. Either flask or the ckan code doesn't seem to be thread-safe. As soon as more than one request is in flight at the same time, the popped wrong app context error occurs, and the site crashes.
In Apache, I've limited our daemon to only one process and one thread. For now, this seems to have alleviated the problem.
```apache
WSGIScriptAlias / "/srv/sites/ckan/public/ckan.wsgi"
WSGIPassAuthorization On
WSGIDaemonProcess ckan processes=1 threads=1
WSGIProcessGroup ckan
<Directory "/srv/sites/ckan/public">
Options FollowSymLinks
AllowOverride None
Require all granted
</Directory>
```
Looking into this. It's reproducible for example by generating a large number of organizations (I generated 1360), setting processes and threads to low numbers, then requesting the organization list page repeatedly.
I'm seeing `ckan.lib.helpers.url_for` calling `_get_auto_flask_context` and receiving `_internal_test_request_context` back. The `_request_ctx_stack.top` it's probably supposed to return for real calls is `None`.
Diving deeper, the expected flask app context is pushed in a different thread than where it is supposed to be popped. So thread T1 may push app context C1 to be used for request context R1, and T2 push C2 for R2, but R1 ends up being exectuted in T2 and get C2 and vice versa. Trying to parse my thread-identified logging it looks like this:
T1, R3: push C3
T1, R1: push C1
T1, R1: pop -> C1
T2, R2: push C2
T1, R2: pop -> C3 (error, expected C2)
T2, R3: pop -> C2 (error, expected C3)
I instrumented `/usr/lib/ckan/default/lib/python2.7/site-packages/flask/ctx.py` app and request context push/pop functions to print `thread.get_ident()` and `hex(id(self))`. I then search-and-replaced the memory addresses into the more readable format above.
T1: Push app context C1
T1: Push request context R1
T1: Pop request context R1
T1: Popped correct app context C1
T1: Push app context C2
T1: Push request context R1
T1: Pop request context R1
T1: Popped correct app context C2
T2: Push app context C3
T2: Push request context R1
T2: Pop request context R1
T2: Popped correct app context C3
T2: Push app context C4
T2: Push request context R1
T2: Pop request context R1
T2: Popped correct app context C4
T2: Push app context C5
T2: Push request context R1
T1: Push app context C6
T1: Push request context R1
T2: Pop request context R1
T2: Popped wrong app context. (C5 instead of C6)
T1: Pop request context R1
T1: Popped wrong app context. (C6 instead of C5)
As can be seen, as long as the same thread pushes and pops the app context before the other gets its turn, everything works out fine. But the moment there's a push from both threads consecutively, the error manifests. The app context stacks are thread-local, so the requests should be handled in the thread they were created at.
A curious addition is that all the request contexts are `R1`, meaning they all point to the same object regardless of thread. Not sure yet if this can cause issues, but it sure sounds suspicious.
As near as I can tell, the request context created in `ckan.config.middleware.AskAppDispatcherMiddleware.__call__` on the line `with flask_app.test_request_context():` in pylons core request handling doesn't live as long as the request handling takes. The request context is popped from the stack as soon as the `self.apps[app_name](environ, start_response)` returns. Then the thread moves on to process the next request.
Now, pylons seems to do multithread request handling, so the request context is actually needed longer than this. Because the `_request_ctx_stack` is now empty, `_get_auto_flask_context` returns the same (AFAICT) entirely thread-unsafe global `ckan.config.middleware._internal_test_request_context` for every pylons call, which even has the comment `"This is a test Flask request context to be used internally. Do not use it!"`.
This may be the main culprit. As the error message "Popped wrong app context" implies, the Flask `AppContext` already knows what should be on the top of the thread-local `_app_ctx_stack` when `pop()` is called. This means that the `AppContext.pop()` is being called in the wrong thread, which suggests the `AppContext` object has somehow traveled from one thread to another and I'm guessing it's through the shared `RequestContext` object.
Pylons needs to run single-threaded if it's embedded with flask contexts like this. The problem only shows when there are enough multiple concurrent requests, because otherwise the same thread seems to get to handle all parts of generating the response, meaning the correct `AppContext` will always be available.
Last clue for now: Calling the same organization list view just once results in
// These are executed under /etc/ckan/default/apache.wsgi
push C1
push R1
execute pylons middleware
pop R1
pop C1
// Then, these are executed under /usr/lib/ckan/default/lib/python2.7/site-packages/paste/registry.py
push C2
push R2
pop R2
pop C2
push C3
push R2
pop R2
pop C3
...
The actual request context, `R1`, is only available for the first part of the full handling run by `apache.wsgi`. Each subsequent part run by paste with `RegistryManager` receives the same global test request context because the request context stack is empty. Based on where the app is running during the latter events, namely template rendering (hence `url_for` I reported earlier), I'm guessing the response isn't sent yet.
Waiting for an opinion on the findings above and potential solutions before digging deeper. Someone more familiar with the code can probably see the issue more clearly. Is the context pushed in `apache.wsgi` supposed to be available when the request is actually processed? What is the threading instance that runs the `RegistryManager`-rooted parts of the request processing and how are they synchronized with the wsgi handling?
@bzar a potential workaround for this could be to make the default request context objects thread-safe. We do that for some other wrappers in `ckan/common.py`. Can you try if applying this patch and see if it helps? (it's based on the `dev-v2.8` branch):
```diff
diff --git a/ckan/config/middleware/__init__.py b/ckan/config/middleware/__init__.py
index 082372d70..fd3eeccc5 100644
--- a/ckan/config/middleware/__init__.py
+++ b/ckan/config/middleware/__init__.py
@@ -5,6 +5,7 @@ import urllib
import urlparse
import urllib
+from werkzeug.local import Local
import webob
from routes import request_config as routes_request_config
@@ -64,7 +65,11 @@ def make_app(conf, full_stack=True, static_files=True, **app_conf):
# Set this internal test request context with the configured environment so
# it can be used when calling url_for from tests
global _internal_test_request_context
- _internal_test_request_context = flask_app._wsgi_app.test_request_context()
+
+ local = Local()
+ local(u'_internal_test_request_context')
+ local._internal_test_request_context = flask_app._wsgi_app.test_request_context()
+ _internal_test_request_context = local._internal_test_request_context
return app
```
Okay, after extensive testing I can say this does not seem to fix the issue, but affects it somehow. It did seem like it worked at first, but ultimately it seems to merely have narrowed the cases it happens in.
With my current test case I can still reproduce the issue, but only with a newly started apache. I think this is because it takes longer to handle the first calls, so if I picked even longer page loads it would probably still pop up.
However, this means the application context thread-hopping probably happens somewhere else, or all the thread-local duplicated test contexts refer to some same global data, even if they themselves are thread-local.
nice work @bzar ! I tried to investigate myself initially but gave up much sooner then you :) very hard to debug it
Setting `streaming=False` here <https://github.com/ckan/ckan/blob/master/ckan/config/middleware/pylons_app.py#L144> seems to fix the issue completely as far as I can see. It makes the entire pylons call synchronous within the wsgi call handling. The `streaming=True` was introduced in CKAN 2.8.
Just to explain how I got there: After trying amercader's patch I realized the issue was going to be really hairy to fix by adding synchronization primitives. There were always going to be places where the entire thing could fall apart since the system wasn't designed to be used this way. So I went back to finding out the reason for the parallelization in the first place. WSGI should already parallelize handling the calls, so further parallelization in pylons shouldn't be necessary. After poring through Pylons' code and CKAN pylons app layer, I came across the streaming functionality right where I saw the break point between the WSGI handler and RegistryManager stack traces earlier. This led me to try disabling the streaming and without any additional changes things started working and stack traces began containing the entire execution tree from WSGI to our template code. | 2019-02-15T10:40:30 |
|
ckan/ckan | 4,661 | ckan__ckan-4661 | [
"4660"
] | 93ac068499a422c67bb90aed92ca071cb5061cc8 | diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py
--- a/ckanext/datastore/backend/postgres.py
+++ b/ckanext/datastore/backend/postgres.py
@@ -471,7 +471,10 @@ def _sort(sort, fields_types, rank_columns):
to order by best text search match
'''
if not sort:
- return rank_columns.values()
+ rank_sorting = []
+ for column in rank_columns.values():
+ rank_sorting.append(u'{0} DESC'.format(column))
+ return rank_sorting
clauses = datastore_helpers.get_list(sort, False)
| datastore_search returns most relevant records last
### CKAN Version if known (or site URL)
data.govt.nz
### Please describe the expected behaviour
When querying the `datastore_search` API method, we expected the most relevant results to be listed first. basically `ORDER BY rank DESC`
(relevant means that they closely march the search query)
When querying for "age concern" we expected results with this exact phrase to be first.
### Please describe the actual behaviour
the most relevant results are listed last. `ORDER BY rank `
results containing only "age" or only "concern" are in the first pages of results, and "age concern" is in the last pages.
### What steps can be taken to reproduce the issue?
http GET `{server}/datastore_search?distinct=true&plain=false&resource_id={resource}&q={keyword}&limit=10`;
e..g
https://catalogue.data.govt.nz/api/3/action/datastore_search?resource_id=35de6bf8-b254-4025-89f5-da9eb6adf9a0&q=age+concern&limit=10
results for "age" or "concern" are in the first pages.
results for "age concern" are in the last pages
| Wow, that's not good. Care to submit a PR? I think we just need a "DESC" after each value here https://github.com/ckan/ckan/blob/master/ckanext/datastore/backend/postgres.py#L474 and a quick test to prevent regressions | 2019-02-22T02:39:44 |
|
ckan/ckan | 4,669 | ckan__ckan-4669 | [
"4472"
] | 93ac068499a422c67bb90aed92ca071cb5061cc8 | diff --git a/ckan/controllers/package.py b/ckan/controllers/package.py
--- a/ckan/controllers/package.py
+++ b/ckan/controllers/package.py
@@ -393,14 +393,13 @@ def read(self, id):
# can the resources be previewed?
for resource in c.pkg_dict['resources']:
- # Backwards compatibility with preview interface
- resource['can_be_previewed'] = self._resource_preview(
- {'resource': resource, 'package': c.pkg_dict})
-
resource_views = get_action('resource_view_list')(
context, {'id': resource['id']})
resource['has_views'] = len(resource_views) > 0
+ # Backwards compatibility with preview interface
+ resource['can_be_previewed'] = bool(len(resource_views))
+
package_type = c.pkg_dict['type'] or 'dataset'
self._setup_template_variables(context, {'id': id},
package_type=package_type)
@@ -1116,13 +1115,12 @@ def resource_read(self, id, resource_id):
c.datastore_api = '%s/api/action' % \
config.get('ckan.site_url', '').rstrip('/')
- c.resource['can_be_previewed'] = self._resource_preview(
- {'resource': c.resource, 'package': c.package})
-
resource_views = get_action('resource_view_list')(
context, {'id': resource_id})
c.resource['has_views'] = len(resource_views) > 0
+ c.resource['can_be_previewed'] = bool(len(resource_views))
+
current_resource_view = None
view_id = request.GET.get('view_id')
if c.resource['can_be_previewed'] and not view_id:
| Function _resource_preview() in module ckan.controllers.package has been deprecated
### CKAN Version if known (or site URL)
2.7.2
> Function _resource_preview() in module ckan.controllers.package has been deprecated and will be removed in a later release of ckan. Resource preview is deprecated. Please use the new resource views
### What steps can be taken to reproduce the issue?
I used the plugin ngsiview and after Clicking on preview dataset. I observe the above message in my logs
So, what changes can i do for it?
| Hi @wardi, @torfsen can you please suggest in it?
The only place, CKAN itself uses result of `_resource_preview` is [here](https://github.com/ckan/ckan/blob/master/ckan/controllers/package.py#L1124). In new implementation(Flask blueprints), we are deciding, whether a resource can be previewed depending [on the amount of it's views](https://github.com/ckan/ckan/blob/master/ckan/views/resource.py#L83). If you are developer of extension or going to provide PR into source or just want to make local modifications - just use `bool(len_of_resource_views)` instead of `_resource_preview`. | 2019-03-04T14:39:45 |
|
ckan/ckan | 4,685 | ckan__ckan-4685 | [
"4684"
] | aa1442cdea0d414a314285151d265b7f719bed81 | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -2698,7 +2698,7 @@ def package_activity_list_html(context, data_dict):
:rtype: string
'''
- activity_stream = package_activity_list(context, data_dict)
+ activity_stream = logic.get_action('package_activity_list')(context, data_dict)
offset = int(data_dict.get('offset', 0))
extra_vars = {
'controller': 'package',
@@ -2729,7 +2729,7 @@ def group_activity_list_html(context, data_dict):
:rtype: string
'''
- activity_stream = group_activity_list(context, data_dict)
+ activity_stream = logic.get_action('group_activity_list')(context, data_dict)
offset = int(data_dict.get('offset', 0))
extra_vars = {
'controller': 'group',
@@ -2784,8 +2784,8 @@ def recently_changed_packages_activity_list_html(context, data_dict):
:rtype: string
'''
- activity_stream = recently_changed_packages_activity_list(
- context, data_dict)
+ activity_stream = logic.get_action(
+ 'recently_changed_packages_activity_list')(context, data_dict)
offset = int(data_dict.get('offset', 0))
extra_vars = {
'controller': 'package',
@@ -3344,7 +3344,7 @@ def dashboard_activity_list_html(context, data_dict):
:rtype: string
'''
- activity_stream = dashboard_activity_list(context, data_dict)
+ activity_stream = logic.get_action('dashboard_activity_list')(context, data_dict)
model = context['model']
user_id = context['user']
offset = data_dict.get('offset', 0)
| Activity stream actions not overridable
Some calls to action functions in `action/get.py` call the functions directly instead of using `get_action`, meaning they can't be overridden from extensions.
| Just noticed that after #4627 this is no longer relevant in master. I'll target 2.8 for this. | 2019-03-14T12:50:39 |
|
ckan/ckan | 4,711 | ckan__ckan-4711 | [
"4611",
"4623"
] | c87d021f382e669ea86d76922713e23af0133931 | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -474,11 +474,17 @@ def filter(self, log_record):
return True
mailhost = tuple(config.get('smtp.server', 'localhost').split(":"))
+ credentials = None
+ if config.get('smtp.user'):
+ credentials = (config.get('smtp.user'), config.get('smtp.password'))
+ secure = () if asbool(config.get('smtp.starttls')) else None
mail_handler = SMTPHandler(
mailhost=mailhost,
fromaddr=config.get('error_email_from'),
toaddrs=[config.get('email_to')],
- subject='Application Error'
+ subject='Application Error',
+ credentials=credentials,
+ secure=secure
)
mail_handler.setFormatter(logging.Formatter('''
| Error emails are not sent in flask routes
### CKAN Version if known (or site URL)
2.8, master
### Please describe the expected behaviour
When some route generates an error and error emails are configured, stacktrace and other info are expected to be mailed in specified email address.
### Please describe the actual behaviour
If the route is migrated to flask, the error email is never sent. Most likely due to the that mailing is based on pylons error middleware https://docs.pylonsproject.org/projects/pylons-webframework/en/latest/modules/middleware.html#pylons.middleware.ErrorHandler
### What steps can be taken to reproduce the issue?
Configure error emails.
Insert syntax error to route migrated to flask. For example view/user.py.
Error page is generated, email is not sent.
Add simple email error logger to flask
Fixes #4611
### Proposed fixes:
Adds simple email error logger to flask app. Uses the same config parameters as pylons did so no extra configuration is required.
In case of error, the email will contain the following example:
Time: 2019-01-17 13:06:18,548
URL: /user/admin
Method: GET
Headers: Cookie: Drupal.toolbar.collapsed=0; SSESS6b28b91ad717e967d3986b15c6c3ee12=ceSUx4deo_M3r5tAKe3wBmixI452mrREzjq-64VWu2I; ckan=d75907f3c439157af44e103541f8dfdee32519a494aa1e2d1a514a2e85f00abf48160a98
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Connection: close
Host: 10.10.10.10
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
X-Url-Scheme: https
Accept-Language: fi-FI,fi;q=0.9,en-GB;q=0.8,en;q=0.7,en-US;q=0.6
Accept-Encoding: gzip, deflate, br
Traceback (most recent call last):
File "/usr/lib/ckan/default/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/ckan/default/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/lib/ckan/default/src/ckan/ckan/views/user.py", line 131, in read
asd
NameError: global name 'asd' is not defined
### Features:
- [ ] includes tests covering changes
- [ ] includes updated documentation
- [ ] includes user-visible changes
- [ ] includes API changes
- [x] includes bugfix for possible backport
Please [X] all the boxes above that apply
| Yes, this was an internal Pylons feature so we lost it during the migration. It seems pretty easy to add an [email log handler](http://flask.pocoo.org/docs/1.0/logging/#email-errors-to-admins) that would replace this functionality. And perhaps there is an already existing Flask plugin that wraps this.
Marking as Good for Contribution in case @Zharktas or someone else wants to work on it.
:+1: Tested and merged | 2019-03-29T08:20:59 |
|
ckan/ckan | 4,717 | ckan__ckan-4717 | [
"4716"
] | 56d6a3fdb57eb3b08497f481316f95d77d2a00cb | diff --git a/ckan/controllers/group.py b/ckan/controllers/group.py
--- a/ckan/controllers/group.py
+++ b/ckan/controllers/group.py
@@ -220,6 +220,10 @@ def read(self, id, limit=20):
# Do not query for the group datasets when dictizing, as they will
# be ignored and get requested on the controller anyway
data_dict['include_datasets'] = False
+
+ # Do not query group members as they aren't used in the view
+ data_dict['include_users'] = False
+
c.group_dict = self._action('group_show')(context, data_dict)
c.group = context['group']
except (NotFound, NotAuthorized):
diff --git a/ckan/views/group.py b/ckan/views/group.py
--- a/ckan/views/group.py
+++ b/ckan/views/group.py
@@ -454,6 +454,10 @@ def read(group_type, is_organization, id=None, limit=20):
# Do not query for the group datasets when dictizing, as they will
# be ignored and get requested on the controller anyway
data_dict['include_datasets'] = False
+
+ # Do not query group members as they aren't used in the view
+ data_dict['include_users'] = False
+
group_dict = _action(u'group_show')(context, data_dict)
group = context['group']
except (NotFound, NotAuthorized):
| Slow group dictization when group has lots of members
### CKAN Version if known (or site URL)
2.8, master
### Please describe the expected behaviour
We have organization which has thousands of members (all accounts are automatically added there). group_dictize is expected to be fast even is there is lots of members.
### Please describe the actual behaviour
Group_show action, group read and member editing are all slow, some of them timeout before anything is rendered. group_dictize calls user_list_dictize https://github.com/ckan/ckan/blob/master/ckan/lib/dictization/model_dictize.py#L535 which loops over user_dictice.
### What steps can be taken to reproduce the issue?
Create organization, add thousands of members, try to access organization page.
| 2019-04-05T12:08:50 |
||
ckan/ckan | 4,750 | ckan__ckan-4750 | [
"4748"
] | 35fc5134edf7db1e90b261e48af71c6579f656e5 | diff --git a/ckan/lib/app_globals.py b/ckan/lib/app_globals.py
--- a/ckan/lib/app_globals.py
+++ b/ckan/lib/app_globals.py
@@ -47,7 +47,6 @@
'ckan.template_footer_end': {},
'ckan.dumps_url': {},
'ckan.dumps_format': {},
- 'ofs.impl': {'name': 'ofs_impl'},
'ckan.homepage_style': {'default': '1'},
# split string
diff --git a/ckan/lib/uploader.py b/ckan/lib/uploader.py
--- a/ckan/lib/uploader.py
+++ b/ckan/lib/uploader.py
@@ -79,20 +79,8 @@ def get_storage_path():
# None means it has not been set. False means not in config.
if _storage_path is None:
storage_path = config.get('ckan.storage_path')
- ofs_impl = config.get('ofs.impl')
- ofs_storage_dir = config.get('ofs.storage_dir')
if storage_path:
_storage_path = storage_path
- elif ofs_impl == 'pairtree' and ofs_storage_dir:
- log.warn('''Please use config option ckan.storage_path instead of
- ofs.storage_dir''')
- _storage_path = ofs_storage_dir
- return _storage_path
- elif ofs_impl:
- log.critical('''We only support local file storage form version 2.2
- of ckan please specify ckan.storage_path in your
- config for your uploads''')
- _storage_path = False
else:
log.critical('''Please specify a ckan.storage_path in your config
for your uploads''')
| Remove ofs and pairtree
As mentioned by @davidread in #4681. These are from a prehistoric version of the filestore and definitely not used anymore
| 2019-04-26T14:00:38 |
||
ckan/ckan | 4,752 | ckan__ckan-4752 | [
"4674"
] | 35fc5134edf7db1e90b261e48af71c6579f656e5 | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -189,7 +189,7 @@ def redirect_to(*args, **kw):
_url = ''
skip_url_parsing = False
parse_url = kw.pop('parse_url', False)
- if uargs and len(uargs) is 1 and isinstance(uargs[0], string_types) \
+ if uargs and len(uargs) == 1 and isinstance(uargs[0], string_types) \
and (uargs[0].startswith('/') or is_url(uargs[0])) \
and parse_url is False:
skip_url_parsing = True
diff --git a/ckan/plugins/toolkit.py b/ckan/plugins/toolkit.py
--- a/ckan/plugins/toolkit.py
+++ b/ckan/plugins/toolkit.py
@@ -475,7 +475,7 @@ def _get_endpoint(cls):
# there are some routes('hello_world') that are not using blueprint
# For such case, let's assume that view function is a controller
# itself and action is None.
- if len(endpoint) is 1:
+ if len(endpoint) == 1:
return endpoint + (None,)
return endpoint
| diff --git a/ckan/tests/legacy/functional/test_pagination.py b/ckan/tests/legacy/functional/test_pagination.py
--- a/ckan/tests/legacy/functional/test_pagination.py
+++ b/ckan/tests/legacy/functional/test_pagination.py
@@ -10,7 +10,7 @@
def scrape_search_results(response, object_type):
assert object_type in ('dataset', 'group_dataset', 'group', 'user')
- if object_type is not 'group_dataset':
+ if object_type != 'group_dataset':
results = re.findall('a href="/%s/%s_(\d\d)' % (object_type, object_type),
str(response))
else:
diff --git a/ckan/tests/legacy/logic/test_action.py b/ckan/tests/legacy/logic/test_action.py
--- a/ckan/tests/legacy/logic/test_action.py
+++ b/ckan/tests/legacy/logic/test_action.py
@@ -702,7 +702,7 @@ def test_42_resource_search_test_percentage_is_escaped(self):
# There shouldn't be any results. If the '%' character wasn't
# escaped correctly, then the search would match because of the
# unescaped wildcard.
- assert count is 0
+ assert count == 0
def test_42_resource_search_fields_parameter_still_accepted(self):
'''The fields parameter is deprecated, but check it still works.
| use ==/!= to compare str, bytes, and int literals
[flake8](http://flake8.pycqa.org) testing of https://github.com/ckan/ckan on Python 3.7.1
$ __flake8 . --count --select=E9,F63,F72,F82 --show-source --statistics__
```
./ckan/lib/helpers.py:192:18: F632 use ==/!= to compare str, bytes, and int literals
if uargs and len(uargs) is 1 and isinstance(uargs[0], string_types) \
^
./ckan/plugins/toolkit.py:478:12: F632 use ==/!= to compare str, bytes, and int literals
if len(endpoint) is 1:
^
./ckan/tests/legacy/logic/test_action.py:705:16: F632 use ==/!= to compare str, bytes, and int literals
assert count is 0
^
./ckan/tests/legacy/functional/test_pagination.py:13:8: F632 use ==/!= to compare str, bytes, and int literals
if object_type is not 'group_dataset':
^
4 F632 use ==/!= to compare str, bytes, and int literals
4
```
| :+1: to this and using flake8 generally
@cclauss sounds good, want to submit a PR? | 2019-04-26T19:02:08 |
ckan/ckan | 4,780 | ckan__ckan-4780 | [
"4779"
] | bcf1271470ec57833eac92fe843a5a5141529833 | diff --git a/ckan/config/environment.py b/ckan/config/environment.py
--- a/ckan/config/environment.py
+++ b/ckan/config/environment.py
@@ -76,14 +76,14 @@ def find_controller(self, controller):
# Pylons paths
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- valid_base_public_folder_names = ['public', 'public-bs2']
+ valid_base_public_folder_names = ['public']
static_files = app_conf.get('ckan.base_public_folder', 'public')
app_conf['ckan.base_public_folder'] = static_files
if static_files not in valid_base_public_folder_names:
raise CkanConfigurationException(
'You provided an invalid value for ckan.base_public_folder. '
- 'Possible values are: "public" and "public-bs2".'
+ 'Possible values are: "public".'
)
log.info('Loading static files from %s' % static_files)
@@ -248,14 +248,14 @@ def update_config():
config['pylons.h'] = helpers.helper_functions
# Templates and CSS loading from configuration
- valid_base_templates_folder_names = ['templates', 'templates-bs2']
+ valid_base_templates_folder_names = ['templates']
templates = config.get('ckan.base_templates_folder', 'templates')
config['ckan.base_templates_folder'] = templates
if templates not in valid_base_templates_folder_names:
raise CkanConfigurationException(
'You provided an invalid value for ckan.base_templates_folder. '
- 'Possible values are: "templates" and "templates-bs2".'
+ 'Possible values are: "templates".'
)
jinja2_templates_path = os.path.join(root, templates)
diff --git a/ckan/templates-bs2/revision/__init__.py b/ckan/templates-bs2/revision/__init__.py
deleted file mode 100644
--- a/ckan/templates-bs2/revision/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# encoding: utf-8
-
-# empty file needed for pylons to find templates in this directory
| diff --git a/ckan/public-bs2/base/test/index.html b/ckan/public-bs2/base/test/index.html
deleted file mode 100644
--- a/ckan/public-bs2/base/test/index.html
+++ /dev/null
@@ -1,169 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <meta charset="utf-8" />
- <title>Mocha Tests</title>
- <link rel="stylesheet" href="vendor/mocha.css" />
- </head>
- <body>
- <div id="mocha"></div>
- <div id="fixture" style="position: absolute; top: -9999px; left: -9999px"></div>
-
- <!-- Test Runner -->
- <script src="./vendor/sinon.js"></script>
- <script src="./vendor/mocha.js"></script>
- <script src="./vendor/chai.js"></script>
- <script>
- mocha.setup('bdd');
- var assert = chai.assert;
-
- // Export sinon.assert methods onto assert.
- sinon.assert.expose(assert, {prefix: ''});
-
- var ckan = {ENV: 'testing'};
- </script>
-
- <!-- Source -->
- <script src="../vendor/jed.js"></script>
- <script src="../vendor/jquery.js"></script>
- <script src="../vendor/bootstrap/js/bootstrap.js"></script>
- <script src="../javascript/plugins/jquery.inherit.js"></script>
- <script src="../javascript/plugins/jquery.proxy-all.js"></script>
- <script src="../javascript/plugins/jquery.url-helpers.js"></script>
- <script src="../javascript/plugins/jquery.date-helpers.js"></script>
- <script src="../javascript/plugins/jquery.slug.js"></script>
- <script src="../javascript/plugins/jquery.slug-preview.js"></script>
- <script src="../javascript/plugins/jquery.form-warning.js"></script>
- <script src="../javascript/sandbox.js"></script>
- <script src="../javascript/module.js"></script>
- <script src="../javascript/pubsub.js"></script>
- <script src="../javascript/client.js"></script>
- <script src="../javascript/notify.js"></script>
- <script src="../javascript/i18n.js"></script>
- <script src="../javascript/main.js"></script>
- <script src="../javascript/view-filters.js"></script>
- <script src="../javascript/modules/basic-form.js"></script>
- <script src="../javascript/modules/autocomplete.js"></script>
- <script src="../javascript/modules/resource-form.js"></script>
- <script src="../javascript/modules/resource-upload-field.js"></script>
- <script src="../javascript/modules/image-upload.js"></script>
- <script src="../javascript/modules/confirm-action.js"></script>
- <script src="../javascript/modules/custom-fields.js"></script>
- <script src="../javascript/modules/followers-counter.js"></script>
-
- <!-- Suite -->
- <script src="./spec/ckan.spec.js"></script>
- <script src="./spec/i18n.spec.js"></script>
- <script src="./spec/module.spec.js"></script>
- <script src="./spec/sandbox.spec.js"></script>
- <script src="./spec/client.spec.js"></script>
- <script src="./spec/pubsub.spec.js"></script>
- <script src="./spec/notify.spec.js"></script>
- <script src="./spec/view-filters.spec.js"></script>
- <script src="./spec/modules/resource-form.spec.js"></script>
- <script src="./spec/modules/resource-upload-field.spec.js"></script>
- <script src="./spec/modules/image-upload.spec.js"></script>
- <script src="./spec/modules/confirm-action.spec.js"></script>
- <script src="./spec/modules/basic-form.spec.js"></script>
- <script src="./spec/modules/autocomplete.spec.js"></script>
- <script src="./spec/modules/custom-fields.spec.js"></script>
- <script src="./spec/modules/followers-counter.spec.js"></script>
- <script src="./spec/plugins/jquery.inherit.spec.js"></script>
- <script src="./spec/plugins/jquery.proxy-all.spec.js"></script>
- <script src="./spec/plugins/jquery.url-helpers.spec.js"></script>
- <script src="./spec/plugins/jquery.date-helpers.spec.js"></script>
- <script src="./spec/plugins/jquery.slug.spec.js"></script>
- <script src="./spec/plugins/jquery.slug-preview.spec.js"></script>
- <script src="./spec/plugins/jquery.form-warning.spec.js"></script>
-
- <script>
- /* Helper function for loading snippets from the ajax_snippets directory.
- * The filename should be provided and an optional object of query
- * string parameters. The returned snippet will be loaded into the
- * fixture and passed to any callback.
- *
- * The callback shares the same scope as the rest of the suite so you
- * can assign test variables easily. It is passed the loaded HTML string
- * and the fixture element.
- *
- * filename - The snippet filename to load.
- * params - An optional object of query string params.
- * callback - An optional callback to call when loaded.
- *
- * Example:
- *
- * // To simply load a fixture.
- * beforeEach(function (done) {
- * this.loadFixture('my-snippet', done);
- * });
- *
- * // To get the html itself.
- * beforeEach(function (done) {
- * this.loadFixture('my-snippet', function (html) {
- * this.template = html;
- * done();
- * });
- * });
- *
- */
- function loadFixture(filename, params, callback) {
- var context = this;
-
- // Allow function to be called without params.
- if (typeof params === 'function') {
- callback = params;
- params = {};
- }
-
- return (new ckan.Client()).getTemplate(filename, params).fail(function () {
- throw new Error('Unable to load fixture: ' + filename);
- }).pipe(function (template) {
- var fixture = jQuery('#fixture').html(template);
- callback && callback.call(context, template, fixture);
- return template;
- });
- }
-
- before(function () {
- // Assign the loadFixture helper. Callbacks will have the same scope
- // as the before() functions.
- this.loadFixture = jQuery.proxy(loadFixture, this);
- });
-
- beforeEach(function () {
- this.fixture = jQuery('#fixture').empty();
- });
-
- afterEach(function () {
- this.fixture.empty();
- });
-
-
- // Add dummy translations for testing i18n
- ckan.i18n.load({
- '': {
- "domain": "ckan",
- "lang": "en",
- "plural_forms": "nplurals=2; plural=(n != 1);"
- },
- 'foo': [null, 'FOO'],
- 'hello %(name)s!': [null, 'HELLO %(name)s!'],
- 'bar': ['bars', 'BAR', 'BARS'],
- '%(color)s shirt': [
- '%(color)s shirts',
- '%(color)s SHIRT',
- '%(color)s SHIRTS'
- ],
- '%(num)d item': ['%(num)d items', '%(num)d ITEM', '%(num)d ITEMS']
- });
-
-
- if (window.mochaPhantomJS) {
- mochaPhantomJS.run();
- } else {
- mocha.run();
- }
-
- </script>
- </body>
-</html>
diff --git a/ckan/public-bs2/base/test/primer/index.html b/ckan/public-bs2/base/test/primer/index.html
deleted file mode 100644
--- a/ckan/public-bs2/base/test/primer/index.html
+++ /dev/null
@@ -1,647 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="utf-8" />
- <title>CKAN Primer</title>
- <link rel="stylesheet/less" href="../../less/main.less">
- <script src="../vendor/less.js"></script>
- <style>
- .primer-wrapper {
- padding: 20px;
- }
-
- .primer-heading {
- margin-bottom: 20px;
- }
-
- .primer-spacer {
- height: 20px;
- }
- </style>
- </head>
- <body>
- <div class="primer-wrapper">
- <h1 class="primer-heading">CKAN CSS Primer</h1>
- <section class="module">
- <p class="content">This is an empty module</p>
- </section>
- <section class="module">
- <h2 class="heading">Module Heading</h2>
- <div class="content">
- <p>This is an example module with a heading and stuff</p>
- </div>
- </section>
- <section class="module">
- <h2 class="heading">Module Heading</h2>
- <ul class="nav nav-simple">
- <li><a href="#">Navigation Item 1</a></li>
- <li><a href="#">Navigation Item 2</a></li>
- <li><a href="#">Navigation Item 3</a></li>
- </ul>
- </section>
- <section class="module">
- <h2 class="heading">Module Heading</h2>
- <ul class="nav nav-simple">
- <li><a href="#">Navigation Item 1</a></li>
- <li class="selected"><a href="#">Selected Item 2</a></li>
- <li><a href="#">Navigation Item 3</a></li>
- </ul>
- <p class="footer"><a href="#">View all</a></p>
- </section>
- <section class="module">
- <h2 class="heading">General Prose</h2>
- <div class="content">
- <h2>Sections <a href="#">Linked</a></h2>
- <p>The main page header of this guide is an <code>h1</code> element. Any header elements may include links, as depicted in the example.</p>
- <p>The secondary header above is an <code>h2</code> element, which may be used for any form of important page-level header. More than one may be used per page. Consider using an <code>h2</code> unless you need a header level of less importance, or as a sub-header to an existing <code>h2</code> element.</p>
- <h3>Third-Level Header <a href="#">Linked</a></h3>
- <p>The header above is an <code>h3</code> element, which may be used for any form of page-level header which falls below the <code>h2</code> header in a document hierarchy.</p>
- <h4>Fourth-Level Header <a href="#">Linked</a></h4>
- <p>The header above is an <code>h4</code> element, which may be used for any form of page-level header which falls below the <code>h3</code> header in a document hierarchy.</p>
- <h5>Fifth-Level Header <a href="#">Linked</a></h5>
- <p>The header above is an <code>h5</code> element, which may be used for any form of page-level header which falls below the <code>h4</code> header in a document hierarchy.</p>
- <h6>Sixth-Level Header <a href="#">Linked</a></h6>
- <p>The header above is an <code>h6</code> element, which may be used for any form of page-level header which falls below the <code>h5</code> header in a document hierarchy.</p>
-
- <h2 id="grouping" class="heading">Grouping content</h2>
- <h3>Paragraphs</h3>
- <p>All paragraphs are wrapped in <code>p</code> tags. Additionally, <code>p</code> elements can be wrapped with a <code>blockquote</code> element <em>if the <code>p</code> element is indeed a quote</em>. Historically, <code>blockquote</code> has been used purely to force indents, but this is now achieved using CSS. Reserve <code>blockquote</code> for quotes.</p>
-
- <h3>Horizontal rule</h3>
- <p>The <code>hr</code> element represents a paragraph-level thematic break, e.g. a scene change in a story, or a transition to another topic within a section of a reference book. The following extract from <cite>Pandora’s Star</cite> by Peter F. Hamilton shows two paragraphs that precede a scene change and the paragraph that follows it:</p>
- <div class="example">
- <p>Dudley was ninety-two, in his second life, and fast approaching time for another rejuvenation. Despite his body having the physical age of a standard fifty-year-old, the prospect of a long degrading campaign within academia was one he regarded with dread. For a supposedly advanced civilization, the Intersolar Commonwearth could be appallingly backward at times, not to mention cruel.</p>
- <p><i>Maybe it won’t be that bad</i>, he told himself. The lie was comforting enough to get him through the rest of the night’s shift.</p>
- <hr/>
- <p>The Carlton AllLander drove Dudley home just after dawn. Like the astronomer, the vehicle was old and worn, but perfectly capable of doing its job. It had a cheap diesel engine, common enough on a semi-frontier world like Gralmond, although its drive array was a thoroughly modern photoneural processor. With its high suspension and deep-tread tyres it could plough along the dirt track to the observatory in all weather and seasons, including the metre-deep snow of Gralmond’s winters.</p>
- </div>
-
- <h3>Pre-formatted text</h3>
- <p>The <code>pre</code> element represents a block of pre-formatted text, in which structure is represented by typographic conventions rather than by elements. Such examples are an e-mail (with paragraphs indicated by blank lines, lists indicated by lines prefixed with a bullet), fragments of computer code (with structure indicated according to the conventions of that language) or displaying <abbr title="American Standard Code for Information Interchange">ASCII</abbr> art. Here’s an example showing the printable characters of <abbr>ASCII</abbr>:</p>
- <div class="example">
-<pre><samp> ! " # $ % & ' ( ) * + , - . /
- 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
- @ A B C D E F G H I J K L M N O
- P Q R S T U V W X Y Z [ \ ] ^ _
- ` a b c d e f g h i j k l m n o
- p q r s t u v w x y z { | } ~ </samp></pre>
- </div>
-
- <h3>Blockquotes</h3>
- <p>The <code>blockquote</code> element represents a section that is being quoted from another source.</p>
- <div class="example">
- <blockquote cite="http://hansard.millbanksystems.com/commons/1947/nov/11/parliament-bill#column_206">
- <p>Many forms of Government have been tried, and will be tried in this world of sin and woe. No one pretends that democracy is perfect or all-wise. Indeed, it has been said that democracy is the worst form of government except all those other forms that have been tried from time to time.</p>
- </blockquote>
- <p>Winston Churchill, in <cite><a href="http://hansard.millbanksystems.com/commons/1947/nov/11/parliament-bill#column_206">a speech to the House of Commons</a></cite>. 11th November 1947</p>
- </div>
- <p>Additionally, you might wish to cite the source, as in the above example. The correct method involves including the <code>cite</code> attribute on the <code>blockquote</code> element, but since no browser makes any use of that information, it’s useful to link to the source also.</p>
-
- <h3>Ordered list</h3>
- <p>The <code>ol</code> element denotes an ordered list, and various numbering schemes are available through the CSS (including 1,2,3… a,b,c… i,ii,iii… and so on). Each item requires a surrounding <code><li></code> and <code></li></code> tag, to denote individual items within the list (as you may have guessed, <code>li</code> stands for list item).</p>
- <div class="example">
- <ol>
- <li>This is an ordered list.</li>
- <li>
- This is the second item, which contains a sub list
- <ol>
- <li>This is the sub list, which is also ordered.</li>
- <li>It has two items.</li>
- </ol>
- </li>
- <li>This is the final item on this list.</li>
- </ol>
- </div>
-
- <h3>Unordered list</h3>
- <p>The <code>ul</code> element denotes an unordered list (ie. a list of loose items that don’t require numbering, or a bulleted list). Again, each item requires a surrounding <code><li></code> and <code></li></code> tag, to denote individual items. Here is an example list showing the constituent parts of the British Isles:</p>
- <div class="example">
- <ul>
- <li>
- United Kingdom of Great Britain and Northern Ireland:
- <ul>
- <li>England</li>
- <li>Scotland</li>
- <li>Wales</li>
- <li>Northern Ireland</li>
- </ul>
- </li>
- <li>Republic of Ireland</li>
- <li>Isle of Man</li>
- <li>
- Channel Islands:
- <ul>
- <li>Bailiwick of Guernsey</li>
- <li>Bailiwick of Jersey</li>
- </ul>
- </li>
- </ul>
- </div>
- <p>Sometimes we may want each list item to contain block elements, typically a paragraph or two.</p>
- <div class="example">
- <ul>
- <li>
- <p>The British Isles is an archipelago consisting of the two large islands of Great Britain and Ireland, and many smaller surrounding islands.</p>
- </li>
- <li>
- <p>Great Britain is the largest island of the archipelago. Ireland is the second largest island of the archipelago and lies directly to the west of Great Britain.</p>
- </li>
- <li>
- <p>The full list of islands in the British Isles includes over 1,000 islands, of which 51 have an area larger than 20 km<sup>2</sup>.</p>
- </li>
- </ul>
- </div>
-
- <h3>Definition list</h3>
- <p>The <code>dl</code> element is for another type of list called a definition list. Instead of list items, the content of a <code>dl</code> consists of <code>dt</code> (Definition Term) and <code>dd</code> (Definition description) pairs. Though it may be called a “definition list”, <code>dl</code> can apply to other scenarios where a parent/child relationship is applicable. For example, it may be used for marking up dialogues, with each <code>dt</code> naming a speaker, and each <code>dd</code> containing his or her words.</p>
- <div class="example">
- <dl>
- <dt>This is a term.</dt>
- <dd>This is the definition of that term, which both live in a <code>dl</code>.</dd>
- <dt>Here is another term.</dt>
- <dd>And it gets a definition too, which is this line.</dd>
- <dt>Here is term that shares a definition with the term below.</dt>
- <dt>Here is a defined term.</dt>
- <dd><code>dt</code> terms may stand on their own without an accompanying <code>dd</code>, but in that case they <em>share</em> descriptions with the next available <code>dt</code>. You may not have a <code>dd</code> without a parent <code>dt</code>.</dd>
- </dl>
- </div>
-
- <h3>Figures</h3>
- <p>Figures are usually used to refer to images:</p>
- <div class="example">
- <figure>
- <img src="http://lorempixum.com/680/400/abstract/?r" alt="Example image"/>
- <figcaption>
- <p>This is a placeholder image, with supporting caption.</p>
- </figcaption>
- </figure>
- </div>
- <p>Here, a part of a poem is marked up using figure:</p>
- <div class="example">
- <figure>
- <p>‘Twas brillig, and the slithy toves<br/>
- Did gyre and gimble in the wabe;<br/>
- All mimsy were the borogoves,<br/>
- And the mome raths outgrabe.</p>
- <figcaption>
- <p><cite>Jabberwocky</cite> (first verse). Lewis Carroll, 1832-98</p>
- </figcaption>
- </figure>
- </div>
-
- <h2 id="text" class="heading">Text-level Semantics</h2>
- <p>There are a number of inline <abbr title="HyperText Markup Language">HTML</abbr> elements you may use anywhere within other elements.</p>
-
- <h3>Links and anchors</h3>
- <p>The <code>a</code> element is used to hyperlink text, be that to another page, a named fragment on the current page or any other location on the web. Example:</p>
- <div class="example">
- <p><a href="/">Go to the home page</a> or <a href="#banner">return to the top of this page</a>.</p>
- </div>
-
- <h3>Stressed emphasis</h3>
- <p>The <code>em</code> element is used to denote text with stressed emphasis, i.e., something you’d pronounce differently. Where italicizing is required for stylistic differentiation, the <code>i</code> element may be preferable. Example:</p>
- <div class="example">
- <p>You simply <em>must</em> try the negitoro maki!</p>
- </div>
-
- <h3>Strong importance</h3>
- <p>The <code>strong</code> element is used to denote text with strong importance. Where bolding is used for stylistic differentiation, the <code>b</code> element may be preferable. Example:</p>
- <div class="example">
- <p><strong>Don’t</strong> stick nails in the electrical outlet.</p>
- </div>
-
- <h3>Small print</h3>
- <p>The <small>small</small> element is used to represent disclaimers, caveats, legal restrictions, or copyrights (commonly referred to as ‘small print’). It can also be used for attributions or satisfying licensing requirements. Example:</p>
- <div class="example">
- <p><small>Copyright © 1922-2011 Acme Corporation. All Rights Reserved.</small></p>
- </div>
-
- <h3>Strikethrough</h3>
- <p>The <code>s</code> element is used to represent content that is no longer accurate or relevant. When indicating document edits i.e., marking a span of text as having been removed from a document, use the <code>del</code> element instead. Example:</p>
- <div class="example">
- <p><s>Recommended retail price: £3.99 per bottle</s><br/><strong>Now selling for just £2.99 a bottle!</strong></p>
- </div>
-
- <h3>Citations</h3>
- <p>The <code>cite</code> element is used to represent the title of a work (e.g. a book, essay, poem, song, film, TV show, sculpture, painting, musical, exhibition, etc). This can be a work that is being quoted or referenced in detail (i.e. a citation), or it can just be a work that is mentioned in passing. Example:</p>
- <div class="example">
- <p><cite>Universal Declaration of Human Rights</cite>, United Nations, December 1948. Adopted by General Assembly resolution 217 A (III).</p>
- </div>
-
- <h3>Inline quotes</h3>
- <p>The <code>q</code> element is used for quoting text inline. Example showing nested quotations:</p>
- <div class="example">
- <p>John said, <q>I saw Lucy at lunch, she told me <q>Mary wants you to get some ice cream on your way home</q>. I think I will get some at Ben and Jerry’s, on Gloucester Road.</q></p>
- </div>
-
- <h3>Definition</h3>
- <p>The <code>dfn</code> element is used to highlight the first use of a term. The <code>title</code> attribute can be used to describe the term. Example:</p>
- <div class="example">
- <p>Bob’s <dfn title="Dog">canine</dfn> mother and <dfn title="Horse">equine</dfn> father sat him down and carefully explained that he was an <dfn title="A mutation that combines two or more sets of chromosomes from different species">allopolyploid</dfn> organism.</p>
- </div>
-
- <h3>Abbreviation</h3>
- <p>The <code>abbr</code> element is used for any abbreviated text, whether it be acronym, initialism, or otherwise. Generally, it’s less work and useful (enough) to mark up only the first occurrence of any particular abbreviation on a page, and ignore the rest. Any text in the <code>title</code> attribute will appear when the user’s mouse hovers the abbreviation (although notably, this does not work in Internet Explorer for Windows). Example abbreviations:</p>
- <div class="example">
- <p><abbr title="British Broadcasting Corportation">BBC</abbr>, <abbr title="HyperText Markup Language">HTML</abbr>, and <abbr title="Staffordshire">Staffs.</abbr></p>
- </div>
-
- <h3>Time</h3>
- <p>The <code>time</code> element is used to represent either a time on a 24 hour clock, or a precise date in the proleptic Gregorian calendar, optionally with a time and a time-zone offset. Example:</p>
- <div class="example">
- <p>Queen Elizabeth II was proclaimed sovereign of each of the Commonwealth realms on <time datetime="1952-02-6">6</time> and <time datetime="1952-02-7">7 February 1952</time>, after the death of her father, King George VI.</p>
- </div>
-
- <h3>Code</h3>
- <p>The <code>code</code> element is used to represent fragments of computer code. Useful for technology-oriented sites, not so useful otherwise. Example:</p>
- <div class="example">
- <p>When you call the <code>activate()</code> method on the <code>robotSnowman</code> object, the eyes glow.</p>
- </div>
- <p>Used in conjunction with the <code>pre</code> element:</p>
- <div class="example">
- <pre><code>function getJelly() {
-     echo $aDeliciousSnack;
- }</code></pre>
- </div>
-
- <h3>Variable</h3>
- <p>The <code>var</code> element is used to denote a variable in a mathematical expression or programming context, but can also be used to indicate a placeholder where the contents should be replaced with your own value. Example:</p>
- <div class="example">
- <p>If there are <var>n</var> pipes leading to the ice cream factory then I expect at <em>least</em> <var>n</var> flavours of ice cream to be available for purchase!</p>
- </div>
-
- <h3>Sample output</h3>
- <p>The <code>samp</code> element is used to represent (sample) output from a program or computing system. Useful for technology-oriented sites, not so useful otherwise. Example:</p>
- <div class="example">
- <p>The computer said <samp>Too much cheese in tray two</samp> but I didn’t know what that meant.</p>
- </div>
-
- <h3>Keyboard entry</h3>
- <p>The <code>kbd</code> element is used to denote user input (typically via a keyboard, although it may also be used to represent other input methods, such as voice commands). Example:<p>
- <div class="example">
- <p>To take a screenshot on your Mac, press <kbd>⌘ Cmd</kbd> + <kbd>⇧ Shift</kbd> + <kbd>3</kbd>.</p>
- </div>
-
- <h3>Superscript and subscript text</h3>
- <p>The <code>sup</code> element represents a superscript and the sub element represents a <code>sub</code>. These elements must be used only to mark up typographical conventions with specific meanings, not for typographical presentation. As a guide, only use these elements if their absence would change the meaning of the content. Example:</p>
- <div class="example">
- <p>The coordinate of the <var>i</var>th point is (<var>x<sub><var>i</var></sub></var>, <var>y<sub><var>i</var></sub></var>). For example, the 10th point has coordinate (<var>x<sub>10</sub></var>, <var>y<sub>10</sub></var>).</p>
- <p>f(<var>x</var>, <var>n</var>) = log<sub>4</sub><var>x</var><sup><var>n</var></sup></p>
- </div>
-
- <h3>Italicised</h3>
- <p>The <code>i</code> element is used for text in an alternate voice or mood, or otherwise offset from the normal prose. Examples include taxonomic designations, technical terms, idiomatic phrases from another language, the name of a ship or other spans of text whose typographic presentation is typically italicised. Example:</p>
- <div class="example">
- <p>There is a certain <i lang="fr">je ne sais quoi</i> in the air.</p>
- </div>
-
- <h3>Emboldened</h3>
- <p>The <code>b</code> element is used for text stylistically offset from normal prose without conveying extra importance, such as key words in a document abstract, product names in a review, or other spans of text whose typographic presentation is typically emboldened. Example:</p>
- <div class="example">
- <p>You enter a small room. Your <b>sword</b> glows brighter. A <b>rat</b> scurries past the corner wall.</p>
- </div>
-
- <h3>Marked or highlighted text</h3>
- <p>The <code>mark</code> element is used to represent a run of text marked or highlighted for reference purposes. When used in a quotation it indicates a highlight not originally present but added to bring the reader’s attention to that part of the text. When used in the main prose of a document, it indicates a part of the document that has been highlighted due to its relevance to the user’s current activity. Example:</p>
- <div class="example">
- <p>I also have some <mark>kitten</mark>s who are visiting me these days. They’re really cute. I think they like my garden! Maybe I should adopt a <mark>kitten</mark>.</p>
- </div>
-
- <h3 id="edits">Edits</h3>
- <p>The <code>del</code> element is used to represent deleted or retracted text which still must remain on the page for some reason. Meanwhile its counterpart, the <code>ins</code> element, is used to represent inserted text. Both <code>del</code> and <code>ins</code> have a <code>datetime</code> attribute which allows you to include a timestamp directly in the element. Example inserted text and usage:</p>
- <div class="example">
- <p>She bought <del datetime="2005-05-30T13:00:00">two</del> <ins datetime="2005-05-30T13:00:00">five</ins> pairs of shoes.</p>
- </div>
-
- <h2 id="tables" class="heading">Tabular data</h2>
- <p>Tables should be used when displaying tabular data. The <code>thead</code>, <code>tfoot</code> and <code>tbody</code> elements enable you to group rows within each a table.</p>
- <p>If you use these elements, you must use every element. They should appear in this order: <code>thead</code>, <code>tfoot</code> and <code>tbody</code>, so that browsers can render the foot before receiving all the data. You must use these tags within the table element.</p>
- <div class="example">
- <table>
- <caption>The Very Best Eggnog</caption>
- <colgroup>
- <col style="width:50%" />
- <col style="width:25%" />
- <col style="width:25%" />
- </colgroup>
- <thead>
- <tr>
- <th scope="col">Ingredients</th>
- <th scope="col">Serves 12</th>
- <th scope="col">Serves 24</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>Milk</td>
- <td>1 quart</td>
- <td>2 quart</td>
- </tr>
- <tr>
- <td>Cinnamon Sticks</td>
- <td>2</td>
- <td>1</td>
- </tr>
- <tr>
- <td>Vanilla Bean, Split</td>
- <td>1</td>
- <td>2</td>
- </tr>
- <tr>
- <td>Cloves</td>
- <td>5</td>
- <td>10</td>
- </tr>
- <tr>
- <td>Mace</td>
- <td>10 blades</td>
- <td>20 blades</td>
- </tr>
- <tr>
- <td>Egg Yolks</td>
- <td>12</td>
- <td>24</td>
- </tr>
- <tr>
- <td>Cups Sugar</td>
- <td>1 ½ cups</td>
- <td>3 cups</td>
- </tr>
- <tr>
- <td>Dark Rum</td>
- <td>1 ½ cups</td>
- <td>3 cups</td>
- </tr>
- <tr>
- <td>Brandy</td>
- <td>1 ½ cups</td>
- <td>3 cups</td>
- </tr>
- <tr>
- <td>Vanilla</td>
- <td>1 tbsp</td>
- <td>2 tbsp</td>
- </tr>
- <tr>
- <td>Half-and-half or Light Cream</td>
- <td>1 quart</td>
- <td>2 quart</td>
- </tr>
- <tr>
- <td>Freshly grated nutmeg to taste</td>
- <td></td>
- <td></td>
- </tr>
- </tbody>
- </table>
- </div>
-
- <h2 id="forms" class="heading">Forms</h2>
- <p>Forms can be used when you wish to collect data from users. The <code>fieldset</code> element enables you to group related fields within a form, and each one should contain a corresponding <code>legend</code>. The <code>label</code> element ensures field descriptions are associated with their corresponding form widgets.</p>
- <div class="example">
- <form action="#">
- <fieldset>
- <legend>Legend</legend>
- <div class="control-group">
- <label for="text">Text Input <abbr title="Required">*</abbr></label>
- <input id="text" class="text" type="text"/>
- <span class="help-inline">Note about this field</span>
- </div class="control-group">
- <div>
- <label for="password">Password</label>
- <input id="password" class="text" type="password"/>
- <span class="help-inline">Note about this field</span>
- </div class="control-group">
- <div>
- <label for="password">Web Address</label>
- <input id="password" class="text" type="url"/>
- <span class="help-inline">Note about this field</span>
- </div class="control-group">
- <div class="control-group">
- <label for="password">Email Address</label>
- <input id="password" class="text" type="email"/>
- <span class="help-inline">Note about this field</span>
- </div>
- <div class="control-group">
- <label for="textarea">Textarea</label>
- <textarea id="textarea" class="text" rows="8" cols="48"></textarea>
- <span class="help-inline">Note about this field</span>
- </div>
- <div class="control-group">
- <label for="checkbox">Single Checkbox</label>
- <label for="checkbox" class="checkbox"><input id="checkbox" type="checkbox" class="checkbox"/> Label</label>
- </div>
- <div class="control-group">
- <label for="select">Select</label>
- <select id="select">
- <optgroup label="Option Group">
- <option>Option One</option>
- <option>Option Two</option>
- <option>Option Three</option>
- </optgroup>
- </select>
- <span class="help-inline">Note about this selection</span>
- </div>
- <fieldset class="control-group">
- <legend>Checkbox <abbr title="Required">*</abbr></legend>
- <div class="control-group">
- <label for="checkbox1" class="checkbox"><input id="checkbox1" name="checkbox" type="checkbox" checked="checked" /> Choice A</label>
- <label for="checkbox2" class="checkbox"><input id="checkbox2" name="checkbox" type="checkbox" /> Choice B</label>
- <label for="checkbox3" class="checkbox"><input id="checkbox3" name="checkbox" type="checkbox" /> Choice C</label>
- </div>
- </fieldset>
- <fieldset class="control-group">
- <div class="control-group">
- <legend>Radio</legend>
- <label for="radio1" class="radio"><input id="radio1" name="radio" type="radio" class="radio" checked="checked" /> Option 1</label>
- </div>
- </fieldset>
- <div class="form-actions">
- <input type="submit" class="btn btn-primary" value="Post Comment" />
- <input type="button" class="btn" value="Preview" />
- </div>
- </fieldset>
- </form>
- </div>
-
- <p><small>This block is copyright © 2012 Paul Robert Lloyd. Code covered by the <a rel="license" href="http://paulrobertlloyd.mit-license.org/">MIT license</a>.</small></p>
- </div>
- </section>
- <h1>Dataset Results</h1>
- <section class="module">
- <div class="content">
- <ul class="dataset-list unstyled">
- <li class="dataset-item">
- <h2 class="heading"><a href="#">Counselling in London Central, Camden</a></h2>
- <ul class="dataset-resources unstyled">
- <li><a href="#" class="label">HTML</a></li>
- <li><a href="#" class="label">XML</a></li>
- <li><a href="#" class="label">CSV</a></li>
- </ul>
- <div class="content">
- <p>This is an application programming interface (API) that opens up
- core EU legislative data for further use. The interface uses JSON,
- meaning that you have easy to use machine-readable access to
- metadata on European Union legislation.</p>
- <p>It will be useful if you
- want to use or analyze European Union legislative data in a way
- that the official databases are not originally build for. The API
- extracts, organize and connects data from various official
- sources.</p>
- </div>
- </li>
- </ul>
- </div>
- </section>
- <section class="module">
- <div class="content">
- <ul class="dataset-list unstyled">
- <li class="dataset-item">
- <h2 class="heading"><a href="#">Counselling in London Central, Camden</a></h2>
- <ul class="dataset-resources unstyled">
- <li><a href="#" class="label">HTML</a></li>
- <li><a href="#" class="label">XML</a></li>
- <li><a href="#" class="label">CSV</a></li>
- </ul>
- <div class="content">
- <p>This is an application programming interface (API) that opens up
- core EU legislative data for further use. The interface uses JSON,
- meaning that you have easy to use machine-readable access to
- metadata on European Union legislation.</p>
- <p>It will be useful if you
- want to use or analyze European Union legislative data in a way
- that the official databases are not originally build for. The API
- extracts, organize and connects data from various official
- sources.</p>
- </div>
- </li>
- <li class="dataset-item">
- <h2 class="heading"><a href="#">Counselling in London Central, Camden</a></h2>
- <ul class="dataset-resources unstyled">
- <li><a href="#" class="label">HTML</a></li>
- <li><a href="#" class="label">XML</a></li>
- <li><a href="#" class="label">CSV</a></li>
- </ul>
- <div class="content">
- <p>This is an application programming interface (API) that opens up
- core EU legislative data for further use. The interface uses JSON,
- meaning that you have easy to use machine-readable access to
- metadata on European Union legislation.</p>
- <p>It will be useful if you
- want to use or analyze European Union legislative data in a way
- that the official databases are not originally build for. The API
- extracts, organize and connects data from various official
- sources.</p>
- </div>
- </li>
- <li class="dataset-item">
- <h2 class="heading"><a href="#">Counselling in London Central, Camden</a></h2>
- <ul class="dataset-resources unstyled">
- <li><a href="#" class="label">HTML</a></li>
- <li><a href="#" class="label">XML</a></li>
- <li><a href="#" class="label">CSV</a></li>
- </ul>
- <div class="content">
- <p>This is an application programming interface (API) that opens up
- core EU legislative data for further use. The interface uses JSON,
- meaning that you have easy to use machine-readable access to
- metadata on European Union legislation.</p>
- <p>It will be useful if you
- want to use or analyze European Union legislative data in a way
- that the official databases are not originally build for. The API
- extracts, organize and connects data from various official
- sources.</p>
- </div>
- </li>
- </ul>
- </div>
- <div class="pagination pagination-centered">
- <ul>
- <li><a href="#">Prev</a></li>
- <li class="active"><a href="#">1</a></li>
- <li><a href="#">2</a></li>
- <li><a href="#">3</a></li>
- <li><a href="#">4</a></li>
- <li><a href="#">Next</a></li>
- </ul>
- </div>
- </section>
- <section class="module dataset-filters">
- <p class="content">
- <strong class="results">4 datasets found for "London"</strong>
- +
- <span>Tags:</span>
- <span class="filtered"><a href="#">camden</a> <a href="#">[remove]</a></span>
- <span>Format:</span>
- <span class="filtered"><a href="#">HTML</a> <a href="#">[remove]</a></span>
- <span class="filtered"><a href="#">CSV</a> <a href="#">[remove]</a></span>
- </p>
- </section>
- <section class="module">
- <form class="form-search">
- <input class="search-giant" placeholder="Search" />
- <button>Search</button>
- </form>
- </section>
- <h1 id="masthead" class="primer-heading">Masthead (Site Header)</h1>
- <header class="masthead">
- <hgroup>
- <h1><a href="">My Site Title</a></h1>
- <h2>My Site Tagline</h2>
- </hgroup>
- <nav>
- <ul class="unstyled">
- <li><a href="#">Find</a></li>
- <li><a class="active" href="#">Groups</a></li>
- <li><a href="#">Share</a></li>
- <li><a href="#">About</a></li>
- <li class="section"><a href="#">Login</a></li>
- </ul>
- </nav>
- </header>
- <div class="primer-spacer"></div>
- <header class="masthead">
- <hgroup>
- <h1><a href="">My Site Title</a></h1>
- <h2>My Site Tagline</h2>
- </hgroup>
- <div class="account">
- <a href="#home" class="image">
- <img src="" width="25" height="25" />
- </a>
- <span class="links">
- <a href="#home">username</a>
- <a class="logout" href="#logout">Log out</a>
- </span>
- </div>
- <nav>
- <ul class="unstyled">
- <li><a href="#">Find</a></li>
- <li><a class="active" href="#">Groups</a></li>
- <li><a href="#">Share</a></li>
- <li><a href="#">About</a></li>
- </ul>
- </nav>
- </header>
- <div class="primer-spacer"></div>
- <footer class="site-footer">
- <nav class="footer-links row-fluid">
- <ul class="unstyled row-fluid">
- <li><a href="#">Terms and Conditions</a></li>
- <li><a href="#">Accessibility</a></li>
- <li><a href="#">Code of conduct</a></li>
- <li><a href="#">Moderation policy</a></li>
- <li><a href="#">FAQ</a></li>
- <li><a href="#">Privacy</a></li>
- <li><a href="#">Contact us</a></li>
- <li><a href="#">Consultation</a></li>
- </ul>
- </nav>
- <div class="attribution">
- <p><strong>Powered by</strong> <a href="">CityData</a> from <a href="">CKAN</a></p>
- <p><small>Maps powered by Leaflet, map data © OpenStreetMap contributors, CC-BY-SA, map imagery © CloudMade</small></p>
- </div>
- </footer>
- </div>
- </body>
-</html>
diff --git a/ckan/public-bs2/base/test/spec/ckan.spec.js b/ckan/public-bs2/base/test/spec/ckan.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/ckan.spec.js
+++ /dev/null
@@ -1,70 +0,0 @@
-describe('ckan.initialize()', function () {
- beforeEach(function () {
- this.promise = jQuery.Deferred();
- this.target = sinon.stub(ckan.Client.prototype, 'getLocaleData').returns(this.promise);
- });
-
- afterEach(function () {
- this.target.restore();
- });
-
- it('should load the localisations for the current page', function () {
- ckan.initialize()
- assert.called(this.target);
- });
-
- it('should load the localisations into the i18n library', function () {
- var target = sinon.stub(ckan.i18n, 'load');
- var data = {lang: {}};
-
- ckan.initialize();
- this.promise.resolve(data);
-
- assert.called(target);
- assert.calledWith(target, data);
-
- target.restore();
- });
-
- it('should initialize the module on the page', function () {
- var target = sinon.stub(ckan.module, 'initialize');
-
- ckan.initialize();
- this.promise.resolve();
-
- assert.called(target);
- target.restore();
- });
-});
-
-describe('ckan.url()', function () {
- beforeEach(function () {
- ckan.SITE_ROOT = 'http://example.com';
- ckan.LOCALE_ROOT = ckan.SITE_ROOT + '/en';
- });
-
- it('should return the ckan.SITE_ROOT', function () {
- var target = ckan.url();
- assert.equal(target, ckan.SITE_ROOT);
- });
-
- it('should return the ckan.LOCALE_ROOT if true is passed', function () {
- var target = ckan.url(true);
- assert.equal(target, ckan.LOCALE_ROOT);
- });
-
- it('should append the path provided', function () {
- var target = ckan.url('/test.html');
- assert.equal(target, ckan.SITE_ROOT + '/test.html');
- });
-
- it('should append the path to the locale provided', function () {
- var target = ckan.url('/test.html', true);
- assert.equal(target, ckan.LOCALE_ROOT + '/test.html');
- });
-
- it('should handle missing preceding slashes', function () {
- var target = ckan.url('test.html');
- assert.equal(target, ckan.SITE_ROOT + '/test.html');
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/client.spec.js b/ckan/public-bs2/base/test/spec/client.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/client.spec.js
+++ /dev/null
@@ -1,405 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.Client()', function () {
- var Client = ckan.Client;
-
- beforeEach(function () {
- this.client = new Client();
- });
-
- it('should add a new instance to each client', function () {
- var target = ckan.sandbox().client;
-
- assert.instanceOf(target, Client);
- });
-
- it('should set the .endpoint property to options.endpoint', function () {
- var client = new Client({endpoint: 'http://example.com'});
- assert.equal(client.endpoint, 'http://example.com');
- });
-
- it('should default the endpoint to a blank string', function () {
- assert.equal(this.client.endpoint, '');
- });
-
- describe('.url(path)', function () {
- beforeEach(function () {
- this.client.endpoint = 'http://api.example.com';
- });
-
- it('should return the path with the enpoint prepended', function () {
- assert.equal(this.client.url('/api/endpoint'), 'http://api.example.com/api/endpoint');
- });
-
- it('should normalise preceding slashes in the path', function () {
- assert.equal(this.client.url('api/endpoint'), 'http://api.example.com/api/endpoint');
- });
-
- it('should return the string if it already has a protocol', function () {
- assert.equal(this.client.url('http://example.com/my/endpoint'), 'http://example.com/my/endpoint');
- });
- });
-
- describe('.getTemplate(filename, params, success, error)', function () {
- beforeEach(function () {
- this.fakePromise = sinon.stub(jQuery.Deferred());
- this.fakePromise.then.returns(this.fakePromise);
- sinon.stub(jQuery, 'get').returns(this.fakePromise);
- });
-
- afterEach(function () {
- jQuery.get.restore();
- });
-
- it('should return a jQuery promise', function () {
- var target = this.client.getTemplate('test.html');
- assert.ok(target === this.fakePromise, 'target === this.fakePromise');
- });
-
- it('should request the template file', function () {
- var target = this.client.getTemplate('test.html');
- assert.called(jQuery.get);
- assert.calledWith(jQuery.get, '/api/1/util/snippet/test.html', {});
- });
-
- it('should request the template file with any provided params', function () {
- var options = {limit: 5, page: 2};
- var target = this.client.getTemplate('test.html', options);
- assert.called(jQuery.get);
- assert.calledWith(jQuery.get, '/api/1/util/snippet/test.html', options);
- });
- });
-
- describe('.getLocaleData(locale, success, error)', function () {
- beforeEach(function () {
- this.fakePromise = sinon.stub(jQuery.Deferred());
- this.fakePromise.then.returns(this.fakePromise);
- sinon.stub(jQuery, 'getJSON').returns(this.fakePromise);
- });
-
- afterEach(function () {
- jQuery.getJSON.restore();
- });
-
- it('should return a jQuery promise', function () {
- var target = this.client.getLocaleData('en');
- assert.ok(target === this.fakePromise, 'target === this.fakePromise');
- });
-
- it('should request the locale provided', function () {
- var target = this.client.getLocaleData('en');
- assert.called(jQuery.getJSON);
- assert.calledWith(jQuery.getJSON, '/api/i18n/en');
- });
- });
-
- describe('.getCompletions(url, options, success, error)', function () {
- beforeEach(function () {
- this.fakePiped = sinon.stub(jQuery.Deferred());
- this.fakePiped.then.returns(this.fakePiped);
- this.fakePiped.promise.returns(this.fakePiped);
-
- this.fakePromise = sinon.stub(jQuery.Deferred());
- this.fakePromise.pipe.returns(this.fakePiped);
-
- sinon.stub(jQuery, 'ajax').returns(this.fakePromise);
- });
-
- afterEach(function () {
- jQuery.ajax.restore();
- });
-
- it('should return a jQuery promise', function () {
- var target = this.client.getCompletions('url');
- assert.ok(target === this.fakePiped, 'target === this.fakePiped');
- });
-
- it('should make an ajax request for the url provided', function () {
- function success() {}
- function error() {}
-
- var target = this.client.getCompletions('url', success, error);
-
- assert.called(jQuery.ajax);
- assert.calledWith(jQuery.ajax, {url: '/url'});
-
- assert.called(this.fakePiped.then);
- assert.calledWith(this.fakePiped.then, success, error);
- });
-
- it('should pipe the result through .parseCompletions()', function () {
- var target = this.client.getCompletions('url');
-
- assert.called(this.fakePromise.pipe);
- assert.calledWith(this.fakePromise.pipe, this.client.parseCompletions);
- });
-
- it('should allow a custom format option to be provided', function () {
- function format() {}
-
- var target = this.client.getCompletions('url', {format: format});
-
- assert.called(this.fakePromise.pipe);
- assert.calledWith(this.fakePromise.pipe, format);
- });
-
- });
-
- describe('.parseCompletions(data, options)', function () {
- it('should return a string of tags for a ResultSet collection', function () {
- var data = {
- ResultSet: {
- Result: [
- {"Name": "1 percent"}, {"Name": "18thc"}, {"Name": "19thcentury"}
- ]
- }
- };
-
- var target = this.client.parseCompletions(data, {});
-
- assert.deepEqual(target, ["1 percent", "18thc", "19thcentury"]);
- });
-
- it('should return a string of formats for a ResultSet collection', function () {
- var data = {
- ResultSet: {
- Result: [
- {"Format": "json"}, {"Format": "csv"}, {"Format": "text"}
- ]
- }
- };
-
- var target = this.client.parseCompletions(data, {});
-
- assert.deepEqual(target, ["json", "csv", "text"]);
- });
-
- it('should strip out duplicates with a case insensitive comparison', function () {
- var data = {
- ResultSet: {
- Result: [
- {"Name": " Test"}, {"Name": "test"}, {"Name": "TEST"}
- ]
- }
- };
-
- var target = this.client.parseCompletions(data, {});
-
- assert.deepEqual(target, ["Test"]);
- });
-
- it('should return an array of objects if options.objects is true', function () {
- var data = {
- ResultSet: {
- Result: [
- {"Format": "json"}, {"Format": "csv"}, {"Format": "text"}
- ]
- }
- };
-
- var target = this.client.parseCompletions(data, {objects: true});
-
- assert.deepEqual(target, [
- {id: "json", text: "json"},
- {id: "csv", text: "csv"},
- {id: "text", text: "text"}
- ]);
- });
-
- it('should call .parsePackageCompletions() id data is a string', function () {
- var data = 'Name|id';
- var target = sinon.stub(this.client, 'parsePackageCompletions');
-
- this.client.parseCompletions(data, {objects: true});
-
- assert.called(target);
- assert.calledWith(target, data);
- });
- });
-
- describe('.parseCompletionsForPlugin(data)', function () {
- it('should return a string of tags for a ResultSet collection', function () {
- var data = {
- ResultSet: {
- Result: [
- {"Name": "1 percent"}, {"Name": "18thc"}, {"Name": "19thcentury"}
- ]
- }
- };
-
- var target = this.client.parseCompletionsForPlugin(data);
-
- assert.deepEqual(target, {
- results: [
- {id: "1 percent", text: "1 percent"},
- {id: "18thc", text: "18thc"},
- {id: "19thcentury", text: "19thcentury"}
- ]
- });
- });
- });
-
- describe('.parsePackageCompletions(string, options)', function () {
- it('should parse the package completions string', function () {
- var data = 'Package 1|package-1\nPackage 2|package-2\nPackage 3|package-3\n';
- var target = this.client.parsePackageCompletions(data);
-
- assert.deepEqual(target, ['package-1', 'package-2', 'package-3']);
- });
-
- it('should return an object if options.object is true', function () {
- var data = 'Package 1|package-1\nPackage 2|package-2\nPackage 3|package-3\n';
- var target = this.client.parsePackageCompletions(data, {objects: true});
-
- assert.deepEqual(target, [
- {id: 'package-1', text: 'Package 1'},
- {id: 'package-2', text: 'Package 2'},
- {id: 'package-3', text: 'Package 3'}
- ]);
- });
- });
-
- describe('.getStorageAuth()', function () {
- beforeEach(function () {
- this.fakePromise = sinon.mock(jQuery.Deferred());
- sinon.stub(jQuery, 'ajax').returns(this.fakePromise);
- });
-
- afterEach(function () {
- jQuery.ajax.restore();
- });
-
- it('should return a jQuery promise', function () {
- var target = this.client.getStorageAuth('filename');
- assert.equal(target, this.fakePromise);
- });
-
- it('should call request a new auth token', function () {
- function success() {}
- function error() {}
-
- var target = this.client.getStorageAuth('filename', success, error);
-
- assert.called(jQuery.ajax);
- assert.calledWith(jQuery.ajax, {
- url: '/api/storage/auth/form/filename',
- success: success,
- error: error
- });
- });
- });
-
- describe('.getStorageMetadata()', function () {
- beforeEach(function () {
- this.fakePromise = sinon.mock(jQuery.Deferred());
- sinon.stub(jQuery, 'ajax').returns(this.fakePromise);
- });
-
- afterEach(function () {
- jQuery.ajax.restore();
- });
-
- it('should return a jQuery promise', function () {
- var target = this.client.getStorageMetadata('filename');
- assert.equal(target, this.fakePromise);
- });
-
- it('should call request a new auth token', function () {
- function success() {}
- function error() {}
-
- var target = this.client.getStorageMetadata('filename', success, error);
-
- assert.called(jQuery.ajax);
- assert.calledWith(jQuery.ajax, {
- url: '/api/storage/metadata/filename',
- success: success,
- error: error
- });
- });
-
- it('should throw an error if no filename is provided', function () {
- var client = this.client;
- assert.throws(function () {
- client.getStorageMetadata();
- });
- });
- });
-
- describe('.convertStorageMetadataToResource(meta)', function () {
- beforeEach(function () {
- this.meta = {
- "_checksum": "md5:527c97d2aa3ed1b40aea4b7ddf98692e",
- "_content_length": 122632,
- "_creation_date": "2012-07-17T14:35:35",
- "_label": "2012-07-17T13:35:35.540Z/cat.jpg",
- "_last_modified": "2012-07-17T14:35:35",
- "_location": "http://example.com/storage/f/2012-07-17T13%3A35%3A35.540Z/cat.jpg",
- "filename-original": "cat.jpg",
- "key": "2012-07-17T13:35:35.540Z/cat.jpg",
- "uploaded-by": "user"
- };
- });
-
- it('should return a representation for a resource', function () {
- var target = this.client.convertStorageMetadataToResource(this.meta);
-
- assert.deepEqual(target, {
- url: 'http://example.com/storage/f/2012-07-17T13%3A35%3A35.540Z/cat.jpg',
- key: '2012-07-17T13:35:35.540Z/cat.jpg',
- name: 'cat.jpg',
- size: 122632,
- created: "2012-07-17T14:35:35",
- last_modified: "2012-07-17T14:35:35",
- format: 'jpg',
- mimetype: null,
- resource_type: 'file.upload', // Is this standard?
- owner: 'user',
- hash: 'md5:527c97d2aa3ed1b40aea4b7ddf98692e',
- cache_url: 'http://example.com/storage/f/2012-07-17T13%3A35%3A35.540Z/cat.jpg',
- cache_url_updated: '2012-07-17T14:35:35'
- });
- });
-
- it('should provide a full url', function () {
- ckan.SITE_ROOT = 'http://example.com';
-
- this.meta._location = "/storage/f/2012-07-17T13%3A35%3A35.540Z/cat.jpg";
- var target = this.client.convertStorageMetadataToResource(this.meta);
- assert.equal(target.url, 'http://example.com/storage/f/2012-07-17T13%3A35%3A35.540Z/cat.jpg');
- });
-
- it('should not include microseconds or timezone in timestamps', function () {
- ckan.SITE_ROOT = 'http://example.com';
-
- var target = this.client.convertStorageMetadataToResource(this.meta);
- assert.ok(!(/\.\d\d\d/).test(target.last_modified), 'no microseconds');
- assert.ok(!(/((\+|\-)\d{4}|Z)$/).test(target.last_modified), 'no timezone');
- });
-
- it('should use the mime type for the format if found', function () {
- this.meta._format = 'image/jpeg';
- var target = this.client.convertStorageMetadataToResource(this.meta);
-
- assert.equal(target.format, 'image/jpeg', 'format');
- assert.equal(target.mimetype, 'image/jpeg', 'mimetype');
- });
- });
-
- describe('.normalizeTimestamp(timestamp)', function () {
- it('should add a timezone to a timestamp without one', function () {
- var target = this.client.normalizeTimestamp("2012-07-17T14:35:35");
- assert.equal(target, "2012-07-17T14:35:35Z");
- });
-
- it('should not add a timezone to a timestamp with one already', function () {
- var target = this.client.normalizeTimestamp("2012-07-17T14:35:35Z");
- assert.equal(target, "2012-07-17T14:35:35Z", 'timestamp with Z');
-
- target = this.client.normalizeTimestamp("2012-07-17T14:35:35+0100");
- assert.equal(target, "2012-07-17T14:35:35+0100", 'timestamp with +0100');
-
- target = this.client.normalizeTimestamp("2012-07-17T14:35:35-0400");
- assert.equal(target, "2012-07-17T14:35:35-0400", 'timestamp with -0400');
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/i18n.spec.js b/ckan/public-bs2/base/test/spec/i18n.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/i18n.spec.js
+++ /dev/null
@@ -1,116 +0,0 @@
-describe('ckan.i18n', function () {
- describe('ckan.i18n.translate', function () {
- it('should work while being deprecated', function () {
- var x = ckan.i18n.translate('foo');
- assert.deepProperty(x, 'fetch');
- assert.equal(x.fetch(), 'FOO');
- assert.deepProperty(x, 'ifPlural');
- });
- });
-
- describe('._(string, [values])', function () {
- it('should return the translated string', function () {
- assert.equal(ckan.i18n._('foo'), 'FOO');
- });
-
- it('should return the key when no translation exists', function () {
- assert.equal(ckan.i18n._('no translation'), 'no translation');
- });
-
- it('should fill in placeholders', function () {
- assert.equal(
- ckan.i18n._('hello %(name)s!', {name: 'Julia'}),
- 'HELLO Julia!'
- );
- });
-
- it('should fill in placeholders when no translation exists', function () {
- assert.equal(
- ckan.i18n._('no %(attr)s translation', {attr: 'good'}),
- 'no good translation'
- );
- });
- });
-
- describe('.ngettext(singular, plural, number, [values])', function () {
- var ngettext = ckan.i18n.ngettext;
-
- it('should return the translated strings', function () {
- assert.equal(ngettext('bar', 'bars', 1), 'BAR');
- assert.equal(ngettext('bar', 'bars', 0), 'BARS');
- assert.equal(ngettext('bar', 'bars', 2), 'BARS');
- });
-
- it('should return the key when no translation exists', function () {
- assert.equal(
- ngettext('no translation', 'no translations', 1),
- 'no translation'
- );
- assert.equal(
- ngettext('no translation', 'no translations', 0),
- 'no translations'
- );
- assert.equal(
- ngettext('no translation', 'no translations', 2),
- 'no translations'
- );
- });
-
- it('should fill in placeholders', function () {
- assert.equal(
- ngettext('%(color)s shirt', '%(color)s shirts', 1, {color: 'RED'}),
- 'RED SHIRT'
- );
- assert.equal(
- ngettext('%(color)s shirt', '%(color)s shirts', 0, {color: 'RED'}),
- 'RED SHIRTS'
- );
- assert.equal(
- ngettext('%(color)s shirt', '%(color)s shirts', 2, {color: 'RED'}),
- 'RED SHIRTS'
- );
- });
-
- it('should fill in placeholders when no translation exists', function () {
- assert.equal(
- ngettext('no %(attr)s translation', 'no %(attr)s translations',
- 1, {attr: 'good'}),
- 'no good translation'
- );
- assert.equal(
- ngettext('no %(attr)s translation', 'no %(attr)s translations',
- 0, {attr: 'good'}),
- 'no good translations'
- );
- assert.equal(
- ngettext('no %(attr)s translation', 'no %(attr)s translations',
- 2, {attr: 'good'}),
- 'no good translations'
- );
- });
-
- it('should provide a magic `num` placeholder', function () {
- assert.equal(ngettext('%(num)d item', '%(num)d items', 1), '1 ITEM');
- assert.equal(ngettext('%(num)d item', '%(num)d items', 0), '0 ITEMS');
- assert.equal(ngettext('%(num)d item', '%(num)d items', 2), '2 ITEMS');
- });
-
- it('should provide `num` when no translation exists', function () {
- assert.equal(
- ngettext('%(num)d missing translation',
- '%(num)d missing translations', 1),
- '1 missing translation'
- );
- assert.equal(
- ngettext('%(num)d missing translation',
- '%(num)d missing translations', 0),
- '0 missing translations'
- );
- assert.equal(
- ngettext('%(num)d missing translation',
- '%(num)d missing translations', 2),
- '2 missing translations'
- );
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/module.spec.js b/ckan/public-bs2/base/test/spec/module.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/module.spec.js
+++ /dev/null
@@ -1,418 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.module(id, properties|callback)', function () {
- beforeEach(function () {
- ckan.module.registry = {};
- ckan.module.instances = {};
- this.factory = {};
- });
-
- it('should add a new item to the registry', function () {
- ckan.module('test', this.factory);
-
- assert.instanceOf(new ckan.module.registry.test(), ckan.module.BaseModule);
- });
-
- it('should allow a function to be provided', function () {
- var target = sinon.stub().returns({});
- ckan.module('test', target);
-
- assert.called(target);
- });
-
- it('should pass jQuery, i18n.translate() and i18n into the function', function () {
- // Note: This behavior is deprecated but kept for backwards-compatibility
- var target = sinon.stub().returns({});
- ckan.module('test', target);
-
- assert.calledWith(target, jQuery, ckan.i18n.translate, ckan.i18n);
- });
-
- it('should throw an exception if the module is already defined', function () {
- ckan.module('name', this.factory);
- assert.throws(function () {
- ckan.module('name', this.factory);
- });
- });
-
- it('should return the ckan object', function () {
- assert.equal(ckan.module('name', this.factory), ckan);
- });
-
- describe('.initialize()', function () {
- beforeEach(function () {
- this.element1 = jQuery('<div data-module="test1">').appendTo(this.fixture);
- this.element2 = jQuery('<div data-module="test1">').appendTo(this.fixture);
- this.element3 = jQuery('<div data-module="test2">').appendTo(this.fixture);
-
- this.test1 = sinon.spy();
-
- // Add test1 to the registry.
- ckan.module.registry = {
- test1: this.test1
- };
-
- this.target = sinon.stub(ckan.module, 'createInstance');
- });
-
- afterEach(function () {
- this.target.restore();
- });
-
- it('should find all elements with the "data-module" attribute', function () {
- ckan.module.initialize();
- assert.called(this.target);
- });
-
- it('should skip modules that are not functions', function () {
- ckan.module.initialize();
- assert.calledTwice(this.target);
- });
-
- it('should call module.createInstance() with the element and factory', function () {
- ckan.module.initialize();
- assert.calledWith(this.target, this.test1, this.element1[0]);
- assert.calledWith(this.target, this.test1, this.element2[0]);
- });
-
- it('should return the module object', function () {
- assert.equal(ckan.module.initialize(), ckan.module);
- });
-
- it('should initialize more than one module sepearted by a space', function () {
- this.fixture.empty();
- this.element4 = jQuery('<div data-module="test1 test2">').appendTo(this.fixture);
- this.test2 = ckan.module.registry.test2 = sinon.spy();
-
- ckan.module.initialize();
-
- assert.calledWith(this.target, this.test1, this.element4[0]);
- assert.calledWith(this.target, this.test2, this.element4[0]);
- });
-
- it('should defer all published events untill all modules have loaded', function () {
- var pubsub = ckan.pubsub;
- var callbacks = [];
-
- // Ensure each module is loaded. Three in total.
- ckan.module.registry = {
- test1: function () {},
- test2: function () {}
- };
-
- // Call a function to publish and subscribe to an event on each instance.
- this.target.restore();
- this.target = sinon.stub(ckan.module, 'createInstance', function () {
- var callback = sinon.spy();
-
- pubsub.publish('test');
- pubsub.subscribe('test', callback);
-
- callbacks.push(callback);
- });
-
- ckan.module.initialize();
-
- // Ensure that all subscriptions received all messages.
- assert.ok(callbacks.length, 'no callbacks were created');
- jQuery.each(callbacks, function () {
- assert.calledThrice(this);
- });
- });
- });
-
- describe('.createInstance(Module, element)', function () {
- beforeEach(function () {
- this.element = document.createElement('div');
- this.factory = ckan.module.BaseModule;
- this.factory.options = this.defaults = {test1: 'a', test2: 'b', test3: 'c'};
-
- this.sandbox = {
- i18n: {
- translate: sinon.spy()
- }
- };
- sinon.stub(ckan, 'sandbox').returns(this.sandbox);
-
- this.extractedOptions = {test1: 1, test2: 2};
- sinon.stub(ckan.module, 'extractOptions').returns(this.extractedOptions);
- });
-
- afterEach(function () {
- ckan.sandbox.restore();
- ckan.module.extractOptions.restore();
- });
-
- it('should extract the options from the element', function () {
- ckan.module.createInstance(this.factory, this.element);
-
- assert.called(ckan.module.extractOptions);
- assert.calledWith(ckan.module.extractOptions, this.element);
- });
-
- it('should not modify the defaults object', function () {
- var clone = jQuery.extend({}, this.defaults);
- ckan.module.createInstance(this.factory, this.element);
-
- assert.deepEqual(this.defaults, clone);
- });
-
- it('should create a sandbox object', function () {
- ckan.module.createInstance(this.factory, this.element);
- assert.called(ckan.sandbox);
- assert.calledWith(ckan.sandbox, this.element);
- });
-
- it('should initialize the module factory with the sandbox, options and translate function', function () {
- var target = sinon.spy();
- ckan.module.createInstance(target, this.element);
-
- assert.called(target);
- assert.calledWith(target, this.element, this.extractedOptions, this.sandbox);
- });
-
- it('should initialize the module as a constructor', function () {
- var target = sinon.spy();
- ckan.module.createInstance(target, this.element);
-
- assert.calledWithNew(target);
-
- });
-
- it('should call the .initialize() method if one exists', function () {
- var init = sinon.spy();
- var target = sinon.stub().returns({
- initialize: init
- });
-
- ckan.module.createInstance(target, this.element);
-
- assert.called(init);
- });
-
- it('should push the new instance into an array under ckan.module.instances', function () {
- var target = function MyModule() { return {'mock': 'instance'}; };
- target.namespace = 'test';
-
- ckan.module.createInstance(target, this.element);
-
- assert.deepEqual(ckan.module.instances.test, [{'mock': 'instance'}]);
- });
-
- it('should push further instances into the existing array under ckan.module.instances', function () {
- var target = function MyModule() { return {'mock': 'instance3'}; };
- target.namespace = 'test';
-
- ckan.module.instances.test = [{'mock': 'instance1'}, {'mock': 'instance2'}];
- ckan.module.createInstance(target, this.element);
-
- assert.deepEqual(ckan.module.instances.test, [
- {'mock': 'instance1'}, {'mock': 'instance2'}, {'mock': 'instance3'}
- ]);
- });
-
- });
-
- describe('.extractOptions(element)', function () {
- it('should extract the data keys from the element', function () {
- var element = jQuery('<div>', {
- 'data-not-module': 'skip',
- 'data-module': 'skip',
- 'data-module-a': 'capture',
- 'data-module-b': 'capture',
- 'data-module-c': 'capture'
- })[0];
-
- var target = ckan.module.extractOptions(element);
-
- assert.deepEqual(target, {a: 'capture', b: 'capture', c: 'capture'});
- });
-
- it('should convert JSON contents of keys into JS primitives', function () {
- var element = jQuery('<div>', {
- 'data-module-null': 'null',
- 'data-module-int': '100',
- 'data-module-arr': '[1, 2, 3]',
- 'data-module-obj': '{"a": 1, "b":2, "c": 3}',
- 'data-module-str': 'hello'
- })[0];
-
- var target = ckan.module.extractOptions(element);
-
- assert.deepEqual(target, {
- 'null': null,
- 'int': 100,
- 'arr': [1, 2, 3],
- 'obj': {"a": 1, "b": 2, "c": 3},
- 'str': 'hello'
- });
- });
-
- it('should simply use strings for content that it cannot parse as JSON', function () {
- var element = jQuery('<div>', {
- 'data-module-url': 'http://example.com/path/to.html',
- 'data-module-bad': '{oh: 1, no'
- })[0];
-
- var target = ckan.module.extractOptions(element);
-
- assert.deepEqual(target, {
- 'url': 'http://example.com/path/to.html',
- 'bad': '{oh: 1, no'
- });
- });
-
- it('should convert keys with hyphens into camelCase', function () {
- var element = jQuery('<div>', {
- 'data-module-long-property': 'long',
- 'data-module-really-very-long-property': 'longer'
- })[0];
-
- var target = ckan.module.extractOptions(element);
-
- assert.deepEqual(target, {
- 'longProperty': 'long',
- 'reallyVeryLongProperty': 'longer'
- });
- });
-
- it('should set boolean attributes to true', function () {
- var element = jQuery('<div>', {
- 'data-module-long-property': ''
- })[0];
-
- var target = ckan.module.extractOptions(element);
-
- assert.deepEqual(target, {'longProperty': true});
- });
- });
-
- describe('BaseModule(element, options, sandbox)', function () {
- var BaseModule = ckan.module.BaseModule;
-
- beforeEach(function () {
- this.el = jQuery('<div />');
- this.options = {};
- this.sandbox = ckan.sandbox();
- this.module = new BaseModule(this.el, this.options, this.sandbox);
- });
-
- it('should assign .el as the element option', function () {
- assert.ok(this.module.el === this.el);
- });
-
- it('should wrap .el in jQuery if not already wrapped', function () {
- var element = document.createElement('div');
- var target = new BaseModule(element, this.options, this.sandbox);
-
- assert.ok(target.el instanceof jQuery);
- });
-
- it('should deep extend the options object', function () {
- // Lazy check :/
- var target = sinon.stub(jQuery, 'extend');
- new BaseModule(this.el, this.options, this.sandbox);
-
- assert.called(target);
- assert.calledWith(target, true, {}, BaseModule.prototype.options, this.options);
-
- target.restore();
- });
-
- it('should assign the sandbox property', function () {
- assert.equal(this.module.sandbox, this.sandbox);
- });
-
- describe('.$(selector)', function () {
- it('should find children within the module element', function () {
- this.module.el.append(jQuery('<input /><input />'));
- assert.equal(this.module.$('input').length, 2);
- });
- });
-
- describe('.i18n()', function () {
- // Note: This function is deprecated but kept for backwards-compatibility
- beforeEach(function () {
- this.i18n = {
- first: 'first string',
- second: {fetch: sinon.stub().returns('second string')},
- third: sinon.stub().returns('third string')
- };
-
- this.module.options.i18n = this.i18n;
- });
-
- it('should return the translation string', function () {
- var target = this.module.i18n('first');
- assert.equal(target, 'first string');
- });
-
- it('should call fetch on the translation string if it exists', function () {
- var target = this.module.i18n('second');
- assert.equal(target, 'second string');
- });
-
- it('should return just the key if no translation exists', function () {
- var target = this.module.i18n('missing');
- assert.equal(target, 'missing');
- });
-
- it('should call the translation function if one is provided', function () {
- var target = this.module.i18n('third');
- assert.equal(target, 'third string');
- });
-
- it('should pass the argments after the key into trans.fetch()', function () {
- var target = this.module.options.i18n.second.fetch;
- this.module.i18n('second', 1, 2, 3);
- assert.called(target);
- assert.calledWith(target, 1, 2, 3);
- });
-
- it('should pass the argments after the key into the translation function', function () {
- var target = this.module.options.i18n.third;
- this.module.i18n('third', 1, 2, 3);
- assert.called(target);
- assert.calledWith(target, 1, 2, 3);
- });
- });
-
- describe('._()', function () {
- it('should be a shortcut for ckan.i18n._', function () {
- /*
- * In a module, this._ is a shortcut for ckan.i18n._,
- * but it's not a direct reference.
- */
- assert.equal(this.module._('foo'), 'FOO');
- });
- });
-
- describe('.ngettext()', function () {
- it('should be a shortcut for ckan.i18n.ngettext', function () {
- /*
- * In a module, this.ngettext is a shortcut for ckan.i18n.ngettext,
- * but it's not a direct reference.
- */
- assert.equal(this.module.ngettext('bar', 'bars', 1), 'BAR');
- assert.equal(this.module.ngettext('bar', 'bars', 0), 'BARS');
- assert.equal(this.module.ngettext('bar', 'bars', 2), 'BARS');
- });
- });
-
- describe('.remove()', function () {
- it('should teardown the module', function () {
- var target = sinon.stub(this.module, 'teardown');
-
- this.module.remove();
-
- assert.called(target);
- });
-
- it('should remove the element from the page', function () {
- this.fixture.append(this.module.el);
- this.module.remove();
-
- assert.equal(this.fixture.children().length, 0);
- });
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/modules/autocomplete.spec.js b/ckan/public-bs2/base/test/spec/modules/autocomplete.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/modules/autocomplete.spec.js
+++ /dev/null
@@ -1,315 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.modules.AutocompleteModule()', function () {
- var Autocomplete = ckan.module.registry['autocomplete'];
-
- beforeEach(function () {
- // Stub select2 plugin if loaded.
- if (jQuery.fn.select2) {
- this.select2 = sinon.stub(jQuery.fn, 'select2');
- } else {
- this.select2 = jQuery.fn.select2 = sinon.stub().returns({
- data: sinon.stub().returns({
- on: sinon.stub()
- })
- });
- }
-
- this.el = document.createElement('input');
- this.sandbox = ckan.sandbox();
- this.sandbox.body = this.fixture;
- this.module = new Autocomplete(this.el, {}, this.sandbox);
- });
-
- afterEach(function () {
- this.module.teardown();
-
- if (this.select2.restore) {
- this.select2.restore();
- } else {
- delete jQuery.fn.select2;
- }
- });
-
- describe('.initialize()', function () {
- it('should bind callback methods to the module', function () {
- var target = sinon.stub(jQuery, 'proxyAll');
-
- this.module.initialize();
-
- assert.called(target);
- assert.calledWith(target, this.module, /_on/, /format/);
-
- target.restore();
- });
-
- it('should setup the autocomplete plugin', function () {
- var target = sinon.stub(this.module, 'setupAutoComplete');
-
- this.module.initialize();
-
- assert.called(target);
- });
- });
-
- describe('.setupAutoComplete()', function () {
- it('should initialize the autocomplete plugin', function () {
- this.module.setupAutoComplete();
-
- assert.called(this.select2);
- assert.calledWith(this.select2, {
- width: 'resolve',
- query: this.module._onQuery,
- dropdownCssClass: '',
- containerCssClass: '',
- formatResult: this.module.formatResult,
- formatNoMatches: this.module.formatNoMatches,
- formatInputTooShort: this.module.formatInputTooShort,
- createSearchChoice: this.module.formatTerm, // Not used by tags.
- initSelection: this.module.formatInitialValue
- });
- });
-
- it('should initialize the autocomplete plugin with a tags callback if options.tags is true', function () {
- this.module.options.tags = true;
- this.module.setupAutoComplete();
-
- assert.called(this.select2);
- assert.calledWith(this.select2, {
- width: 'resolve',
- tags: this.module._onQuery,
- dropdownCssClass: '',
- containerCssClass: '',
- formatResult: this.module.formatResult,
- formatNoMatches: this.module.formatNoMatches,
- formatInputTooShort: this.module.formatInputTooShort,
- initSelection: this.module.formatInitialValue
- });
-
- it('should watch the keydown event on the select2 input');
-
- it('should allow a custom css class to be added to the dropdown', function () {
- this.module.options.dropdownClass = 'tags';
- this.module.setupAutoComplete();
-
- assert.called(this.select2);
- assert.calledWith(this.select2, {
- width: 'resolve',
- tags: this.module._onQuery,
- dropdownCssClass: 'tags',
- containerCssClass: '',
- formatResult: this.module.formatResult,
- formatNoMatches: this.module.formatNoMatches,
- formatInputTooShort: this.module.formatInputTooShort,
- initSelection: this.module.formatInitialValue
- });
- });
-
- it('should allow a custom css class to be added to the container', function () {
- this.module.options.containerClass = 'tags';
- this.module.setupAutoComplete();
-
- assert.called(this.select2);
- assert.calledWith(this.select2, {
- width: 'resolve',
- tags: this.module._onQuery,
- dropdownCssClass: '',
- containerCssClass: 'tags',
- formatResult: this.module.formatResult,
- formatNoMatches: this.module.formatNoMatches,
- formatInputTooShort: this.module.formatInputTooShort,
- initSelection: this.module.formatInitialValue
- });
- });
-
- });
- });
-
- describe('.getCompletions(term, fn)', function () {
- beforeEach(function () {
- this.term = 'term';
- this.module.options.source = 'http://example.com?term=?';
-
- this.target = sinon.stub(this.sandbox.client, 'getCompletions');
- });
-
- it('should get the completions from the client', function () {
- this.module.getCompletions(this.term);
- assert.called(this.target);
- });
-
- it('should replace the last ? in the source url with the term', function () {
- this.module.getCompletions(this.term);
- assert.calledWith(this.target, 'http://example.com?term=term');
- });
-
- it('should escape special characters in the term', function () {
- this.module.getCompletions('term with spaces');
- assert.calledWith(this.target, 'http://example.com?term=term%20with%20spaces');
- });
- });
-
- describe('.lookup(term, fn)', function () {
- beforeEach(function () {
- sinon.stub(this.module, 'getCompletions');
- this.target = sinon.spy();
- this.module.setupAutoComplete();
- });
-
- it('should set the _lastTerm property', function () {
- this.module.lookup('term', this.target);
- assert.equal(this.module._lastTerm, 'term');
- });
-
- it('should call the fn immediately if there is no term', function () {
- this.module.lookup('', this.target);
- assert.called(this.target);
- assert.calledWith(this.target, {results: []});
- });
-
- it('should debounce the request if there is a term');
- it('should cancel the last request');
- });
-
- describe('.formatResult(state)', function () {
- beforeEach(function () {
- this.module._lastTerm = 'term';
- });
-
- it('should return the string with the last term wrapped in bold tags', function () {
- var target = this.module.formatResult({id: 'we have termites', text: 'we have termites'});
- assert.equal(target, 'we have <b>term</b>ites');
- });
-
- it('should return the string with each instance of the term wrapped in bold tags', function () {
- var target = this.module.formatResult({id: 'we have a termite terminology', text: 'we have a termite terminology'});
- assert.equal(target, 'we have a <b>term</b>ite <b>term</b>inology');
- });
-
- it('should return the term if there is no last term saved', function () {
- delete this.module._lastTerm;
- var target = this.module.formatResult({id: 'we have a termite terminology', text: 'we have a termite terminology'});
- assert.equal(target, 'we have a termite terminology');
- });
- });
-
- describe('.formatNoMatches(term)', function () {
- it('should return the no matches string if there is a term', function () {
- var target = this.module.formatNoMatches('term');
- assert.equal(target, 'No matches found');
- });
-
- it('should return the empty string if there is no term', function () {
- var target = this.module.formatNoMatches('');
- assert.equal(target, 'Start typing…');
- });
- });
-
- describe('.formatInputTooShort(term, min)', function () {
- it('should return the plural input too short string', function () {
- var target = this.module.formatInputTooShort('term', 2);
- assert.equal(target, 'Input is too short, must be at least 2 characters');
- });
-
- it('should return the singular input too short string', function () {
- var target = this.module.formatInputTooShort('term', 1);
- assert.equal(target, 'Input is too short, must be at least one character');
- });
- });
-
- describe('.formatTerm()', function () {
- it('should return an item object with id and text properties', function () {
- assert.deepEqual(this.module.formatTerm('test'), {id: 'test', text: 'test'});
- });
-
- it('should trim whitespace from the value', function () {
- assert.deepEqual(this.module.formatTerm(' test '), {id: 'test', text: 'test'});
- });
-
- it('should convert commas in ids into unicode characters', function () {
- assert.deepEqual(this.module.formatTerm('test, test'), {id: 'test\u002C test', text: 'test, test'});
- });
- });
-
- describe('.formatInitialValue(element, callback)', function () {
- beforeEach(function () {
- this.callback = sinon.spy();
- });
-
- it('should pass an item object with id and text properties into the callback', function () {
- var target = jQuery('<input value="test"/>');
-
- this.module.formatInitialValue(target, this.callback);
- assert.calledWith(this.callback, {id: 'test', text: 'test'});
- });
-
- it('should pass an array of properties into the callback if options.tags is true', function () {
- this.module.options.tags = true;
- var target = jQuery('<input />', {value: "test, test"});
-
- this.module.formatInitialValue(target, this.callback);
- assert.calledWith(this.callback, [{id: 'test', text: 'test'}, {id: 'test', text: 'test'}]);
- });
-
- it('should return the value if no callback is provided (to support select2 v2.1)', function () {
- var target = jQuery('<input value="test"/>');
-
- assert.deepEqual(this.module.formatInitialValue(target), {id: 'test', text: 'test'});
- });
- });
-
- describe('._onQuery(options)', function () {
- it('should lookup the current term with the callback', function () {
- var target = sinon.stub(this.module, 'lookup');
-
- this.module._onQuery({term: 'term', callback: 'callback'});
-
- assert.called(target);
- assert.calledWith(target, 'term', 'callback');
- });
-
- it('should do nothing if there is no options object', function () {
- var target = sinon.stub(this.module, 'lookup');
- this.module._onQuery();
- assert.notCalled(target);
- });
- });
-
- describe('._onKeydown(event)', function () {
- beforeEach(function () {
- this.keyDownEvent = jQuery.Event("keydown", { which: 188 });
- this.fakeEvent = {};
- this.clock = sinon.useFakeTimers();
- this.jQuery = sinon.stub(jQuery.fn, 'init', jQuery.fn.init);
- this.Event = sinon.stub(jQuery, 'Event').returns(this.fakeEvent);
- this.trigger = sinon.stub(jQuery.fn, 'trigger');
- });
-
- afterEach(function () {
- this.clock.restore();
- this.jQuery.restore();
- this.Event.restore();
- this.trigger.restore();
- });
-
- it('should trigger fake "return" keypress if a comma is pressed', function () {
- this.module._onKeydown(this.keyDownEvent);
-
- this.clock.tick(100);
-
- assert.called(this.jQuery);
- assert.called(this.Event);
- assert.called(this.trigger);
- assert.calledWith(this.trigger, this.fakeEvent);
- });
-
- it('should do nothing if another key is pressed', function () {
- this.keyDownEvent.which = 200;
-
- this.module._onKeydown(this.keyDownEvent);
-
- this.clock.tick(100);
-
- assert.notCalled(this.Event);
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/modules/basic-form.spec.js b/ckan/public-bs2/base/test/spec/modules/basic-form.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/modules/basic-form.spec.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.module.BasicFormModule()', function () {
- var BasicFormModule = ckan.module.registry['basic-form'];
-
- beforeEach(function () {
- sinon.stub(jQuery.fn, 'incompleteFormWarning');
-
- this.el = document.createElement('form');
- this.el.innerHTML = '<button name="save" type="submit">Save</button>'
- this.sandbox = ckan.sandbox();
- this.sandbox.body = this.fixture;
- this.sandbox.body.append(this.el)
- this.module = new BasicFormModule(this.el, {}, this.sandbox);
- });
-
- afterEach(function () {
- this.module.teardown();
- jQuery.fn.incompleteFormWarning.restore();
- });
-
- describe('.initialize()', function () {
- it('should attach the jQuery.fn.incompleteFormWarning() to the form', function () {
- this.module.initialize();
- assert.called(jQuery.fn.incompleteFormWarning);
- });
-
- it('should disable the submit button on form submit', function(done) {
- this.module.initialize();
- this.module._onSubmit();
-
- setTimeout(function() {
- var buttonAttrDisabled = this.el.querySelector('button').getAttribute('disabled');
-
- assert.ok(buttonAttrDisabled === 'disabled')
- done();
- }.bind(this), 0);
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/modules/confirm-action.spec.js b/ckan/public-bs2/base/test/spec/modules/confirm-action.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/modules/confirm-action.spec.js
+++ /dev/null
@@ -1,118 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.module.ConfirmActionModule()', function () {
- var ConfirmActionModule = ckan.module.registry['confirm-action'];
-
- beforeEach(function () {
- jQuery.fn.modal = sinon.spy();
-
- this.el = document.createElement('button');
- this.sandbox = ckan.sandbox();
- this.sandbox.body = this.fixture;
- this.module = new ConfirmActionModule(this.el, {}, this.sandbox);
- });
-
- afterEach(function () {
- this.module.teardown();
- });
-
- describe('.initialize()', function () {
- it('should watch for clicks on the module element', function () {
- var target = sinon.stub(this.module.el, 'on');
- this.module.initialize();
- assert.called(target);
- assert.calledWith(target, 'click', this.module._onClick);
- });
- });
-
- describe('.confirm()', function () {
- it('should append the modal to the document body', function () {
- this.module.confirm();
- assert.equal(this.fixture.children().length, 1);
- assert.equal(this.fixture.find('.modal').length, 1);
- });
-
- it('should show the modal dialog', function () {
- this.module.confirm();
- assert.called(jQuery.fn.modal);
- assert.calledWith(jQuery.fn.modal, 'show');
- });
- });
-
- describe('.performAction()', function () {
- it('should submit the action');
- });
-
- describe('.createModal()', function () {
- it('should create the modal element', function () {
- var target = this.module.createModal();
-
- assert.ok(target.hasClass('modal'));
- });
-
- it('should set the module.modal property', function () {
- var target = this.module.createModal();
-
- assert.ok(target === this.module.modal);
- });
-
- it('should bind the success/cancel listeners', function () {
- var target = sinon.stub(jQuery.fn, 'on');
-
- this.module.createModal();
-
- // Not an ideal check as this implementation could be done in many ways.
- assert.calledTwice(target);
- assert.calledWith(target, 'click', '.btn-primary', this.module._onConfirmSuccess);
- assert.calledWith(target, 'click', '.btn-cancel', this.module._onConfirmCancel);
-
- target.restore();
- });
-
- it('should initialise the modal plugin', function () {
- this.module.createModal();
- assert.called(jQuery.fn.modal);
- assert.calledWith(jQuery.fn.modal, {show: false});
- });
-
- it('should allow to customize the content', function () {
- this.module.options.content = 'some custom content';
- var target = this.module.createModal();
-
- assert.equal(target.find('.modal-body').text(), 'some custom content');
- });
- });
-
- describe('._onClick()', function () {
- it('should prevent the default action', function () {
- var target = {preventDefault: sinon.spy()};
- this.module._onClick(target);
-
- assert.called(target.preventDefault);
- });
-
- it('should display the confirmation dialog', function () {
- var target = sinon.stub(this.module, 'confirm');
- this.module._onClick({preventDefault: sinon.spy()});
- assert.called(target);
- });
- });
-
- describe('._onConfirmSuccess()', function () {
- it('should perform the action', function () {
- var target = sinon.stub(this.module, 'performAction');
- this.module._onConfirmSuccess(jQuery.Event('click'));
- assert.called(target);
- });
- });
-
- describe('._onConfirmCancel()', function () {
- it('should hide the modal', function () {
- this.module.modal = jQuery('<div/>');
- this.module._onConfirmCancel(jQuery.Event('click'));
-
- assert.called(jQuery.fn.modal);
- assert.calledWith(jQuery.fn.modal, 'hide');
- });
- });
-
-});
diff --git a/ckan/public-bs2/base/test/spec/modules/custom-fields.spec.js b/ckan/public-bs2/base/test/spec/modules/custom-fields.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/modules/custom-fields.spec.js
+++ /dev/null
@@ -1,175 +0,0 @@
-/*globals describe before beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.module.CustomFieldsModule()', function () {
- var CustomFieldsModule = ckan.module.registry['custom-fields'];
-
- before(function (done) {
- this.loadFixture('custom_fields.html', function (template) {
- this.template = template;
- done();
- });
- });
-
- beforeEach(function () {
- this.fixture.html(this.template);
- this.el = this.fixture.find('[data-module]');
- this.sandbox = ckan.sandbox();
- this.sandbox.body = this.fixture;
- this.module = new CustomFieldsModule(this.el, {}, this.sandbox);
- });
-
- afterEach(function () {
- this.module.teardown();
- });
-
- describe('.initialize()', function () {
- it('should bind all functions beginning with _on to the module scope', function () {
- var target = sinon.stub(jQuery, 'proxyAll');
-
- this.module.initialize();
-
- assert.called(target);
- assert.calledWith(target, this.module, /_on/);
-
- target.restore();
- });
-
- it('should listen for changes to the last "key" input', function () {
- var target = sinon.stub(this.module, '_onChange');
-
- this.module.initialize();
- this.module.$('input[name*=key]').change();
-
- assert.calledOnce(target);
- });
-
- it('should listen for changes to all checkboxes', function () {
- var target = sinon.stub(this.module, '_onRemove');
-
- this.module.initialize();
- this.module.$(':checkbox').trigger('change');
-
- assert.calledOnce(target);
- });
-
- it('should add "button" classes to the remove input', function () {
- this.module.initialize();
-
- assert.equal(this.module.$('.checkbox.btn').length, 1, 'each item should have the .btn class');
- assert.equal(this.module.$('.checkbox.fa-times').length, 1, 'each item shoud have the .fa-times class');
- });
- });
-
- describe('.newField(element)', function () {
- it('should append a new field to the element', function () {
- var element = document.createElement('div');
- sinon.stub(this.module, 'cloneField').returns(element);
-
- this.module.newField();
-
- assert.ok(jQuery.contains(this.module.el[0], element));
- });
- });
-
- describe('.cloneField(element)', function () {
- it('should clone the provided field', function () {
- var element = document.createElement('div');
- var init = sinon.stub(jQuery.fn, 'init', jQuery.fn.init);
- var clone = sinon.stub(jQuery.fn, 'clone', jQuery.fn.clone);
-
- this.module.cloneField(element);
-
- assert.called(init);
- assert.calledWith(init, element);
- assert.called(clone);
-
- init.restore();
- clone.restore();
- });
-
- it('should return the cloned element', function () {
- var element = document.createElement('div');
- var cloned = document.createElement('div');
- var init = sinon.stub(jQuery.fn, 'init', jQuery.fn.init);
- var clone = sinon.stub(jQuery.fn, 'clone').returns(jQuery(cloned));
-
- assert.ok(this.module.cloneField(element)[0] === cloned);
-
- init.restore();
- clone.restore();
- });
- });
-
- describe('.resetField(element)', function () {
- beforeEach(function () {
- this.field = jQuery('<div><label for="field-1">Field 1</label><input name="field-1" value="value" /></div>');
- });
-
- it('should empty all input values', function () {
- var target = this.module.resetField(this.field);
- assert.equal(target.find(':input').val(), '');
- });
-
- it('should increment any integers in the input names by one', function () {
- var target = this.module.resetField(this.field);
- assert.equal(target.find(':input').attr('name'), 'field-2');
- });
-
- it('should increment any numbers in the label text by one', function () {
- var target = this.module.resetField(this.field);
- assert.equal(target.find('label').text(), 'Field 2');
- });
-
- it('should increment any numbers in the label for by one', function () {
- var target = this.module.resetField(this.field);
- assert.equal(target.find('label').attr('for'), 'field-2');
- });
- });
-
- describe('.disableField(field, disable)', function () {
- beforeEach(function () {
- this.target = this.module.$('.control-custom:first');
- });
-
- it('should add a .disable class to the element', function () {
- this.module.disableField(this.target);
- assert.isTrue(this.target.hasClass('disabled'));
- });
-
- it('should remove a .disable class to the element if disable is false', function () {
- this.target.addClass('disable');
-
- this.module.disableField(this.target, false);
- assert.isFalse(this.target.hasClass('disabled'));
- });
-
- });
-
- describe('._onChange(event)', function () {
- it('should call .newField() with the custom control', function () {
- var target = sinon.stub(this.module, 'newField');
- var field = this.module.$('[name*=key]:last').val('test');
-
- this.module._onChange(jQuery.Event('change', {target: field[0]}));
-
- assert.called(target);
- });
-
- it('should not call .newField() if the target field is empty', function () {
- var target = sinon.stub(this.module, 'newField');
- var field = this.module.$('[name*=key]:last').val('');
-
- this.module._onChange(jQuery.Event('change', {target: field[0]}));
-
- assert.notCalled(target);
- });
- });
-
- describe('._onRemove(event)', function () {
- it('should call .disableField() with the custom control', function () {
- var target = sinon.stub(this.module, 'disableField');
- this.module._onRemove(jQuery.Event('change', {target: this.module.$(':checkbox')[0]}));
-
- assert.called(target);
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/modules/followers-counter.spec.js b/ckan/public-bs2/base/test/spec/modules/followers-counter.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/modules/followers-counter.spec.js
+++ /dev/null
@@ -1,186 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.module.FollowersCounterModule()', function() {
- var FollowersCounterModule = ckan.module.registry['followers-counter'];
-
- beforeEach(function() {
- this.initialCounter = 10;
- this.el = jQuery('<dd><span>' + this.initialCounter + '</span></dd>');
- this.sandbox = ckan.sandbox();
- this.module = new FollowersCounterModule(this.el, {}, this.sandbox);
- this.module.options.num_followers = this.initialCounter;
- });
-
- afterEach(function() {
- this.module.teardown();
- });
-
- describe('.initialize()', function() {
- it('should bind callback methods to the module', function() {
- var target = sinon.stub(jQuery, 'proxyAll');
-
- this.module.initialize();
-
- assert.called(target);
- assert.calledWith(target, this.module, /_on/);
-
- target.restore();
- });
-
- it('should subscribe to the "follow-follow-some-id" event', function() {
- var target = sinon.stub(this.sandbox, 'subscribe');
-
- this.module.options = {id: 'some-id'};
- this.module.initialize();
-
- assert.called(target);
- assert.calledWith(target, 'follow-follow-some-id', this.module._onFollow);
-
- target.restore();
- });
-
- it('should subscribe to the "follow-unfollow-some-id" event', function() {
- var target = sinon.stub(this.sandbox, 'subscribe');
-
- this.module.options = {id: 'some-id'};
- this.module.initialize();
-
- assert.called(target);
- assert.calledWith(target, 'follow-unfollow-some-id', this.module._onUnfollow);
-
- target.restore();
- });
- });
-
- describe('.teardown()', function() {
- it('should unsubscribe to the "follow-follow-some-id" event', function() {
- var target = sinon.stub(this.sandbox, 'unsubscribe');
-
- this.module.options = {id: 'some-id'};
- this.module.initialize();
- this.module.teardown();
-
- assert.called(target);
- assert.calledWith(target, 'follow-follow-some-id', this.module._onFollow);
-
- target.restore();
- });
-
- it('should unsubscribe to the "follow-unfollow-some-id" event', function() {
- var target = sinon.stub(this.sandbox, 'unsubscribe');
-
- this.module.options = {id: 'some-id'};
- this.module.initialize();
- this.module.teardown();
-
- assert.called(target);
- assert.calledWith(target, 'follow-unfollow-some-id', this.module._onUnfollow);
-
- target.restore();
- });
- });
-
- describe('._onFollow', function() {
- it('should call _onFollow on "follow-follow-some-id" event', function() {
- var target = sinon.stub(this.module, '_onFollow');
-
- this.module.options = {id: 'some-id'};
- this.module.initialize();
-
- this.sandbox.publish('follow-follow-some-id');
-
- assert.called(target);
- });
-
- it('should call _updateCounter when ._onFollow is called', function() {
- var target = sinon.stub(this.module, '_updateCounter');
-
- this.module.options = {id: 'some-id'};
- this.module.initialize();
-
- this.module._onFollow();
-
- assert.called(target);
- assert.calledWith(target, {action: 'follow'});
- });
- });
-
- describe('._onUnfollow', function() {
- it('should call _onUnfollow on "follow-unfollow-some-id" event', function() {
- var target = sinon.stub(this.module, '_onUnfollow');
-
- this.module.options = {id: 'some-id'};
- this.module.initialize();
-
- this.sandbox.publish('follow-unfollow-some-id');
-
- assert.called(target);
- });
-
- it('should call _updateCounter when ._onUnfollow is called', function() {
- var target = sinon.stub(this.module, '_updateCounter');
-
- this.module.options = {id: 'some-id'};
- this.module.initialize();
-
- this.module._onUnfollow();
-
- assert.called(target);
- assert.calledWith(target, {action: 'unfollow'});
- });
- });
-
- describe('._updateCounter', function() {
- it('should increment this.options.num_followers on calling _onFollow', function() {
- this.module.initialize();
- this.module._onFollow();
-
- assert.equal(this.module.options.num_followers, ++this.initialCounter);
- });
-
- it('should increment the counter value in the DOM on calling _onFollow', function() {
- var counterVal;
-
- this.module.initialize();
- this.module._onFollow();
-
- counterVal = this.module.counterEl.text();
- counterVal = parseInt(counterVal, 10);
-
- assert.equal(counterVal, ++this.initialCounter);
- });
-
- it('should decrement this.options.num_followers on calling _onUnfollow', function() {
- this.module.initialize();
- this.module._onUnfollow();
-
- assert.equal(this.module.options.num_followers, --this.initialCounter);
- });
-
- it('should decrement the counter value in the DOM on calling _onUnfollow', function() {
- var counterVal;
-
- this.module.initialize();
- this.module._onUnfollow();
-
- counterVal = this.module.counterEl.text();
- counterVal = parseInt(counterVal, 10);
-
- assert.equal(counterVal, --this.initialCounter);
- });
-
- it('should not change the counter value in the DOM when the value is greater than 1000', function() {
- var beforeCounterVal = 1536;
- var afterCounterVal;
-
- this.module.options = {num_followers: beforeCounterVal};
- this.module.initialize();
- this.module.counterEl.text(this.module.options.num_followers);
- this.module._onFollow();
-
- afterCounterVal = this.module.counterEl.text();
- afterCounterVal = parseInt(afterCounterVal, 10);
-
- assert.equal(beforeCounterVal, afterCounterVal);
- });
- });
- });
diff --git a/ckan/public-bs2/base/test/spec/modules/image-upload.spec.js b/ckan/public-bs2/base/test/spec/modules/image-upload.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/modules/image-upload.spec.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.modules.ImageUploadModule()', function () {
- var ImageUploadModule = ckan.module.registry['image-upload'];
-
- beforeEach(function () {
- this.el = document.createElement('div');
- this.sandbox = ckan.sandbox();
- this.module = new ImageUploadModule(this.el, {}, this.sandbox);
- this.module.el.html([
- '<div class="control-group"><input name="image_url" /></div>',
- '<input name="image_upload" />',
- ]);
- this.module.initialize();
- this.module.field_name = jQuery('<input>', {type: 'text'})
- });
-
- afterEach(function () {
- this.module.teardown();
- });
-
- describe('._onFromWeb()', function () {
-
- it('should change name when url changed', function () {
- this.module.field_url_input.val('http://example.com/some_image.png');
- this.module._onFromWebBlur();
- assert.equal(this.module.field_name.val(), 'some_image.png');
-
- this.module.field_url_input.val('http://example.com/undefined_file');
- this.module._onFromWebBlur();
- assert.equal(this.module.field_name.val(), 'undefined_file');
- });
-
- it('should ignore url changes if name was manualy changed', function () {
- this.module.field_url_input.val('http://example.com/some_image.png');
- this.module._onFromWebBlur();
- assert.equal(this.module.field_name.val(), 'some_image.png');
-
- this.module._onModifyName();
-
- this.module.field_url_input.val('http://example.com/undefined_file');
- this.module._onFromWebBlur();
- assert.equal(this.module.field_name.val(), 'some_image.png');
- });
-
- it('should ignore url changes if name was filled before', function () {
- this.module._nameIsDirty = true;
- this.module.field_name.val('prefilled');
-
- this.module.field_url_input.val('http://example.com/some_image.png');
- this.module._onFromWebBlur();
- assert.equal(this.module.field_name.val(), 'prefilled');
-
- this.module.field_url_input.val('http://example.com/second_some_image.png');
- this.module._onFromWebBlur();
- assert.equal(this.module.field_name.val(), 'prefilled');
-
- this.module._onModifyName()
-
- this.module.field_url_input.val('http://example.com/undefined_file');
- this.module._onFromWebBlur();
- assert.equal(this.module.field_name.val(), 'prefilled');
- });
- });
-
-});
diff --git a/ckan/public-bs2/base/test/spec/modules/resource-form.spec.js b/ckan/public-bs2/base/test/spec/modules/resource-form.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/modules/resource-form.spec.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.modules.ResourceFormModule()', function () {
- var ResourceFormModule = ckan.module.registry['resource-form'];
-
- beforeEach(function () {
- this.el = document.createElement('form');
- this.sandbox = ckan.sandbox();
- this.module = new ResourceFormModule(this.el, {}, this.sandbox);
- });
-
- afterEach(function () {
- this.module.teardown();
- });
-
- describe('.initialize()', function () {
- it('should subscribe to the "resource:uploaded" event', function () {
- var target = sinon.stub(this.sandbox, 'subscribe');
-
- this.module.initialize();
-
- assert.called(target);
- assert.calledWith(target, 'resource:uploaded', this.module._onResourceUploaded);
-
- target.restore();
- });
- });
-
- describe('.teardown()', function () {
- it('should unsubscribe from the "resource:uploaded" event', function () {
- var target = sinon.stub(this.sandbox, 'unsubscribe');
-
- this.module.teardown();
-
- assert.called(target);
- assert.calledWith(target, 'resource:uploaded', this.module._onResourceUploaded);
-
- target.restore();
- });
- });
-
- describe('._onResourceUploaded()', function () {
- beforeEach(function () {
- this.module.el.html([
- '<input type="text" name="text" />',
- '<input type="checkbox" name="checkbox" value="check" />',
- '<input type="radio" name="radio" value="radio1" />',
- '<input type="radio" name="radio" value="radio2" />',
- '<input type="hidden" name="hidden" />',
- '<select name="select">',
- '<option value="option1" />',
- '<option value="option2" />',
- '</select>'
- ].join(''));
-
- this.resource = {
- text: 'text',
- checkbox: "check",
- radio: "radio2",
- hidden: "hidden",
- select: "option1"
- };
- });
-
- it('should set the values on appropriate fields', function () {
- var res = this.resource;
-
- this.module._onResourceUploaded(res);
-
- jQuery.each(this.module.el.serializeArray(), function (idx, field) {
- assert.equal(field.value, res[field.name]);
- });
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/modules/resource-upload-field.spec.js b/ckan/public-bs2/base/test/spec/modules/resource-upload-field.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/modules/resource-upload-field.spec.js
+++ /dev/null
@@ -1,290 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.modules.ResourceUploadFieldModule()', function () {
- var ResourceFileUploadModule = ckan.module.registry['resource-upload-field'];
-
- beforeEach(function () {
- jQuery.fn.fileupload = sinon.spy();
-
- this.el = jQuery('<form />');
- this.sandbox = ckan.sandbox();
- this.module = new ResourceFileUploadModule(this.el, {}, this.sandbox);
- this.module.initialize();
- });
-
- afterEach(function () {
- this.module.teardown();
- });
-
- describe('.initialize()', function () {
- beforeEach(function () {
- // Create un-initialised module.
- this.module.teardown();
- this.module = new ResourceFileUploadModule(this.el, {}, this.sandbox);
- });
-
- it('should create the #upload field', function () {
- this.module.initialize();
- assert.ok(typeof this.module.upload === 'object');
- });
-
- it('should append the upload field to the module element', function () {
- this.module.initialize();
-
- assert.ok(jQuery.contains(this.el[0], this.module.upload[0]));
- });
-
- it('should call .setupFileUpload()', function () {
- var target = sinon.stub(this.module, 'setupFileUpload');
-
- this.module.initialize();
-
- assert.called(target);
- });
- });
-
- describe('.setupFileUpload()', function () {
- it('should set the label text on the form input', function () {
- this.module.initialize();
- this.module.setupFileUpload();
-
- assert.equal(this.module.upload.find('label').text(), 'Upload a file');
- });
-
- it('should setup the file upload with relevant options', function () {
- this.module.initialize();
- this.module.setupFileUpload();
-
- assert.called(jQuery.fn.fileupload);
- assert.calledWith(jQuery.fn.fileupload, {
- type: 'POST',
- paramName: 'file',
- forceIframeTransport: true, // Required for XDomain request.
- replaceFileInput: true,
- autoUpload: false,
- add: this.module._onUploadAdd,
- send: this.module._onUploadSend,
- done: this.module._onUploadDone,
- fail: this.module._onUploadFail,
- always: this.module._onUploadComplete
- });
- });
- });
-
- describe('.loading(show)', function () {
- it('should add a loading class to the upload element', function () {
- this.module.loading();
-
- assert.ok(this.module.upload.hasClass('loading'));
- });
-
- it('should remove the loading class if false is passed as an argument', function () {
- this.module.upload.addClass('loading');
- this.module.loading();
-
- assert.ok(!this.module.upload.hasClass('loading'));
- });
- });
-
- describe('.authenticate(key, data)', function () {
- beforeEach(function () {
- this.fakeThen = sinon.spy();
- this.fakeProxy = sinon.stub(jQuery, 'proxy').returns('onsuccess');
-
- this.target = sinon.stub(this.sandbox.client, 'getStorageAuth');
- this.target.returns({
- then: this.fakeThen
- });
- });
-
- afterEach(function () {
- jQuery.proxy.restore();
- });
-
- it('should request authentication for the upload', function () {
- this.module.authenticate('test', {});
- assert.called(this.target);
- assert.calledWith(this.target, 'test');
- });
-
- it('should register success and error callbacks', function () {
- this.module.authenticate('test', {});
- assert.called(this.fakeThen);
- assert.calledWith(this.fakeThen, 'onsuccess', this.module._onAuthError);
- });
-
- it('should save the key on the data object', function () {
- var data = {};
-
- this.module.authenticate('test', data);
-
- assert.equal(data.key, 'test');
- });
- });
-
- describe('.lookupMetadata(key, data)', function () {
- beforeEach(function () {
- this.fakeThen = sinon.spy();
- this.fakeProxy = sinon.stub(jQuery, 'proxy').returns('onsuccess');
-
- this.target = sinon.stub(this.sandbox.client, 'getStorageMetadata');
- this.target.returns({
- then: this.fakeThen
- });
- });
-
- afterEach(function () {
- jQuery.proxy.restore();
- });
-
- it('should request metadata for the upload key', function () {
- this.module.lookupMetadata('test', {});
- assert.called(this.target);
- assert.calledWith(this.target, 'test');
- });
-
- it('should register success and error callbacks', function () {
- this.module.lookupMetadata('test', {});
- assert.called(this.fakeThen);
- assert.calledWith(this.fakeThen, 'onsuccess', this.module._onMetadataError);
- });
- });
-
- describe('.notify(message, type)', function () {
- it('should call the sandbox.notify() method', function () {
- var target = sinon.stub(this.sandbox, 'notify');
-
- this.module.notify('this is an example message', 'info');
-
- assert.called(target);
- assert.calledWith(target, 'An Error Occurred', 'this is an example message', 'info');
- });
- });
-
- describe('.generateKey(file)', function () {
- it('should generate a unique filename prefixed with a timestamp', function () {
- var now = new Date();
- var date = jQuery.date.toISOString(now);
- var clock = sinon.useFakeTimers(now.getTime());
- var target = this.module.generateKey('this is my file.png');
-
- assert.equal(target, date + '/this-is-my-file.png');
-
- clock.restore();
- });
- });
-
- describe('._onUploadAdd(event, data)', function () {
- beforeEach(function () {
- this.target = sinon.stub(this.module, 'authenticate');
- sinon.stub(this.module, 'generateKey').returns('stubbed');
- });
-
- it('should authenticate the upload if a file is provided', function () {
- var data = {files: [{name: 'my_file.jpg'}]};
- this.module._onUploadAdd({}, data);
-
- assert.called(this.target);
- assert.calledWith(this.target, 'stubbed', data);
- });
-
- it('should not authenticate the upload if no file is provided', function () {
- var data = {files: []};
- this.module._onUploadAdd({}, data);
-
- assert.notCalled(this.target);
- });
- });
-
- describe('._onUploadSend()', function () {
- it('should display the loading spinner', function () {
- var target = sinon.stub(this.module, 'loading');
- this.module._onUploadSend({}, {});
-
- assert.called(target);
- });
- });
-
- describe('._onUploadDone()', function () {
- it('should request the metadata for the file', function () {
- var target = sinon.stub(this.module, 'lookupMetadata');
- this.module._onUploadDone({}, {result: {}});
-
- assert.called(target);
- });
-
- it('should call the fail handler if the "result" key in the data is undefined', function () {
- var target = sinon.stub(this.module, '_onUploadFail');
- this.module._onUploadDone({}, {result: undefined});
-
- assert.called(target);
- });
-
- it('should call the fail handler if the "result" object has an "error" key', function () {
- var target = sinon.stub(this.module, '_onUploadFail');
- this.module._onUploadDone({}, {result: {error: 'failed'}});
-
- assert.called(target);
- });
- });
-
- describe('._onUploadComplete()', function () {
- it('should hide the loading spinner', function () {
- var target = sinon.stub(this.module, 'loading');
- this.module._onUploadComplete({}, {});
-
- assert.called(target);
- assert.calledWith(target, false);
- });
- });
-
- describe('._onAuthSuccess()', function () {
- beforeEach(function () {
- this.target = {
- submit: sinon.spy()
- };
-
- this.response = {
- action: 'action',
- fields: [{name: 'name', value: 'value'}]
- };
- });
-
- it('should set the data url', function () {
- this.module._onAuthSuccess(this.target, this.response);
-
- assert.equal(this.target.url, this.response.action);
- });
-
- it('should set the additional form data', function () {
- this.module._onAuthSuccess(this.target, this.response);
-
- assert.deepEqual(this.target.formData, this.response.fields);
- });
-
- it('should merge the form data with the options', function () {
- this.module.options.form.params = [{name: 'option', value: 'option'}];
- this.module._onAuthSuccess(this.target, this.response);
-
- assert.deepEqual(this.target.formData, [{name: 'option', value: 'option'}, {name: 'name', value: 'value'}]);
- });
-
- it('should call data.submit()', function () {
- this.module._onAuthSuccess(this.target, this.response);
- assert.called(this.target.submit);
- });
- });
-
- describe('._onMetadataSuccess()', function () {
- it('should publish the "resource:uploaded" event', function () {
- var resource = {url: 'http://', name: 'My File'};
- var target = sinon.stub(this.sandbox, 'publish');
-
- sinon.stub(this.sandbox.client, 'convertStorageMetadataToResource').returns(resource);
-
- this.module._onMetadataSuccess();
-
- assert.called(target);
- assert.calledWith(target, "resource:uploaded", resource);
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/notify.spec.js b/ckan/public-bs2/base/test/spec/notify.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/notify.spec.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.notify()', function () {
- beforeEach(function () {
- this.element = jQuery('<div />');
- this.fixture.append(this.element);
-
- ckan.notify.el = this.element;
- });
-
- it('should append a notification to the element', function () {
- ckan.notify('test');
- assert.equal(this.element.children().length, 1, 'should be one child');
- ckan.notify('test');
- assert.equal(this.element.children().length, 2, 'should be two children');
- });
-
- it('should append a notification title', function () {
- ckan.notify('test');
- assert.equal(this.element.find('strong').text(), 'test');
- });
-
- it('should append a notification body', function () {
- ckan.notify('test', 'this is a message');
- assert.equal(this.element.find('span').text(), 'this is a message');
- });
-
- it('should escape all content', function () {
- ckan.notify('<script>', '<script>');
- assert.equal(this.element.find('strong').html(), '<script>');
- assert.equal(this.element.find('span').html(), '<script>');
- });
-
- it('should default the class to "alert-error"', function () {
- ckan.notify('test');
- assert.ok(this.element.find('.alert').hasClass('alert-error'));
- });
-
- it('should allow a type to be provided', function () {
- ckan.notify('test', '', 'info');
- assert.ok(this.element.find('.alert').hasClass('alert-info'));
- });
-
- it('should add itself to the ckan.sandbox()', function () {
- assert.equal(ckan.sandbox().notify, ckan.notify);
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/plugins/jquery.date-helpers.spec.js b/ckan/public-bs2/base/test/spec/plugins/jquery.date-helpers.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/plugins/jquery.date-helpers.spec.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('jQuery.date', function () {
- beforeEach(function () {
- this.now = new Date();
- this.now.setTime(0);
-
- this.clock = sinon.useFakeTimers(this.now.getTime());
- });
-
- afterEach(function () {
- this.clock.restore();
- });
-
- describe('jQuery.date.format()', function () {
- it('should format the date based on the string provided', function () {
- var target = jQuery.date.format('yyyy-MM-dd', this.now);
- assert.equal(target, '1970-01-01');
- });
-
- it('should use the current time if none provided', function () {
- var target = jQuery.date.format('yyyy/MM/dd');
- assert.equal(target, '1970/01/01');
- });
- });
-
- describe('jQuery.date.toISOString()', function () {
- it('should output an ISO8601 compatible string', function () {
- var target = jQuery.date.toISOString(this.now);
- assert.equal(target, '1970-01-01T00:00:00.000Z');
- });
-
- it('should use the current time if none provided', function () {
- var target = jQuery.date.toISOString();
- assert.equal(target, '1970-01-01T00:00:00.000Z');
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/plugins/jquery.form-warning.spec.js b/ckan/public-bs2/base/test/spec/plugins/jquery.form-warning.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/plugins/jquery.form-warning.spec.js
+++ /dev/null
@@ -1,42 +0,0 @@
-describe('jQuery.incompleteFormWarning()', function () {
- beforeEach(function () {
- this.el = jQuery('<form />').appendTo(this.fixture);
- this.el.on('submit', false);
-
- this.input1 = jQuery('<input name="input1" value="a" />').appendTo(this.el);
- this.input2 = jQuery('<input name="input2" value="b" />').appendTo(this.el);
-
- this.el.incompleteFormWarning('my message');
-
- this.on = sinon.stub(jQuery.fn, 'on');
- this.off = sinon.stub(jQuery.fn, 'off');
- });
-
- afterEach(function () {
- this.on.restore();
- this.off.restore();
- });
-
- it('should bind a beforeunload event when the form changes', function () {
- this.input1.val('c');
- this.el.change();
-
- assert.called(this.on);
- });
-
- it('should unbind a beforeunload event when a form returns to the original state', function () {
- this.input1.val('c');
- this.el.change();
-
- this.input1.val('a');
- this.el.change();
-
- assert.called(this.off);
- });
-
- it('should unbind the beforeunload event when the form is submitted', function () {
- this.el.submit();
-
- assert.called(this.off);
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/plugins/jquery.inherit.spec.js b/ckan/public-bs2/base/test/spec/plugins/jquery.inherit.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/plugins/jquery.inherit.spec.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('jQuery.inherit()', function () {
- beforeEach(function () {
- this.MyClass = function MyClass() {};
- this.MyClass.static = function () {};
- this.MyClass.prototype.method = function () {};
- });
-
- it('should create a subclass of the constructor provided', function () {
- var target = new (jQuery.inherit(this.MyClass))();
- assert.isTrue(target instanceof this.MyClass);
- });
-
- it('should set the childs prototype object', function () {
- var target = new (jQuery.inherit(this.MyClass))();
- assert.isFunction(target.method);
- });
-
- it('should copy over the childs static properties', function () {
- var Target = jQuery.inherit(this.MyClass);
- assert.isFunction(Target.static);
- });
-
- it('should allow instance properties to be overridden', function () {
- function method() {}
-
- var target = new (jQuery.inherit(this.MyClass, {method: method}))();
- assert.equal(target.method, method);
- });
-
- it('should allow static properties to be overridden', function () {
- function staticmethod() {}
-
- var Target = jQuery.inherit(this.MyClass, {}, {static: staticmethod});
- assert.equal(Target.static, staticmethod);
- });
-
- it('should allow a custom constructor to be provided', function () {
- var MyConstructor = sinon.spy();
- var Target = jQuery.inherit(this.MyClass, {constructor: MyConstructor});
-
- new Target();
-
- sinon.assert.called(MyConstructor);
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/plugins/jquery.proxy-all.spec.js b/ckan/public-bs2/base/test/spec/plugins/jquery.proxy-all.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/plugins/jquery.proxy-all.spec.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/*globals describe it beforeEach afterEach jQuery sinon assert */
-describe('jQuery.proxyAll(obj, args...)', function () {
- beforeEach(function () {
- this.proxy = sinon.stub(jQuery, 'proxy').returns(function proxied() {});
- this.target = {
- prop1: '',
- method1: function method1() {},
- method2: function method2() {},
- method3: function method3() {}
- };
-
- this.cloned = jQuery.extend({}, this.target);
- });
-
- afterEach(function () {
- this.proxy.restore();
- });
-
- it('should bind the methods provided to the object', function () {
- jQuery.proxyAll(this.target, 'method1', 'method2');
-
- assert.called(this.proxy);
-
- assert.calledWith(this.proxy, this.cloned.method1, this.target);
- assert.calledWith(this.proxy, this.cloned.method2, this.target);
- assert.neverCalledWith(this.proxy, this.cloned.method3, this.target);
- });
-
- it('should allow regular expressions to be provided', function () {
- jQuery.proxyAll(this.target, /method[1-2]/);
-
- assert.called(this.proxy);
-
- assert.calledWith(this.proxy, this.cloned.method1, this.target);
- assert.calledWith(this.proxy, this.cloned.method2, this.target);
- assert.neverCalledWith(this.proxy, this.cloned.method3, this.target);
- });
-
- it('should skip properties that are not functions', function () {
- jQuery.proxyAll(this.target, 'prop1');
- assert.notCalled(this.proxy);
- });
-
- it('should not bind function more than once', function () {
- jQuery.proxyAll(this.target, 'method1');
- jQuery.proxyAll(this.target, 'method1');
-
- assert.calledOnce(this.proxy);
- });
-
- it('should not bind function more than once if the method name is passed twice', function () {
- jQuery.proxyAll(this.target, 'method1', 'method1');
-
- assert.calledOnce(this.proxy);
- });
-
- it('should return the first argument', function () {
- assert.equal(jQuery.proxyAll(this.target), this.target);
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/plugins/jquery.slug-preview.spec.js b/ckan/public-bs2/base/test/spec/plugins/jquery.slug-preview.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/plugins/jquery.slug-preview.spec.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/*globals describe it assert jQuery*/
-describe('jQuery.fn.slugPreview()', function () {
- beforeEach(function () {
- this.element = jQuery('<div><input /></div>');
- });
-
- it('should return the preview element', function () {
- var target = this.element.slugPreview();
- assert.ok(target.hasClass('slug-preview'));
- });
-
- it('should restore the stack when .end() is called', function () {
- var target = this.element.slugPreview();
- assert.ok(target.end() === this.element);
- });
-
- it('should allow a prefix to be provided', function () {
- var target = this.element.slugPreview({prefix: 'prefix'});
- assert.equal(target.find('.slug-preview-prefix').text(), 'prefix');
- });
-
- it('should allow a placeholder to be provided', function () {
- var target = this.element.slugPreview({placeholder: 'placeholder'});
- assert.equal(target.find('.slug-preview-value').text(), 'placeholder');
- });
-
- it('should allow translations for strings to be provided', function () {
- var target = this.element.slugPreview({
- i18n: {'Edit': 'translated'}
- });
- assert.equal(target.find('button').text(), 'translated');
- });
-
- it('should set preview value to the initial value of the input', function () {
- var input = this.element.find('input').val('initial');
- var target = this.element.slugPreview();
-
- assert.equal(target.find('.slug-preview-value').text(), 'initial');
- });
-
- it('should update the preview value when the target input changes', function () {
- var target = this.element.slugPreview();
- var input = this.element.find('input').val('initial');
-
- input.val('updated').change();
- assert.equal(target.find('.slug-preview-value').text(), 'updated');
- });
-
- it('should hide the original element', function () {
- var target = this.element.slugPreview();
- assert.ok(this.element.css('display') === 'none');
- });
-
- it('should show the original element when Edit is clicked', function () {
- var target = this.element.slugPreview();
- target.find('button').click();
- assert.ok(this.element.css('display') === '');
- });
-
- it('should hide the preview element when Edit is clicked', function () {
- var target = this.element.slugPreview();
- target.find('button').click();
- assert.ok(target.css('display') === 'none');
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/plugins/jquery.slug.spec.js b/ckan/public-bs2/base/test/spec/plugins/jquery.slug.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/plugins/jquery.slug.spec.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/*globals beforeEach describe it assert jQuery*/
-describe('jQuery.fn.slug()', function () {
- beforeEach(function () {
- this.input = jQuery('<input />').slug();
- this.fixture.append(this.input);
- });
-
- it('should slugify and append the pressed key', function () {
- var e = jQuery.Event('keypress', {charCode: 97 /* a */});
- this.input.trigger(e);
-
- assert.equal(this.input.val(), 'a', 'append an "a"');
-
- e = jQuery.Event('keypress', {charCode: 38 /* & */});
- this.input.trigger(e);
-
- assert.equal(this.input.val(), 'a-', 'append an "-"');
- });
-
- it('should do nothing if a non character key is pressed', function () {
- var e = jQuery.Event('keypress', {charCode: 0});
- this.input.val('some other string').trigger(e);
-
- assert.equal(this.input.val(), 'some other string');
- });
-
- it('should slugify the input contents on "blur" and "change" events', function () {
- this.input.val('apples & pears').trigger(jQuery.Event('blur'));
- assert.equal(this.input.val(), 'apples-pears', 'on blur');
-
- this.input.val('apples & pears').trigger(jQuery.Event('change'));
- assert.equal(this.input.val(), 'apples-pears', 'on change');
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/plugins/jquery.url-helpers.spec.js b/ckan/public-bs2/base/test/spec/plugins/jquery.url-helpers.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/plugins/jquery.url-helpers.spec.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/*globals describe it assert jQuery*/
-describe('jQuery.url', function () {
- describe('.escape()', function () {
- it('should escape special characters', function () {
- var target = jQuery.url.escape('&<>=?#/');
- assert.equal(target, '%26%3C%3E%3D%3F%23%2F');
- });
-
- it('should convert spaces to + rather than %20', function () {
- var target = jQuery.url.escape(' ');
- assert.equal(target, '+');
- });
- });
-
- describe('.slugify()', function () {
- it('should replace spaces with hyphens', function () {
- var target = jQuery.url.slugify('apples and pears');
- assert.equal(target, 'apples-and-pears');
- });
-
- it('should lowecase all characters', function () {
- var target = jQuery.url.slugify('APPLES AND PEARS');
- assert.equal(target, 'apples-and-pears');
- });
-
- it('should convert unknown characters to hyphens', function () {
- var target = jQuery.url.slugify('apples & pears');
- assert.equal(target, 'apples-pears');
- });
-
- it('should nomalise hyphens', function () {
- var target = jQuery.url.slugify('apples---pears');
- assert.equal(target, 'apples-pears', 'remove duplicate hyphens');
-
- target = jQuery.url.slugify('--apples-pears');
- assert.equal(target, 'apples-pears', 'strip preceding hyphens');
-
- target = jQuery.url.slugify('apples-pears--');
- assert.equal(target, 'apples-pears', 'strip trailing hyphens');
- });
-
- it('should try and asciify unicode characters', function () {
- var target = jQuery.url.slugify('éåøç');
- assert.equal(target, 'eaoc');
- });
-
- it('should allow underscore characters', function() {
- var target = jQuery.url.slugify('apples_pears');
- assert.equal(target, 'apples_pears');
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/pubsub.spec.js b/ckan/public-bs2/base/test/spec/pubsub.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/pubsub.spec.js
+++ /dev/null
@@ -1,92 +0,0 @@
-describe('ckan.pubsub', function () {
- beforeEach(function () {
- ckan.pubsub.events = jQuery({});
- ckan.pubsub.queue = [];
- });
-
- describe('.enqueue()', function () {
- beforeEach(function () {
- this.target = sinon.spy();
- });
-
- it('should defer callbacks for published events until later', function () {
- ckan.pubsub.subscribe('change', this.target);
- ckan.pubsub.enqueue();
- ckan.pubsub.publish('change');
-
- assert.notCalled(this.target);
- });
-
- it('should add the published calls to the .queue', function () {
- var queue = ckan.pubsub.queue;
-
- ckan.pubsub.enqueue();
-
- ckan.pubsub.publish('change');
- assert.equal(queue.length, 1);
-
- ckan.pubsub.publish('change');
- assert.equal(queue.length, 2);
-
- ckan.pubsub.publish('change');
- assert.equal(queue.length, 3);
- });
- });
-
- describe('.dequeue()', function () {
- beforeEach(function () {
- ckan.pubsub.queue = [
- ['change'],
- ['change', 'arg1', 'arg2'],
- ['update', 'arg1']
- ];
-
- this.target1 = sinon.spy();
- this.target2 = sinon.spy();
- this.target3 = sinon.spy();
-
- ckan.pubsub.subscribe('change', this.target1);
- ckan.pubsub.subscribe('change', this.target2);
- ckan.pubsub.subscribe('update', this.target3);
- });
-
- it('should publish all queued callbacks', function () {
- ckan.pubsub.dequeue();
-
- assert.calledTwice(this.target1);
- assert.calledWith(this.target1, 'arg1', 'arg2');
-
- assert.calledTwice(this.target2);
- assert.calledWith(this.target2, 'arg1', 'arg2');
-
- assert.calledOnce(this.target3);
- });
-
- it('should set the queue to null to allow new events to be published', function () {
- ckan.pubsub.dequeue();
- assert.isNull(ckan.pubsub.queue);
- });
-
- it('should not block new events from being published', function () {
- var pubsub = ckan.pubsub;
-
- var second = sinon.spy();
- var third = sinon.spy();
-
- pubsub.enqueue();
- pubsub.subscribe('first', function () {
- pubsub.publish('third');
- });
- pubsub.subscribe('second', second);
- pubsub.subscribe('third', third);
-
- pubsub.publish('first');
- pubsub.publish('second');
-
- pubsub.dequeue();
-
- assert.called(second);
- assert.called(third);
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/spec/sandbox.spec.js b/ckan/public-bs2/base/test/spec/sandbox.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/sandbox.spec.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/*globals describe beforeEach afterEach it assert sinon ckan jQuery */
-describe('ckan.sandbox()', function () {
- it('should create an instance of Sandbox', function () {
- var target = sinon.stub(ckan.sandbox, 'Sandbox');
- ckan.sandbox();
- sinon.assert.called(target);
- target.restore();
- });
-
- it('should pass in sandbox.callbacks', function () {
- var target = sinon.stub(ckan.sandbox, 'Sandbox');
- ckan.sandbox();
- sinon.assert.calledWith(target, ckan.sandbox.callbacks);
- target.restore();
- });
-
- describe('Sandbox()', function () {
- var Sandbox = ckan.sandbox.Sandbox;
-
- beforeEach(function () {
- });
-
- it('should call each callback provided with itself', function () {
- var callbacks = [sinon.spy(), sinon.spy(), sinon.spy()];
-
- var target = new Sandbox(callbacks);
-
- jQuery.each(callbacks, function () {
- sinon.assert.called(this);
- sinon.assert.calledWith(this, target);
- });
- });
-
- describe('.ajax()', function () {
- it('should be an alias for the jQuery.ajax() method', function () {
- var target = new Sandbox();
- assert.strictEqual(target.ajax, jQuery.ajax);
- });
- });
-
- describe('.jQuery()', function () {
- it('should be a reference to jQuery', function () {
- var target = new Sandbox();
- assert.ok(target.jQuery === jQuery);
- });
- });
-
- describe('.body', function () {
- it('should be a jQuery wrapped body object', function () {
- var target = new Sandbox();
- assert.ok(target.body instanceof jQuery);
- assert.ok(target.body[0] === window.document.body);
- });
- });
-
- describe('.location', function () {
- it('should be a reference to window.location', function () {
- var target = new Sandbox();
- assert.ok(target.location === window.location);
- });
- });
-
- describe('.window', function () {
- it('should be a reference to window', function () {
- var target = new Sandbox();
- assert.ok(target.window === window);
- });
- });
-
- describe('.i18n', function () {
- it('should be available while being deprecated', function () {
- var target = new Sandbox();
- assert.equal(target.i18n, ckan.i18n);
- });
- });
-
- describe('.translate', function () {
- it('should be available while being deprecated', function () {
- var target = new Sandbox();
- assert.equal(target.translate, ckan.i18n.translate);
- });
- });
- });
-
- describe('sandbox.extend()', function () {
- it('should extend the Sandbox.prototype with properties', function () {
- var method = sinon.spy();
-
- ckan.sandbox.extend({method: method});
-
- assert.equal(ckan.sandbox().method, method);
- });
- });
-
- describe('sandbox.setup()', function () {
- it('should register a function to be called when the sandbox is initialized', function () {
- var target = sinon.spy();
-
- ckan.sandbox.setup(target);
- ckan.sandbox();
-
- sinon.assert.called(target);
- });
-
- it('should throw an error if a non function is provided', function () {
- assert.throws(function () {
- ckan.sandbox.setup('not a function');
- });
- });
- });
-
-});
diff --git a/ckan/public-bs2/base/test/spec/view-filters.spec.js b/ckan/public-bs2/base/test/spec/view-filters.spec.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/spec/view-filters.spec.js
+++ /dev/null
@@ -1,233 +0,0 @@
-describe('ckan.views.filters', function(){
- var filters = ckan.views.filters,
- setLocationHrefSpy;
-
- function _currentHref() {
- return setLocationHrefSpy.args[setLocationHrefSpy.args.length-1][0];
- }
-
- beforeEach(function() {
- filters._initialize('');
- setLocationHrefSpy = sinon.spy();
- filters._setLocationHref = setLocationHrefSpy;
- });
-
- describe('#initialization', function() {
- it('should clear the filters on subsequent calls', function() {
- filters._initialize('?filters=country:Brazil');
- assert.deepEqual(['Brazil'], filters.get('country'));
- filters._initialize('');
- assert.equal(undefined, filters.get('country'));
- });
-
- it('should work with multiple filters', function() {
- var expectedFilters = {
- country: ['Brazil'],
- state: ['Paraiba']
- };
-
- filters._initialize('?filters=country:Brazil|state:Paraiba');
-
- assert.deepEqual(expectedFilters, filters.get());
- });
-
- it('should work with multiple values for the same filter', function() {
- var expectedFilters = {
- country: ['Brazil', 'Argentina'],
- state: ['Paraiba']
- };
-
- filters._initialize('?filters=country:Brazil|state:Paraiba|country:Argentina');
-
- assert.deepEqual(expectedFilters, filters.get());
- });
-
- it('should keep the order defined in the query string', function() {
- var expectedFiltersSorted = {
- country: ['Argentina', 'Brazil']
- },
- expectedFiltersReverse = {
- country: ['Brazil', 'Argentina']
- };
-
- filters._initialize('?filters=country:Argentina|country:Brazil');
- assert.deepEqual(expectedFiltersSorted, filters.get());
-
- filters._initialize('?filters=country:Brazil|country:Argentina');
- assert.deepEqual(expectedFiltersReverse, filters.get());
- });
-
- it('should work with a single numeric filter', function() {
- var expectedFilters = {
- year: ['2014']
- };
-
- filters._initialize('?filters=year:2014');
- assert.deepEqual(expectedFilters, filters.get());
- });
-
- it('should work with quoted filters', function() {
- var expectedFilters = {
- country: ['"Brazil"']
- };
-
- filters._initialize('?filters=country:"Brazil"');
- assert.deepEqual(expectedFilters, filters.get());
- });
-
- it('should work with filters with colons', function() {
- var expectedFilters = {
- time: ['11:00', '']
- };
-
- filters._initialize('?filters=time:11:00|time:');
- assert.deepEqual(expectedFilters, filters.get());
- });
- });
-
- describe('#get', function(){
- it('should return all filters if called without params', function(){
- var expectedFilters = {
- country: ['Brazil']
- };
-
- filters._initialize('?filters=country:Brazil');
-
- assert.deepEqual(expectedFilters, filters.get());
- });
-
- it('should return the requested filter field', function(){
- var countryFilter;
-
- filters._initialize('?filters=country:Brazil');
-
- countryFilter = filters.get('country');
-
- assert.equal(1, countryFilter.length);
- assert.equal('Brazil', countryFilter[0]);
- });
-
- it('should return an empty object if there\'re no filters', function(){
- filters._initialize('');
-
- assert.deepEqual({}, filters.get());
- });
-
- it('should return undefined if there\'s no filter with the requested field', function(){
- var cityFilter;
- filters._initialize('?filters=country:Brazil');
-
- cityFilter = filters.get('city');
-
- assert.equal(undefined, cityFilter);
- });
- });
-
- describe('#set', function(){
- it('should set the filters', function(){
- var expectedFilters = {
- country: 'Brazil'
- };
-
- filters.set('country', 'Brazil');
-
- assert.deepEqual(expectedFilters, filters.get());
- });
-
- it('should update the url', function(){
- var expectedSearch = '?filters=country%3ABrazil%7Ccountry%3AArgentina' +
- '%7Cindicator%3Ahappiness';
-
- filters.set('country', ['Brazil', 'Argentina']);
- filters.set('indicator', 'happiness');
-
- assert.include(_currentHref(), expectedSearch);
- });
- });
-
- describe('#setAndRedirectTo', function(){
- it('should set the filters', function(){
- var url = 'http://www.ckan.org',
- expectedFilters = {
- country: 'Brazil'
- };
-
- filters.setAndRedirectTo('country', 'Brazil', 'http://www.ckan.org');
-
- assert.deepEqual(expectedFilters, filters.get());
- });
-
- it('should update the url', function(){
- var url = 'http://www.ckan.org',
- expectedSearch = '?filters=country%3ABrazil%7Ccountry%3AArgentina' +
- '%7Cindicator%3Ahappiness';
-
- filters.setAndRedirectTo('country', ['Brazil', 'Argentina'], url);
- filters.setAndRedirectTo('indicator', 'happiness', url);
-
- assert.include(_currentHref(), expectedSearch);
- });
-
- it('should keep the original url\'s query params', function(){
- var url = 'http://www.ckan.org/?id=42',
- expectedSearch = '?id=42&filters=country%3ABrazil%7Ccountry%3AArgentina' +
- '%7Cindicator%3Ahappiness';
-
- filters.setAndRedirectTo('country', ['Brazil', 'Argentina'], url);
- filters.setAndRedirectTo('indicator', 'happiness', url);
-
- assert.include(_currentHref(), expectedSearch);
- });
-
- it('should override the original url\'s filters', function(){
- var url = 'http://www.ckan.org/?filters=country%3AEngland%7Cyear%3A2014',
- expectedSearch = '?filters=country%3ABrazil%7Ccountry%3AArgentina' +
- '%7Cindicator%3Ahappiness';
-
- filters.setAndRedirectTo('country', ['Brazil', 'Argentina'], url);
- filters.setAndRedirectTo('indicator', 'happiness', url);
-
- assert.include(_currentHref(), expectedSearch);
- });
- });
-
- describe('#unset', function(){
- it('should unset the filters', function(){
- var expectedFilters = {};
- filters.set('country', 'Brazil');
-
- filters.unset('country', 'Brazil');
-
- assert.deepEqual(expectedFilters, filters.get());
- });
-
- it('should unset the filters when we unset every filter activated', function(){
- var expectedFilters = {};
- filters.set('country', ['Brazil', 'Argentina']);
-
- filters.unset('country', ['Brazil', 'Argentina']);
-
- assert.deepEqual(expectedFilters, filters.get());
- });
-
- it('should work with arrays', function(){
- var expectedFilters = {
- country: ['Argentina']
- };
- filters.set('country', ['Brazil', 'Argentina', 'Uruguay']);
-
- filters.unset('country', ['Brazil', 'Uruguay']);
-
- assert.deepEqual(expectedFilters, filters.get());
- });
-
- it('should update the url', function(){
- var expectedSearch = '?filters=country%3AArgentina';
- filters.set('country', ['Brazil', 'Argentina']);
-
- filters.unset('country', 'Brazil');
-
- assert.include(_currentHref(), expectedSearch);
- });
- });
-});
diff --git a/ckan/public-bs2/base/test/vendor/chai.js b/ckan/public-bs2/base/test/vendor/chai.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/vendor/chai.js
+++ /dev/null
@@ -1,3464 +0,0 @@
-!function (name, definition) {
- if (typeof define == 'function' && typeof define.amd == 'object') define(definition);
- else this[name] = definition();
-}('chai', function () {
-
-// CommonJS require()
-
-function require(p){
- var path = require.resolve(p)
- , mod = require.modules[path];
- if (!mod) throw new Error('failed to require "' + p + '"');
- if (!mod.exports) {
- mod.exports = {};
- mod.call(mod.exports, mod, mod.exports, require.relative(path));
- }
- return mod.exports;
- }
-
-require.modules = {};
-
-require.resolve = function (path){
- var orig = path
- , reg = path + '.js'
- , index = path + '/index.js';
- return require.modules[reg] && reg
- || require.modules[index] && index
- || orig;
- };
-
-require.register = function (path, fn){
- require.modules[path] = fn;
- };
-
-require.relative = function (parent) {
- return function(p){
- if ('.' != p[0]) return require(p);
-
- var path = parent.split('/')
- , segs = p.split('/');
- path.pop();
-
- for (var i = 0; i < segs.length; i++) {
- var seg = segs[i];
- if ('..' == seg) path.pop();
- else if ('.' != seg) path.push(seg);
- }
-
- return require(path.join('/'));
- };
- };
-
-
-require.register("chai.js", function(module, exports, require){
-/*!
- * chai
- * Copyright(c) 2011-2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-var used = []
- , exports = module.exports = {};
-
-/*!
- * Chai version
- */
-
-exports.version = '1.1.0';
-
-/*!
- * Primary `Assertion` prototype
- */
-
-exports.Assertion = require('./chai/assertion');
-
-/*!
- * Assertion Error
- */
-
-exports.AssertionError = require('./chai/browser/error');
-
-/*!
- * Utils for plugins (not exported)
- */
-
-var util = require('./chai/utils');
-
-/**
- * # .use(function)
- *
- * Provides a way to extend the internals of Chai
- *
- * @param {Function}
- * @returns {this} for chaining
- * @api public
- */
-
-exports.use = function (fn) {
- if (!~used.indexOf(fn)) {
- fn(this, util);
- used.push(fn);
- }
-
- return this;
-};
-
-/*!
- * Core Assertions
- */
-
-var core = require('./chai/core/assertions');
-exports.use(core);
-
-/*!
- * Expect interface
- */
-
-var expect = require('./chai/interface/expect');
-exports.use(expect);
-
-/*!
- * Should interface
- */
-
-var should = require('./chai/interface/should');
-exports.use(should);
-
-/*!
- * Assert interface
- */
-
-var assert = require('./chai/interface/assert');
-exports.use(assert);
-
-}); // module: chai.js
-
-require.register("chai/assertion.js", function(module, exports, require){
-/*!
- * chai
- * http://chaijs.com
- * Copyright(c) 2011-2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/*!
- * Module dependencies.
- */
-
-var AssertionError = require('./browser/error')
- , util = require('./utils')
- , flag = util.flag;
-
-/*!
- * Module export.
- */
-
-module.exports = Assertion;
-
-
-/*!
- * Assertion Constructor
- *
- * Creates object for chaining.
- *
- * @api private
- */
-
-function Assertion (obj, msg, stack) {
- flag(this, 'ssfi', stack || arguments.callee);
- flag(this, 'object', obj);
- flag(this, 'message', msg);
-}
-
-/*!
- * ### Assertion.includeStack
- *
- * User configurable property, influences whether stack trace
- * is included in Assertion error message. Default of false
- * suppresses stack trace in the error message
- *
- * Assertion.includeStack = true; // enable stack on error
- *
- * @api public
- */
-
-Assertion.includeStack = false;
-
-Assertion.addProperty = function (name, fn) {
- util.addProperty(this.prototype, name, fn);
-};
-
-Assertion.addMethod = function (name, fn) {
- util.addMethod(this.prototype, name, fn);
-};
-
-Assertion.addChainableMethod = function (name, fn, chainingBehavior) {
- util.addChainableMethod(this.prototype, name, fn, chainingBehavior);
-};
-
-Assertion.overwriteProperty = function (name, fn) {
- util.overwriteProperty(this.prototype, name, fn);
-};
-
-Assertion.overwriteMethod = function (name, fn) {
- util.overwriteMethod(this.prototype, name, fn);
-};
-
-/*!
- * ### .assert(expression, message, negateMessage, expected, actual)
- *
- * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass.
- *
- * @name assert
- * @param {Philosophical} expression to be tested
- * @param {String} message to display if fails
- * @param {String} negatedMessage to display if negated expression fails
- * @param {Mixed} expected value (remember to check for negation)
- * @param {Mixed} actual (optional) will default to `this.obj`
- * @api private
- */
-
-Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual) {
- var msg = util.getMessage(this, arguments)
- , actual = util.getActual(this, arguments)
- , ok = util.test(this, arguments);
-
- if (!ok) {
- throw new AssertionError({
- message: msg
- , actual: actual
- , expected: expected
- , stackStartFunction: (Assertion.includeStack) ? this.assert : flag(this, 'ssfi')
- });
- }
-};
-
-/*!
- * ### ._obj
- *
- * Quick reference to stored `actual` value for plugin developers.
- *
- * @api private
- */
-
-Object.defineProperty(Assertion.prototype, '_obj',
- { get: function () {
- return flag(this, 'object');
- }
- , set: function (val) {
- flag(this, 'object', val);
- }
-});
-
-}); // module: chai/assertion.js
-
-require.register("chai/browser/error.js", function(module, exports, require){
-/*!
- * chai
- * Copyright(c) 2011-2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-module.exports = AssertionError;
-
-function AssertionError (options) {
- options = options || {};
- this.message = options.message;
- this.actual = options.actual;
- this.expected = options.expected;
- this.operator = options.operator;
-
- if (options.stackStartFunction && Error.captureStackTrace) {
- var stackStartFunction = options.stackStartFunction;
- Error.captureStackTrace(this, stackStartFunction);
- }
-}
-
-AssertionError.prototype = Object.create(Error.prototype);
-AssertionError.prototype.name = 'AssertionError';
-AssertionError.prototype.constructor = AssertionError;
-
-AssertionError.prototype.toString = function() {
- return this.message;
-};
-
-}); // module: chai/browser/error.js
-
-require.register("chai/core/assertions.js", function(module, exports, require){
-/*!
- * chai
- * http://chaijs.com
- * Copyright(c) 2011-2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-module.exports = function (chai, _) {
- var Assertion = chai.Assertion
- , toString = Object.prototype.toString
- , flag = _.flag;
-
- /**
- * ### Language Chains
- *
- * The following are provide as chainable getters to
- * improve the readability of your assertions. They
- * do not provide an testing capability unless they
- * have been overwritten by a plugin.
- *
- * **Chains**
- *
- * - to
- * - be
- * - been
- * - is
- * - that
- * - and
- * - have
- * - with
- *
- * @name language chains
- * @api public
- */
-
- [ 'to', 'be', 'been'
- , 'is', 'and', 'have'
- , 'with', 'that' ].forEach(function (chain) {
- Assertion.addProperty(chain, function () {
- return this;
- });
- });
-
- /**
- * ### .not
- *
- * Negates any of assertions following in the chain.
- *
- * expect(foo).to.not.equal('bar');
- * expect(goodFn).to.not.throw(Error);
- * expect({ foo: 'baz' }).to.have.property('foo')
- * .and.not.equal('bar');
- *
- * @name not
- * @api public
- */
-
- Assertion.addProperty('not', function () {
- flag(this, 'negate', true);
- });
-
- /**
- * ### .deep
- *
- * Sets the `deep` flag, later used by the `equal` and
- * `property` assertions.
- *
- * expect(foo).to.deep.equal({ bar: 'baz' });
- * expect({ foo: { bar: { baz: 'quux' } } })
- * .to.have.deep.property('foo.bar.baz', 'quux');
- *
- * @name deep
- * @api public
- */
-
- Assertion.addProperty('deep', function () {
- flag(this, 'deep', true);
- });
-
- /**
- * ### .a(type)
- *
- * The `a` and `an` assertions are aliases that can be
- * used either as language chains or to assert a value's
- * type (as revealed by `Object.prototype.toString`).
- *
- * // typeof
- * expect('test').to.be.a('string');
- * expect({ foo: 'bar' }).to.be.an('object');
- * expect(null).to.be.a('null');
- * expect(undefined).to.be.an('undefined');
- *
- * // language chain
- * expect(foo).to.be.an.instanceof(Foo);
- *
- * @name a
- * @alias an
- * @param {String} type
- * @api public
- */
-
- function an(type) {
- var obj = flag(this, 'object')
- , klassStart = type.charAt(0).toUpperCase()
- , klass = klassStart + type.slice(1)
- , article = ~[ 'A', 'E', 'I', 'O', 'U' ].indexOf(klassStart) ? 'an ' : 'a ';
-
- this.assert(
- '[object ' + klass + ']' === toString.call(obj)
- , 'expected #{this} to be ' + article + type
- , 'expected #{this} not to be ' + article + type
- );
- }
-
- Assertion.addChainableMethod('an', an);
- Assertion.addChainableMethod('a', an);
-
- /**
- * ### .include(value)
- *
- * The `include` and `contain` assertions can be used as either property
- * based language chains or as methods to assert the inclusion of an object
- * in an array or a substring in a string. When used as language chains,
- * they toggle the `contain` flag for the `keys` assertion.
- *
- * expect([1,2,3]).to.include(2);
- * expect('foobar').to.contain('foo');
- * expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');
- *
- * @name include
- * @alias contain
- * @param {Object|String|Number} obj
- * @api public
- */
-
- function includeChainingBehavior () {
- flag(this, 'contains', true);
- }
-
- function include (val) {
- var obj = flag(this, 'object')
- this.assert(
- ~obj.indexOf(val)
- , 'expected #{this} to include ' + _.inspect(val)
- , 'expected #{this} to not include ' + _.inspect(val));
- }
-
- Assertion.addChainableMethod('include', include, includeChainingBehavior);
- Assertion.addChainableMethod('contain', include, includeChainingBehavior);
-
- /**
- * ### .ok
- *
- * Asserts that the target is truthy.
- *
- * expect('everthing').to.be.ok;
- * expect(1).to.be.ok;
- * expect(false).to.not.be.ok;
- * expect(undefined).to.not.be.ok;
- * expect(null).to.not.be.ok;
- *
- * @name ok
- * @api public
- */
-
- Assertion.addProperty('ok', function () {
- this.assert(
- flag(this, 'object')
- , 'expected #{this} to be truthy'
- , 'expected #{this} to be falsy');
- });
-
- /**
- * ### .true
- *
- * Asserts that the target is `true`.
- *
- * expect(true).to.be.true;
- * expect(1).to.not.be.true;
- *
- * @name true
- * @api public
- */
-
- Assertion.addProperty('true', function () {
- this.assert(
- true === flag(this, 'object')
- , 'expected #{this} to be true'
- , 'expected #{this} to be false'
- , this.negate ? false : true
- );
- });
-
- /**
- * ### .false
- *
- * Asserts that the target is `false`.
- *
- * expect(false).to.be.false;
- * expect(0).to.not.be.false;
- *
- * @name false
- * @api public
- */
-
- Assertion.addProperty('false', function () {
- this.assert(
- false === flag(this, 'object')
- , 'expected #{this} to be false'
- , 'expected #{this} to be true'
- , this.negate ? true : false
- );
- });
-
- /**
- * ### .null
- *
- * Asserts that the target is `null`.
- *
- * expect(null).to.be.null;
- * expect(undefined).not.to.be.null;
- *
- * @name null
- * @api public
- */
-
- Assertion.addProperty('null', function () {
- this.assert(
- null === flag(this, 'object')
- , 'expected #{this} to be null'
- , 'expected #{this} not to be null'
- );
- });
-
- /**
- * ### .undefined
- *
- * Asserts that the target is `undefined`.
- *
- * expect(undefined).to.be.undefined;
- * expect(null).to.not.be.undefined;
- *
- * @name undefined
- * @api public
- */
-
- Assertion.addProperty('undefined', function () {
- this.assert(
- undefined === flag(this, 'object')
- , 'expected #{this} to be undefined'
- , 'expected #{this} not to be undefined'
- );
- });
-
- /**
- * ### .exist
- *
- * Asserts that the target is neither `null` nor `undefined`.
- *
- * var foo = 'hi'
- * , bar = null
- * , baz;
- *
- * expect(foo).to.exist;
- * expect(bar).to.not.exist;
- * expect(baz).to.not.exist;
- *
- * @name exist
- * @api public
- */
-
- Assertion.addProperty('exist', function () {
- this.assert(
- null != flag(this, 'object')
- , 'expected #{this} to exist'
- , 'expected #{this} to not exist'
- );
- });
-
-
- /**
- * ### .empty
- *
- * Asserts that the target's length is `0`. For arrays, it checks
- * the `length` property. For objects, it gets the count of
- * enumerable keys.
- *
- * expect([]).to.be.empty;
- * expect('').to.be.empty;
- * expect({}).to.be.empty;
- *
- * @name empty
- * @api public
- */
-
- Assertion.addProperty('empty', function () {
- var obj = flag(this, 'object')
- , expected = obj;
-
- if (Array.isArray(obj) || 'string' === typeof object) {
- expected = obj.length;
- } else if (typeof obj === 'object') {
- expected = Object.keys(obj).length;
- }
-
- this.assert(
- !expected
- , 'expected #{this} to be empty'
- , 'expected #{this} not to be empty'
- );
- });
-
- /**
- * ### .arguments
- *
- * Asserts that the target is an arguments object.
- *
- * function test () {
- * expect(arguments).to.be.arguments;
- * }
- *
- * @name arguments
- * @alias Arguments
- * @api public
- */
-
- function checkArguments () {
- var obj = flag(this, 'object')
- , type = Object.prototype.toString.call(obj);
- this.assert(
- '[object Arguments]' === type
- , 'expected #{this} to be arguments but got ' + type
- , 'expected #{this} to not be arguments'
- );
- }
-
- Assertion.addProperty('arguments', checkArguments);
- Assertion.addProperty('Arguments', checkArguments);
-
- /**
- * ### .equal(value)
- *
- * Asserts that the target is strictly equal (`===`) to `value`.
- * Alternately, if the `deep` flag is set, asserts that
- * the target is deeply equal to `value`.
- *
- * expect('hello').to.equal('hello');
- * expect(42).to.equal(42);
- * expect(1).to.not.equal(true);
- * expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' });
- * expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });
- *
- * @name equal
- * @alias eq
- * @alias deep.equal
- * @param {Mixed} value
- * @api public
- */
-
- function assertEqual (val) {
- var obj = flag(this, 'object');
- if (flag(this, 'deep')) {
- return this.eql(val);
- } else {
- this.assert(
- val === obj
- , 'expected #{this} to equal #{exp}'
- , 'expected #{this} to not equal #{exp}'
- , val
- );
- }
- }
-
- Assertion.addMethod('equal', assertEqual);
- Assertion.addMethod('eq', assertEqual);
-
- /**
- * ### .eql(value)
- *
- * Asserts that the target is deeply equal to `value`.
- *
- * expect({ foo: 'bar' }).to.eql({ foo: 'bar' });
- * expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]);
- *
- * @name eql
- * @param {Mixed} value
- * @api public
- */
-
- Assertion.addMethod('eql', function (obj) {
- this.assert(
- _.eql(obj, flag(this, 'object'))
- , 'expected #{this} to deeply equal #{exp}'
- , 'expected #{this} to not deeply equal #{exp}'
- , obj
- );
- });
-
- /**
- * ### .above(value)
- *
- * Asserts that the target is greater than `value`.
- *
- * expect(10).to.be.above(5);
- *
- * Can also be used in conjunction with `length` to
- * assert a minimum length. The benefit being a
- * more informative error message than if the length
- * was supplied directly.
- *
- * expect('foo').to.have.length.above(2);
- * expect([ 1, 2, 3 ]).to.have.length.above(2);
- *
- * @name above
- * @alias gt
- * @alias greaterThan
- * @param {Number} value
- * @api public
- */
-
- function assertAbove (n) {
- var obj = flag(this, 'object');
- if (flag(this, 'doLength')) {
- new Assertion(obj).to.have.property('length');
- var len = obj.length;
- this.assert(
- len > n
- , 'expected #{this} to have a length above #{exp} but got #{act}'
- , 'expected #{this} to not have a length above #{exp}'
- , n
- , len
- );
- } else {
- this.assert(
- obj > n
- , 'expected #{this} to be above ' + n
- , 'expected #{this} to be below ' + n
- );
- }
- }
-
- Assertion.addMethod('above', assertAbove);
- Assertion.addMethod('gt', assertAbove);
- Assertion.addMethod('greaterThan', assertAbove);
-
- /**
- * ### .below(value)
- *
- * Asserts that the target is less than `value`.
- *
- * expect(5).to.be.below(10);
- *
- * Can also be used in conjunction with `length` to
- * assert a maximum length. The benefit being a
- * more informative error message than if the length
- * was supplied directly.
- *
- * expect('foo').to.have.length.below(4);
- * expect([ 1, 2, 3 ]).to.have.length.below(4);
- *
- * @name below
- * @alias lt
- * @alias lessThan
- * @param {Number} value
- * @api public
- */
-
- function assertBelow (n) {
- var obj = flag(this, 'object');
- if (flag(this, 'doLength')) {
- new Assertion(obj).to.have.property('length');
- var len = obj.length;
- this.assert(
- len < n
- , 'expected #{this} to have a length below #{exp} but got #{act}'
- , 'expected #{this} to not have a length below #{exp}'
- , n
- , len
- );
- } else {
- this.assert(
- obj < n
- , 'expected #{this} to be below ' + n
- , 'expected #{this} to be above ' + n
- );
- }
- }
-
- Assertion.addMethod('below', assertBelow);
- Assertion.addMethod('lt', assertBelow);
- Assertion.addMethod('lessThan', assertBelow);
-
- /**
- * ### .within(start, finish)
- *
- * Asserts that the target is within a range.
- *
- * expect(7).to.be.within(5,10);
- *
- * Can also be used in conjunction with `length` to
- * assert a length range. The benefit being a
- * more informative error message than if the length
- * was supplied directly.
- *
- * expect('foo').to.have.length.within(2,4);
- * expect([ 1, 2, 3 ]).to.have.length.within(2,4);
- *
- * @name within
- * @param {Number} start lowerbound inclusive
- * @param {Number} finish upperbound inclusive
- * @api public
- */
-
- Assertion.addMethod('within', function (start, finish) {
- var obj = flag(this, 'object')
- , range = start + '..' + finish;
- if (flag(this, 'doLength')) {
- new Assertion(obj).to.have.property('length');
- var len = obj.length;
- this.assert(
- len >= start && len <= finish
- , 'expected #{this} to have a length within ' + range
- , 'expected #{this} to not have a length within ' + range
- );
- } else {
- this.assert(
- obj >= start && obj <= finish
- , 'expected #{this} to be within ' + range
- , 'expected #{this} to not be within ' + range
- );
- }
- });
-
- /**
- * ### .instanceof(constructor)
- *
- * Asserts that the target is an instance of `constructor`.
- *
- * var Tea = function (name) { this.name = name; }
- * , Chai = new Tea('chai');
- *
- * expect(Chai).to.be.an.instanceof(Tea);
- * expect([ 1, 2, 3 ]).to.be.instanceof(Array);
- *
- * @name instanceof
- * @param {Constructor} constructor
- * @alias instanceOf
- * @api public
- */
-
- function assertInstanceOf (constructor) {
- var name = _.getName(constructor);
- this.assert(
- flag(this, 'object') instanceof constructor
- , 'expected #{this} to be an instance of ' + name
- , 'expected #{this} to not be an instance of ' + name
- );
- };
-
- Assertion.addMethod('instanceof', assertInstanceOf);
- Assertion.addMethod('instanceOf', assertInstanceOf);
-
- /**
- * ### .property(name, [value])
- *
- * Asserts that the target has a property `name`, optionally asserting that
- * the value of that property is strictly equal to `value`.
- * If the `deep` flag is set, you can use dot- and bracket-notation for deep
- * references into objects and arrays.
- *
- * // simple referencing
- * var obj = { foo: 'bar' };
- * expect(obj).to.have.property('foo');
- * expect(obj).to.have.property('foo', 'bar');
- *
- * // deep referencing
- * var deepObj = {
- * green: { tea: 'matcha' }
- * , teas: [ 'chai', 'matcha', { tea: 'konacha' } ]
- * };
-
- * expect(deepObj).to.have.deep.property('green.tea', 'matcha');
- * expect(deepObj).to.have.deep.property('teas[1]', 'matcha');
- * expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha');
- *
- * You can also use an array as the starting point of a `deep.property`
- * assertion, or traverse nested arrays.
- *
- * var arr = [
- * [ 'chai', 'matcha', 'konacha' ]
- * , [ { tea: 'chai' }
- * , { tea: 'matcha' }
- * , { tea: 'konacha' } ]
- * ];
- *
- * expect(arr).to.have.deep.property('[0][1]', 'matcha');
- * expect(arr).to.have.deep.property('[1][2].tea', 'konacha');
- *
- * Furthermore, `property` changes the subject of the assertion
- * to be the value of that property from the original object. This
- * permits for further chainable assertions on that property.
- *
- * expect(obj).to.have.property('foo')
- * .that.is.a('string');
- * expect(deepObj).to.have.property('green')
- * .that.is.an('object')
- * .that.deep.equals({ tea: 'matcha' });
- * expect(deepObj).to.have.property('teas')
- * .that.is.an('array')
- * .with.deep.property('[2]')
- * .that.deep.equals({ tea: 'konacha' });
- *
- * @name property
- * @alias deep.property
- * @param {String} name
- * @param {Mixed} value (optional)
- * @returns value of property for chaining
- * @api public
- */
-
- Assertion.addMethod('property', function (name, val) {
- var obj = flag(this, 'object')
- , value = flag(this, 'deep') ? _.getPathValue(name, obj) : obj[name]
- , descriptor = flag(this, 'deep') ? 'deep property ' : 'property '
- , negate = flag(this, 'negate');
-
- if (negate && undefined !== val) {
- if (undefined === value) {
- throw new Error(_.inspect(obj) + ' has no ' + descriptor + _.inspect(name));
- }
- } else {
- this.assert(
- undefined !== value
- , 'expected #{this} to have a ' + descriptor + _.inspect(name)
- , 'expected #{this} to not have ' + descriptor + _.inspect(name));
- }
-
- if (undefined !== val) {
- this.assert(
- val === value
- , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}'
- , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}'
- , val
- , value
- );
- }
-
- flag(this, 'object', value);
- });
-
-
- /**
- * ### .ownProperty(name)
- *
- * Asserts that the target has an own property `name`.
- *
- * expect('test').to.have.ownProperty('length');
- *
- * @name ownProperty
- * @alias haveOwnProperty
- * @param {String} name
- * @api public
- */
-
- function assertOwnProperty (name) {
- var obj = flag(this, 'object');
- this.assert(
- obj.hasOwnProperty(name)
- , 'expected #{this} to have own property ' + _.inspect(name)
- , 'expected #{this} to not have own property ' + _.inspect(name)
- );
- }
-
- Assertion.addMethod('ownProperty', assertOwnProperty);
- Assertion.addMethod('haveOwnProperty', assertOwnProperty);
-
- /**
- * ### .length(value)
- *
- * Asserts that the target's `length` property has
- * the expected value.
- *
- * expect([ 1, 2, 3]).to.have.length(3);
- * expect('foobar').to.have.length(6);
- *
- * Can also be used as a chain precursor to a value
- * comparison for the length property.
- *
- * expect('foo').to.have.length.above(2);
- * expect([ 1, 2, 3 ]).to.have.length.above(2);
- * expect('foo').to.have.length.below(4);
- * expect([ 1, 2, 3 ]).to.have.length.below(4);
- * expect('foo').to.have.length.within(2,4);
- * expect([ 1, 2, 3 ]).to.have.length.within(2,4);
- *
- * @name length
- * @alias lengthOf
- * @param {Number} length
- * @api public
- */
-
- function assertLengthChain () {
- flag(this, 'doLength', true);
- }
-
- function assertLength (n) {
- var obj = flag(this, 'object');
- new Assertion(obj).to.have.property('length');
- var len = obj.length;
-
- this.assert(
- len == n
- , 'expected #{this} to have a length of #{exp} but got #{act}'
- , 'expected #{this} to not have a length of #{act}'
- , n
- , len
- );
- }
-
- Assertion.addChainableMethod('length', assertLength, assertLengthChain);
- Assertion.addMethod('lengthOf', assertLength, assertLengthChain);
-
- /**
- * ### .match(regexp)
- *
- * Asserts that the target matches a regular expression.
- *
- * expect('foobar').to.match(/^foo/);
- *
- * @name match
- * @param {RegExp} RegularExpression
- * @api public
- */
-
- Assertion.addMethod('match', function (re) {
- var obj = flag(this, 'object');
- this.assert(
- re.exec(obj)
- , 'expected #{this} to match ' + re
- , 'expected #{this} not to match ' + re
- );
- });
-
- /**
- * ### .string(string)
- *
- * Asserts that the string target contains another string.
- *
- * expect('foobar').to.have.string('bar');
- *
- * @name string
- * @param {String} string
- * @api public
- */
-
- Assertion.addMethod('string', function (str) {
- var obj = flag(this, 'object');
- new Assertion(obj).is.a('string');
-
- this.assert(
- ~obj.indexOf(str)
- , 'expected #{this} to contain ' + _.inspect(str)
- , 'expected #{this} to not contain ' + _.inspect(str)
- );
- });
-
-
- /**
- * ### .keys(key1, [key2], [...])
- *
- * Asserts that the target has exactly the given keys, or
- * asserts the inclusion of some keys when using the
- * `include` or `contain` modifiers.
- *
- * expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']);
- * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar');
- *
- * @name keys
- * @alias key
- * @param {String...|Array} keys
- * @api public
- */
-
- function assertKeys (keys) {
- var obj = flag(this, 'object')
- , str
- , ok = true;
-
- keys = keys instanceof Array
- ? keys
- : Array.prototype.slice.call(arguments);
-
- if (!keys.length) throw new Error('keys required');
-
- var actual = Object.keys(obj)
- , len = keys.length;
-
- // Inclusion
- ok = keys.every(function(key){
- return ~actual.indexOf(key);
- });
-
- // Strict
- if (!flag(this, 'negate') && !flag(this, 'contains')) {
- ok = ok && keys.length == actual.length;
- }
-
- // Key string
- if (len > 1) {
- keys = keys.map(function(key){
- return _.inspect(key);
- });
- var last = keys.pop();
- str = keys.join(', ') + ', and ' + last;
- } else {
- str = _.inspect(keys[0]);
- }
-
- // Form
- str = (len > 1 ? 'keys ' : 'key ') + str;
-
- // Have / include
- str = (flag(this, 'contains') ? 'contain ' : 'have ') + str;
-
- // Assertion
- this.assert(
- ok
- , 'expected #{this} to ' + str
- , 'expected #{this} to not ' + str
- );
- }
-
- Assertion.addMethod('keys', assertKeys);
- Assertion.addMethod('key', assertKeys);
-
- /**
- * ### .throw(constructor)
- *
- * Asserts that the function target will throw a specific error, or specific type of error
- * (as determined using `instanceof`), optionally with a RegExp or string inclusion test
- * for the error's message.
- *
- * var err = new ReferenceError('This is a bad function.');
- * var fn = function () { throw err; }
- * expect(fn).to.throw(ReferenceError);
- * expect(fn).to.throw(Error);
- * expect(fn).to.throw(/bad function/);
- * expect(fn).to.not.throw('good function');
- * expect(fn).to.throw(ReferenceError, /bad function/);
- * expect(fn).to.throw(err);
- * expect(fn).to.not.throw(new RangeError('Out of range.'));
- *
- * Please note that when a throw expectation is negated, it will check each
- * parameter independently, starting with error constructor type. The appropriate way
- * to check for the existence of a type of error but for a message that does not match
- * is to use `and`.
- *
- * expect(fn).to.throw(ReferenceError)
- * .and.not.throw(/good function/);
- *
- * @name throw
- * @alias throws
- * @alias Throw
- * @param {ErrorConstructor} constructor
- * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types
- * @api public
- */
-
- function assertThrows (constructor, msg) {
- var obj = flag(this, 'object');
- new Assertion(obj).is.a('function');
-
- var thrown = false
- , desiredError = null
- , name = null;
-
- if (arguments.length === 0) {
- msg = null;
- constructor = null;
- } else if (constructor && (constructor instanceof RegExp || 'string' === typeof constructor)) {
- msg = constructor;
- constructor = null;
- } else if (constructor && constructor instanceof Error) {
- desiredError = constructor;
- constructor = null;
- msg = null;
- } else if (typeof constructor === 'function') {
- name = (new constructor()).name;
- } else {
- constructor = null;
- }
-
- try {
- obj();
- } catch (err) {
- // first, check desired error
- if (desiredError) {
- this.assert(
- err === desiredError
- , 'expected #{this} to throw ' + _.inspect(desiredError) + ' but ' + _.inspect(err) + ' was thrown'
- , 'expected #{this} to not throw ' + _.inspect(desiredError)
- );
- return this;
- }
- // next, check constructor
- if (constructor) {
- this.assert(
- err instanceof constructor
- , 'expected #{this} to throw ' + name + ' but a ' + err.name + ' was thrown'
- , 'expected #{this} to not throw ' + name );
- if (!msg) return this;
- }
- // next, check message
- if (err.message && msg && msg instanceof RegExp) {
- this.assert(
- msg.exec(err.message)
- , 'expected #{this} to throw error matching ' + msg + ' but got ' + _.inspect(err.message)
- , 'expected #{this} to throw error not matching ' + msg
- );
- return this;
- } else if (err.message && msg && 'string' === typeof msg) {
- this.assert(
- ~err.message.indexOf(msg)
- , 'expected #{this} to throw error including #{exp} but got #{act}'
- , 'expected #{this} to throw error not including #{act}'
- , msg
- , err.message
- );
- return this;
- } else {
- thrown = true;
- }
- }
-
- var expectedThrown = name ? name : desiredError ? _.inspect(desiredError) : 'an error';
-
- this.assert(
- thrown === true
- , 'expected #{this} to throw ' + expectedThrown
- , 'expected #{this} to not throw ' + expectedThrown
- );
- };
-
- Assertion.addMethod('throw', assertThrows);
- Assertion.addMethod('throws', assertThrows);
- Assertion.addMethod('Throw', assertThrows);
-
- /**
- * ### .respondTo(method)
- *
- * Asserts that the object or class target will respond to a method.
- *
- * Klass.prototype.bar = function(){};
- * expect(Klass).to.respondTo('bar');
- * expect(obj).to.respondTo('bar');
- *
- * To check if a constructor will respond to a static function,
- * set the `itself` flag.
- *
- * Klass.baz = function(){};
- * expect(Klass).itself.to.respondTo('baz');
- *
- * @name respondTo
- * @param {String} method
- * @api public
- */
-
- Assertion.addMethod('respondTo', function (method) {
- var obj = flag(this, 'object')
- , itself = flag(this, 'itself')
- , context = ('function' === typeof obj && !itself)
- ? obj.prototype[method]
- : obj[method];
-
- this.assert(
- 'function' === typeof context
- , 'expected #{this} to respond to ' + _.inspect(method)
- , 'expected #{this} to not respond to ' + _.inspect(method)
- );
- });
-
- /**
- * ### .itself
- *
- * Sets the `itself` flag, later used by the `respondTo` assertion.
- *
- * function Foo() {}
- * Foo.bar = function() {}
- * Foo.prototype.baz = function() {}
- *
- * expect(Foo).itself.to.respondTo('bar');
- * expect(Foo).itself.not.to.respondTo('baz');
- *
- * @name itself
- * @api public
- */
-
- Assertion.addProperty('itself', function () {
- flag(this, 'itself', true);
- });
-
- /**
- * ### .satisfy(method)
- *
- * Asserts that the target passes a given truth test.
- *
- * expect(1).to.satisfy(function(num) { return num > 0; });
- *
- * @name satisfy
- * @param {Function} matcher
- * @api public
- */
-
- Assertion.addMethod('satisfy', function (matcher) {
- var obj = flag(this, 'object');
- this.assert(
- matcher(obj)
- , 'expected #{this} to satisfy ' + _.inspect(matcher)
- , 'expected #{this} to not satisfy' + _.inspect(matcher)
- , this.negate ? false : true
- , matcher(obj)
- );
- });
-
- /**
- * ### .closeTo(expected, delta)
- *
- * Asserts that the target is equal `expected`, to within a +/- `delta` range.
- *
- * expect(1.5).to.be.closeTo(1, 0.5);
- *
- * @name closeTo
- * @param {Number} expected
- * @param {Number} delta
- * @api public
- */
-
- Assertion.addMethod('closeTo', function (expected, delta) {
- var obj = flag(this, 'object');
- this.assert(
- Math.abs(obj - expected) <= delta
- , 'expected #{this} to be close to ' + expected + ' +/- ' + delta
- , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta
- );
- });
-
-};
-
-}); // module: chai/core/assertions.js
-
-require.register("chai/interface/assert.js", function(module, exports, require){
-/*!
- * chai
- * Copyright(c) 2011-2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-
-module.exports = function (chai, util) {
-
- /*!
- * Chai dependencies.
- */
-
- var Assertion = chai.Assertion
- , flag = util.flag;
-
- /*!
- * Module export.
- */
-
- /**
- * ### assert(expression, message)
- *
- * Write your own test expressions.
- *
- * assert('foo' !== 'bar', 'foo is not bar');
- * assert(Array.isArray([]), 'empty arrays are arrays');
- *
- * @param {Mixed} expression to test for truthiness
- * @param {String} message to display on error
- * @name assert
- * @api public
- */
-
- var assert = chai.assert = function (express, errmsg) {
- var test = new Assertion(null);
- test.assert(
- express
- , errmsg
- , '[ negation message unavailable ]'
- );
- };
-
- /**
- * ### .fail(actual, expected, [message], [operator])
- *
- * Throw a failure. Node.js `assert` module-compatible.
- *
- * @name fail
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @param {String} operator
- * @api public
- */
-
- assert.fail = function (actual, expected, message, operator) {
- throw new chai.AssertionError({
- actual: actual
- , expected: expected
- , message: message
- , operator: operator
- , stackStartFunction: assert.fail
- });
- };
-
- /**
- * ### .ok(object, [message])
- *
- * Asserts that `object` is truthy.
- *
- * assert.ok('everything', 'everything is ok');
- * assert.ok(false, 'this will fail');
- *
- * @name ok
- * @param {Mixed} object to test
- * @param {String} message
- * @api public
- */
-
- assert.ok = function (val, msg) {
- new Assertion(val, msg).is.ok;
- };
-
- /**
- * ### .equal(actual, expected, [message])
- *
- * Asserts non-strict equality (`==`) of `actual` and `expected`.
- *
- * assert.equal(3, '3', '== coerces values to strings');
- *
- * @name equal
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.equal = function (act, exp, msg) {
- var test = new Assertion(act, msg);
-
- test.assert(
- exp == flag(test, 'object')
- , 'expected #{this} to equal #{exp}'
- , 'expected #{this} to not equal #{act}'
- , exp
- , act
- );
- };
-
- /**
- * ### .notEqual(actual, expected, [message])
- *
- * Asserts non-strict inequality (`!=`) of `actual` and `expected`.
- *
- * assert.notEqual(3, 4, 'these numbers are not equal');
- *
- * @name notEqual
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.notEqual = function (act, exp, msg) {
- var test = new Assertion(act, msg);
-
- test.assert(
- exp != flag(test, 'object')
- , 'expected #{this} to not equal #{exp}'
- , 'expected #{this} to equal #{act}'
- , exp
- , act
- );
- };
-
- /**
- * ### .strictEqual(actual, expected, [message])
- *
- * Asserts strict equality (`===`) of `actual` and `expected`.
- *
- * assert.strictEqual(true, true, 'these booleans are strictly equal');
- *
- * @name strictEqual
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.strictEqual = function (act, exp, msg) {
- new Assertion(act, msg).to.equal(exp);
- };
-
- /**
- * ### .notStrictEqual(actual, expected, [message])
- *
- * Asserts strict inequality (`!==`) of `actual` and `expected`.
- *
- * assert.notStrictEqual(3, '3', 'no coercion for strict equality');
- *
- * @name notStrictEqual
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.notStrictEqual = function (act, exp, msg) {
- new Assertion(act, msg).to.not.equal(exp);
- };
-
- /**
- * ### .deepEqual(actual, expected, [message])
- *
- * Asserts that `actual` is deeply equal to `expected`.
- *
- * assert.deepEqual({ tea: 'green' }, { tea: 'green' });
- *
- * @name deepEqual
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.deepEqual = function (act, exp, msg) {
- new Assertion(act, msg).to.eql(exp);
- };
-
- /**
- * ### .notDeepEqual(actual, expected, [message])
- *
- * Assert that `actual` is not deeply equal to `expected`.
- *
- * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' });
- *
- * @name notDeepEqual
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.notDeepEqual = function (act, exp, msg) {
- new Assertion(act, msg).to.not.eql(exp);
- };
-
- /**
- * ### .isTrue(value, [message])
- *
- * Asserts that `value` is true.
- *
- * var teaServed = true;
- * assert.isTrue(teaServed, 'the tea has been served');
- *
- * @name isTrue
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isTrue = function (val, msg) {
- new Assertion(val, msg).is['true'];
- };
-
- /**
- * ### .isFalse(value, [message])
- *
- * Asserts that `value` is false.
- *
- * var teaServed = false;
- * assert.isFalse(teaServed, 'no tea yet? hmm...');
- *
- * @name isFalse
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isFalse = function (val, msg) {
- new Assertion(val, msg).is['false'];
- };
-
- /**
- * ### .isNull(value, [message])
- *
- * Asserts that `value` is null.
- *
- * assert.isNull(err, 'there was no error');
- *
- * @name isNull
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNull = function (val, msg) {
- new Assertion(val, msg).to.equal(null);
- };
-
- /**
- * ### .isNotNull(value, [message])
- *
- * Asserts that `value` is not null.
- *
- * var tea = 'tasty chai';
- * assert.isNotNull(tea, 'great, time for tea!');
- *
- * @name isNotNull
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotNull = function (val, msg) {
- new Assertion(val, msg).to.not.equal(null);
- };
-
- /**
- * ### .isUndefined(value, [message])
- *
- * Asserts that `value` is `undefined`.
- *
- * var tea;
- * assert.isUndefined(tea, 'no tea defined');
- *
- * @name isUndefined
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isUndefined = function (val, msg) {
- new Assertion(val, msg).to.equal(undefined);
- };
-
- /**
- * ### .isDefined(value, [message])
- *
- * Asserts that `value` is not `undefined`.
- *
- * var tea = 'cup of chai';
- * assert.isDefined(tea, 'tea has been defined');
- *
- * @name isUndefined
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isDefined = function (val, msg) {
- new Assertion(val, msg).to.not.equal(undefined);
- };
-
- /**
- * ### .isFunction(value, [message])
- *
- * Asserts that `value` is a function.
- *
- * function serveTea() { return 'cup of tea'; };
- * assert.isFunction(serveTea, 'great, we can have tea now');
- *
- * @name isFunction
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isFunction = function (val, msg) {
- new Assertion(val, msg).to.be.a('function');
- };
-
- /**
- * ### .isNotFunction(value, [message])
- *
- * Asserts that `value` is _not_ a function.
- *
- * var serveTea = [ 'heat', 'pour', 'sip' ];
- * assert.isNotFunction(serveTea, 'great, we have listed the steps');
- *
- * @name isNotFunction
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotFunction = function (val, msg) {
- new Assertion(val, msg).to.not.be.a('function');
- };
-
- /**
- * ### .isObject(value, [message])
- *
- * Asserts that `value` is an object (as revealed by
- * `Object.prototype.toString`).
- *
- * var selection = { name: 'Chai', serve: 'with spices' };
- * assert.isObject(selection, 'tea selection is an object');
- *
- * @name isObject
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isObject = function (val, msg) {
- new Assertion(val, msg).to.be.a('object');
- };
-
- /**
- * ### .isNotObject(value, [message])
- *
- * Asserts that `value` is _not_ an object.
- *
- * var selection = 'chai'
- * assert.isObject(selection, 'tea selection is not an object');
- * assert.isObject(null, 'null is not an object');
- *
- * @name isNotObject
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotObject = function (val, msg) {
- new Assertion(val, msg).to.not.be.a('object');
- };
-
- /**
- * ### .isArray(value, [message])
- *
- * Asserts that `value` is an array.
- *
- * var menu = [ 'green', 'chai', 'oolong' ];
- * assert.isArray(menu, 'what kind of tea do we want?');
- *
- * @name isArray
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isArray = function (val, msg) {
- new Assertion(val, msg).to.be.an('array');
- };
-
- /**
- * ### .isNotArray(value, [message])
- *
- * Asserts that `value` is _not_ an array.
- *
- * var menu = 'green|chai|oolong';
- * assert.isNotArray(menu, 'what kind of tea do we want?');
- *
- * @name isNotArray
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotArray = function (val, msg) {
- new Assertion(val, msg).to.not.be.an('array');
- };
-
- /**
- * ### .isString(value, [message])
- *
- * Asserts that `value` is a string.
- *
- * var teaOrder = 'chai';
- * assert.isString(teaOrder, 'order placed');
- *
- * @name isString
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isString = function (val, msg) {
- new Assertion(val, msg).to.be.a('string');
- };
-
- /**
- * ### .isNotString(value, [message])
- *
- * Asserts that `value` is _not_ a string.
- *
- * var teaOrder = 4;
- * assert.isNotString(teaOrder, 'order placed');
- *
- * @name isNotString
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotString = function (val, msg) {
- new Assertion(val, msg).to.not.be.a('string');
- };
-
- /**
- * ### .isNumber(value, [message])
- *
- * Asserts that `value` is a number.
- *
- * var cups = 2;
- * assert.isNumber(cups, 'how many cups');
- *
- * @name isNumber
- * @param {Number} value
- * @param {String} message
- * @api public
- */
-
- assert.isNumber = function (val, msg) {
- new Assertion(val, msg).to.be.a('number');
- };
-
- /**
- * ### .isNotNumber(value, [message])
- *
- * Asserts that `value` is _not_ a number.
- *
- * var cups = '2 cups please';
- * assert.isNotNumber(cups, 'how many cups');
- *
- * @name isNotNumber
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotNumber = function (val, msg) {
- new Assertion(val, msg).to.not.be.a('number');
- };
-
- /**
- * ### .isBoolean(value, [message])
- *
- * Asserts that `value` is a boolean.
- *
- * var teaReady = true
- * , teaServed = false;
- *
- * assert.isBoolean(teaReady, 'is the tea ready');
- * assert.isBoolean(teaServed, 'has tea been served');
- *
- * @name isBoolean
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isBoolean = function (val, msg) {
- new Assertion(val, msg).to.be.a('boolean');
- };
-
- /**
- * ### .isNotBoolean(value, [message])
- *
- * Asserts that `value` is _not_ a boolean.
- *
- * var teaReady = 'yep'
- * , teaServed = 'nope';
- *
- * assert.isNotBoolean(teaReady, 'is the tea ready');
- * assert.isNotBoolean(teaServed, 'has tea been served');
- *
- * @name isNotBoolean
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotBoolean = function (val, msg) {
- new Assertion(val, msg).to.not.be.a('boolean');
- };
-
- /**
- * ### .typeOf(value, name, [message])
- *
- * Asserts that `value`'s type is `name`, as determined by
- * `Object.prototype.toString`.
- *
- * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object');
- * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array');
- * assert.typeOf('tea', 'string', 'we have a string');
- * assert.typeOf(/tea/, 'regexp', 'we have a regular expression');
- * assert.typeOf(null, 'null', 'we have a null');
- * assert.typeOf(undefined, 'undefined', 'we have an undefined');
- *
- * @name typeOf
- * @param {Mixed} value
- * @param {String} name
- * @param {String} message
- * @api public
- */
-
- assert.typeOf = function (val, type, msg) {
- new Assertion(val, msg).to.be.a(type);
- };
-
- /**
- * ### .notTypeOf(value, name, [message])
- *
- * Asserts that `value`'s type is _not_ `name`, as determined by
- * `Object.prototype.toString`.
- *
- * assert.notTypeOf('tea', 'number', 'strings are not numbers');
- *
- * @name notTypeOf
- * @param {Mixed} value
- * @param {String} typeof name
- * @param {String} message
- * @api public
- */
-
- assert.notTypeOf = function (val, type, msg) {
- new Assertion(val, msg).to.not.be.a(type);
- };
-
- /**
- * ### .instanceOf(object, constructor, [message])
- *
- * Asserts that `value` is an instance of `constructor`.
- *
- * var Tea = function (name) { this.name = name; }
- * , chai = new Tea('chai');
- *
- * assert.instanceOf(chai, Tea, 'chai is an instance of tea');
- *
- * @name instanceOf
- * @param {Object} object
- * @param {Constructor} constructor
- * @param {String} message
- * @api public
- */
-
- assert.instanceOf = function (val, type, msg) {
- new Assertion(val, msg).to.be.instanceOf(type);
- };
-
- /**
- * ### .notInstanceOf(object, constructor, [message])
- *
- * Asserts `value` is not an instance of `constructor`.
- *
- * var Tea = function (name) { this.name = name; }
- * , chai = new String('chai');
- *
- * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea');
- *
- * @name notInstanceOf
- * @param {Object} object
- * @param {Constructor} constructor
- * @param {String} message
- * @api public
- */
-
- assert.notInstanceOf = function (val, type, msg) {
- new Assertion(val, msg).to.not.be.instanceOf(type);
- };
-
- /**
- * ### .include(haystack, needle, [message])
- *
- * Asserts that `haystack` includes `needle`. Works
- * for strings and arrays.
- *
- * assert.include('foobar', 'bar', 'foobar contains string "bar"');
- * assert.include([ 1, 2, 3 ], 3, 'array contains value');
- *
- * @name include
- * @param {Array|String} haystack
- * @param {Mixed} needle
- * @param {String} message
- * @api public
- */
-
- assert.include = function (exp, inc, msg) {
- var obj = new Assertion(exp, msg);
-
- if (Array.isArray(exp)) {
- obj.to.include(inc);
- } else if ('string' === typeof exp) {
- obj.to.contain.string(inc);
- }
- };
-
- /**
- * ### .match(value, regexp, [message])
- *
- * Asserts that `value` matches the regular expression `regexp`.
- *
- * assert.match('foobar', /^foo/, 'regexp matches');
- *
- * @name match
- * @param {Mixed} value
- * @param {RegExp} regexp
- * @param {String} message
- * @api public
- */
-
- assert.match = function (exp, re, msg) {
- new Assertion(exp, msg).to.match(re);
- };
-
- /**
- * ### .notMatch(value, regexp, [message])
- *
- * Asserts that `value` does not match the regular expression `regexp`.
- *
- * assert.notMatch('foobar', /^foo/, 'regexp does not match');
- *
- * @name notMatch
- * @param {Mixed} value
- * @param {RegExp} regexp
- * @param {String} message
- * @api public
- */
-
- assert.notMatch = function (exp, re, msg) {
- new Assertion(exp, msg).to.not.match(re);
- };
-
- /**
- * ### .property(object, property, [message])
- *
- * Asserts that `object` has a property named by `property`.
- *
- * assert.property({ tea: { green: 'matcha' }}, 'tea');
- *
- * @name property
- * @param {Object} object
- * @param {String} property
- * @param {String} message
- * @api public
- */
-
- assert.property = function (obj, prop, msg) {
- new Assertion(obj, msg).to.have.property(prop);
- };
-
- /**
- * ### .notProperty(object, property, [message])
- *
- * Asserts that `object` does _not_ have a property named by `property`.
- *
- * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee');
- *
- * @name notProperty
- * @param {Object} object
- * @param {String} property
- * @param {String} message
- * @api public
- */
-
- assert.notProperty = function (obj, prop, msg) {
- new Assertion(obj, msg).to.not.have.property(prop);
- };
-
- /**
- * ### .deepProperty(object, property, [message])
- *
- * Asserts that `object` has a property named by `property`, which can be a
- * string using dot- and bracket-notation for deep reference.
- *
- * assert.deepProperty({ tea: { green: 'matcha' }}, 'tea.green');
- *
- * @name deepProperty
- * @param {Object} object
- * @param {String} property
- * @param {String} message
- * @api public
- */
-
- assert.deepProperty = function (obj, prop, msg) {
- new Assertion(obj, msg).to.have.deep.property(prop);
- };
-
- /**
- * ### .notDeepProperty(object, property, [message])
- *
- * Asserts that `object` does _not_ have a property named by `property`, which
- * can be a string using dot- and bracket-notation for deep reference.
- *
- * assert.notDeepProperty({ tea: { green: 'matcha' }}, 'tea.oolong');
- *
- * @name notDeepProperty
- * @param {Object} object
- * @param {String} property
- * @param {String} message
- * @api public
- */
-
- assert.notDeepProperty = function (obj, prop, msg) {
- new Assertion(obj, msg).to.not.have.deep.property(prop);
- };
-
- /**
- * ### .propertyVal(object, property, value, [message])
- *
- * Asserts that `object` has a property named by `property` with value given
- * by `value`.
- *
- * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good');
- *
- * @name propertyVal
- * @param {Object} object
- * @param {String} property
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.propertyVal = function (obj, prop, val, msg) {
- new Assertion(obj, msg).to.have.property(prop, val);
- };
-
- /**
- * ### .propertyNotVal(object, property, value, [message])
- *
- * Asserts that `object` has a property named by `property`, but with a value
- * different from that given by `value`.
- *
- * assert.propertyNotVal({ tea: 'is good' }, 'tea', 'is bad');
- *
- * @name propertyNotVal
- * @param {Object} object
- * @param {String} property
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.propertyNotVal = function (obj, prop, val, msg) {
- new Assertion(obj, msg).to.not.have.property(prop, val);
- };
-
- /**
- * ### .deepPropertyVal(object, property, value, [message])
- *
- * Asserts that `object` has a property named by `property` with value given
- * by `value`. `property` can use dot- and bracket-notation for deep
- * reference.
- *
- * assert.deepPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha');
- *
- * @name deepPropertyVal
- * @param {Object} object
- * @param {String} property
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.deepPropertyVal = function (obj, prop, val, msg) {
- new Assertion(obj, msg).to.have.deep.property(prop, val);
- };
-
- /**
- * ### .deepPropertyNotVal(object, property, value, [message])
- *
- * Asserts that `object` has a property named by `property`, but with a value
- * different from that given by `value`. `property` can use dot- and
- * bracket-notation for deep reference.
- *
- * assert.deepPropertyNotVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha');
- *
- * @name deepPropertyNotVal
- * @param {Object} object
- * @param {String} property
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.deepPropertyNotVal = function (obj, prop, val, msg) {
- new Assertion(obj, msg).to.not.have.deep.property(prop, val);
- };
-
- /**
- * ### .lengthOf(object, length, [message])
- *
- * Asserts that `object` has a `length` property with the expected value.
- *
- * assert.lengthOf([1,2,3], 3, 'array has length of 3');
- * assert.lengthOf('foobar', 5, 'string has length of 6');
- *
- * @name lengthOf
- * @param {Mixed} object
- * @param {Number} length
- * @param {String} message
- * @api public
- */
-
- assert.lengthOf = function (exp, len, msg) {
- new Assertion(exp, msg).to.have.length(len);
- };
-
- /**
- * ### .throws(function, [constructor/regexp], [message])
- *
- * Asserts that `function` will throw an error that is an instance of
- * `constructor`, or alternately that it will throw an error with message
- * matching `regexp`.
- *
- * assert.throw(fn, ReferenceError, 'function throws a reference error');
- *
- * @name throws
- * @alias throw
- * @alias Throw
- * @param {Function} function
- * @param {ErrorConstructor} constructor
- * @param {RegExp} regexp
- * @param {String} message
- * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types
- * @api public
- */
-
- assert.Throw = function (fn, type, msg) {
- if ('string' === typeof type) {
- msg = type;
- type = null;
- }
-
- new Assertion(fn, msg).to.Throw(type);
- };
-
- /**
- * ### .doesNotThrow(function, [constructor/regexp], [message])
- *
- * Asserts that `function` will _not_ throw an error that is an instance of
- * `constructor`, or alternately that it will not throw an error with message
- * matching `regexp`.
- *
- * assert.doesNotThrow(fn, Error, 'function does not throw');
- *
- * @name doesNotThrow
- * @param {Function} function
- * @param {ErrorConstructor} constructor
- * @param {RegExp} regexp
- * @param {String} message
- * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types
- * @api public
- */
-
- assert.doesNotThrow = function (fn, type, msg) {
- if ('string' === typeof type) {
- msg = type;
- type = null;
- }
-
- new Assertion(fn, msg).to.not.Throw(type);
- };
-
- /**
- * ### .operator(val1, operator, val2, [message])
- *
- * Compares two values using `operator`.
- *
- * assert.operator(1, '<', 2, 'everything is ok');
- * assert.operator(1, '>', 2, 'this will fail');
- *
- * @name operator
- * @param {Mixed} val1
- * @param {String} operator
- * @param {Mixed} val2
- * @param {String} message
- * @api public
- */
-
- assert.operator = function (val, operator, val2, msg) {
- if (!~['==', '===', '>', '>=', '<', '<=', '!=', '!=='].indexOf(operator)) {
- throw new Error('Invalid operator "' + operator + '"');
- }
- var test = new Assertion(eval(val + operator + val2), msg);
- test.assert(
- true === flag(test, 'object')
- , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2)
- , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) );
- };
-
- /*!
- * Undocumented / untested
- */
-
- assert.ifError = function (val, msg) {
- new Assertion(val, msg).to.not.be.ok;
- };
-
- /*!
- * Aliases.
- */
-
- (function alias(name, as){
- assert[as] = assert[name];
- return alias;
- })
- ('Throw', 'throw')
- ('Throw', 'throws');
-};
-
-}); // module: chai/interface/assert.js
-
-require.register("chai/interface/expect.js", function(module, exports, require){
-/*!
- * chai
- * Copyright(c) 2011-2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-module.exports = function (chai, util) {
- chai.expect = function (val, message) {
- return new chai.Assertion(val, message);
- };
-};
-
-
-}); // module: chai/interface/expect.js
-
-require.register("chai/interface/should.js", function(module, exports, require){
-/*!
- * chai
- * Copyright(c) 2011-2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-module.exports = function (chai, util) {
- var Assertion = chai.Assertion;
-
- function loadShould () {
- // modify Object.prototype to have `should`
- Object.defineProperty(Object.prototype, 'should',
- { set: function () {}
- , get: function(){
- if (this instanceof String || this instanceof Number) {
- return new Assertion(this.constructor(this));
- } else if (this instanceof Boolean) {
- return new Assertion(this == true);
- }
- return new Assertion(this);
- }
- , configurable: true
- });
-
- var should = {};
-
- should.equal = function (val1, val2) {
- new Assertion(val1).to.equal(val2);
- };
-
- should.Throw = function (fn, errt, errs) {
- new Assertion(fn).to.Throw(errt, errs);
- };
-
- should.exist = function (val) {
- new Assertion(val).to.exist;
- }
-
- // negation
- should.not = {}
-
- should.not.equal = function (val1, val2) {
- new Assertion(val1).to.not.equal(val2);
- };
-
- should.not.Throw = function (fn, errt, errs) {
- new Assertion(fn).to.not.Throw(errt, errs);
- };
-
- should.not.exist = function (val) {
- new Assertion(val).to.not.exist;
- }
-
- should['throw'] = should['Throw'];
- should.not['throw'] = should.not['Throw'];
-
- return should;
- };
-
- chai.should = loadShould;
- chai.Should = loadShould;
-};
-
-}); // module: chai/interface/should.js
-
-require.register("chai/utils/addChainableMethod.js", function(module, exports, require){
-/*!
- * Chai - addChainingMethod utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/*!
- * Module dependencies
- */
-
-var transferFlags = require('./transferFlags');
-
-/**
- * ### addChainableMethod (ctx, name, method, chainingBehavior)
- *
- * Adds a method to an object, such that the method can also be chained.
- *
- * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) {
- * var obj = utils.flag(this, 'object');
- * new chai.Assertion(obj).to.be.equal(str);
- * });
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior);
- *
- * The result can then be used as both a method assertion, executing both `method` and
- * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`.
- *
- * expect(fooStr).to.be.foo('bar');
- * expect(fooStr).to.be.foo.equal('foo');
- *
- * @param {Object} ctx object to which the method is added
- * @param {String} name of method to add
- * @param {Function} method function to be used for `name`, when called
- * @param {Function} chainingBehavior function to be called every time the property is accessed
- * @name addChainableMethod
- * @api public
- */
-
-module.exports = function (ctx, name, method, chainingBehavior) {
- if (typeof chainingBehavior !== 'function')
- chainingBehavior = function () { };
-
- Object.defineProperty(ctx, name,
- { get: function () {
- chainingBehavior.call(this);
-
- var assert = function () {
- var result = method.apply(this, arguments);
- return result === undefined ? this : result;
- };
-
- // Re-enumerate every time to better accomodate plugins.
- var asserterNames = Object.getOwnPropertyNames(ctx);
- asserterNames.forEach(function (asserterName) {
- var pd = Object.getOwnPropertyDescriptor(ctx, asserterName)
- , functionProtoPD = Object.getOwnPropertyDescriptor(Function.prototype, asserterName);
- // Avoid trying to overwrite things that we can't, like `length` and `arguments`.
- if (functionProtoPD && !functionProtoPD.configurable) return;
- if (asserterName === 'arguments') return; // @see chaijs/chai/issues/69
- Object.defineProperty(assert, asserterName, pd);
- });
-
- transferFlags(this, assert);
- return assert;
- }
- , configurable: true
- });
-};
-
-}); // module: chai/utils/addChainableMethod.js
-
-require.register("chai/utils/addMethod.js", function(module, exports, require){
-/*!
- * Chai - addMethod utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/**
- * ### addMethod (ctx, name, method)
- *
- * Adds a method to the prototype of an object.
- *
- * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) {
- * var obj = utils.flag(this, 'object');
- * new chai.Assertion(obj).to.be.equal(str);
- * });
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- * chai.Assertion.addMethod('foo', fn);
- *
- * Then can be used as any other assertion.
- *
- * expect(fooStr).to.be.foo('bar');
- *
- * @param {Object} ctx object to which the method is added
- * @param {String} name of method to add
- * @param {Function} method function to be used for name
- * @name addMethod
- * @api public
- */
-
-module.exports = function (ctx, name, method) {
- ctx[name] = function () {
- var result = method.apply(this, arguments);
- return result === undefined ? this : result;
- };
-};
-
-}); // module: chai/utils/addMethod.js
-
-require.register("chai/utils/addProperty.js", function(module, exports, require){
-/*!
- * Chai - addProperty utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/**
- * ### addProperty (ctx, name, getter)
- *
- * Adds a property to the prototype of an object.
- *
- * utils.addProperty(chai.Assertion.prototype, 'foo', function () {
- * var obj = utils.flag(this, 'object');
- * new chai.Assertion(obj).to.be.instanceof(Foo);
- * });
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- * chai.Assertion.addProperty('foo', fn);
- *
- * Then can be used as any other assertion.
- *
- * expect(myFoo).to.be.foo;
- *
- * @param {Object} ctx object to which the property is added
- * @param {String} name of property to add
- * @param {Function} getter function to be used for name
- * @name addProperty
- * @api public
- */
-
-module.exports = function (ctx, name, getter) {
- Object.defineProperty(ctx, name,
- { get: function () {
- var result = getter.call(this);
- return result === undefined ? this : result;
- }
- , configurable: true
- });
-};
-
-}); // module: chai/utils/addProperty.js
-
-require.register("chai/utils/eql.js", function(module, exports, require){
-// This is directly from Node.js assert
-// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/assert.js
-
-
-module.exports = _deepEqual;
-
-// For browser implementation
-if (!Buffer) {
- var Buffer = {
- isBuffer: function () {
- return false;
- }
- };
-}
-
-function _deepEqual(actual, expected) {
- // 7.1. All identical values are equivalent, as determined by ===.
- if (actual === expected) {
- return true;
-
- } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
- if (actual.length != expected.length) return false;
-
- for (var i = 0; i < actual.length; i++) {
- if (actual[i] !== expected[i]) return false;
- }
-
- return true;
-
- // 7.2. If the expected value is a Date object, the actual value is
- // equivalent if it is also a Date object that refers to the same time.
- } else if (actual instanceof Date && expected instanceof Date) {
- return actual.getTime() === expected.getTime();
-
- // 7.3. Other pairs that do not both pass typeof value == 'object',
- // equivalence is determined by ==.
- } else if (typeof actual != 'object' && typeof expected != 'object') {
- return actual === expected;
-
- // 7.4. For all other Object pairs, including Array objects, equivalence is
- // determined by having the same number of owned properties (as verified
- // with Object.prototype.hasOwnProperty.call), the same set of keys
- // (although not necessarily the same order), equivalent values for every
- // corresponding key, and an identical 'prototype' property. Note: this
- // accounts for both named and indexed properties on Arrays.
- } else {
- return objEquiv(actual, expected);
- }
-}
-
-function isUndefinedOrNull(value) {
- return value === null || value === undefined;
-}
-
-function isArguments(object) {
- return Object.prototype.toString.call(object) == '[object Arguments]';
-}
-
-function objEquiv(a, b) {
- if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
- return false;
- // an identical 'prototype' property.
- if (a.prototype !== b.prototype) return false;
- //~~~I've managed to break Object.keys through screwy arguments passing.
- // Converting to array solves the problem.
- if (isArguments(a)) {
- if (!isArguments(b)) {
- return false;
- }
- a = pSlice.call(a);
- b = pSlice.call(b);
- return _deepEqual(a, b);
- }
- try {
- var ka = Object.keys(a),
- kb = Object.keys(b),
- key, i;
- } catch (e) {//happens when one is a string literal and the other isn't
- return false;
- }
- // having the same number of owned properties (keys incorporates
- // hasOwnProperty)
- if (ka.length != kb.length)
- return false;
- //the same set of keys (although not necessarily the same order),
- ka.sort();
- kb.sort();
- //~~~cheap key test
- for (i = ka.length - 1; i >= 0; i--) {
- if (ka[i] != kb[i])
- return false;
- }
- //equivalent values for every corresponding key, and
- //~~~possibly expensive deep test
- for (i = ka.length - 1; i >= 0; i--) {
- key = ka[i];
- if (!_deepEqual(a[key], b[key])) return false;
- }
- return true;
-}
-}); // module: chai/utils/eql.js
-
-require.register("chai/utils/flag.js", function(module, exports, require){
-/*!
- * Chai - flag utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/**
- * ### flag(object ,key, [value])
- *
- * Get or set a flag value on an object. If a
- * value is provided it will be set, else it will
- * return the currently set value or `undefined` if
- * the value is not set.
- *
- * utils.flag(this, 'foo', 'bar'); // setter
- * utils.flag(this, 'foo'); // getter, returns `bar`
- *
- * @param {Object} object (constructed Assertion
- * @param {String} key
- * @param {Mixed} value (optional)
- * @name flag
- * @api private
- */
-
-module.exports = function (obj, key, value) {
- var flags = obj.__flags || (obj.__flags = Object.create(null));
- if (arguments.length === 3) {
- flags[key] = value;
- } else {
- return flags[key];
- }
-};
-
-}); // module: chai/utils/flag.js
-
-require.register("chai/utils/getActual.js", function(module, exports, require){
-/*!
- * Chai - getActual utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/**
- * # getActual(object, [actual])
- *
- * Returns the `actual` value for an Assertion
- *
- * @param {Object} object (constructed Assertion)
- * @param {Arguments} chai.Assertion.prototype.assert arguments
- */
-
-module.exports = function (obj, args) {
- var actual = args[4];
- return 'undefined' !== actual ? actual : obj.obj;
-};
-
-}); // module: chai/utils/getActual.js
-
-require.register("chai/utils/getMessage.js", function(module, exports, require){
-/*!
- * Chai - message composition utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/*!
- * Module dependancies
- */
-
-var flag = require('./flag')
- , getActual = require('./getActual')
- , inspect = require('./inspect');
-
-/**
- * # getMessage(object, message, negateMessage)
- *
- * Construct the error message based on flags
- * and template tags. Template tags will return
- * a stringified inspection of the object referenced.
- *
- * Messsage template tags:
- * - `#{this}` current asserted object
- * - `#{act}` actual value
- * - `#{exp}` expected value
- *
- * @param {Object} object (constructed Assertion)
- * @param {Arguments} chai.Assertion.prototype.assert arguments
- */
-
-module.exports = function (obj, args) {
- var negate = flag(obj, 'negate')
- , val = flag(obj, 'object')
- , expected = args[3]
- , actual = getActual(obj, args)
- , msg = negate ? args[2] : args[1]
- , flagMsg = flag(obj, 'message');
-
- msg = msg || '';
- msg = msg
- .replace(/#{this}/g, inspect(val))
- .replace(/#{act}/g, inspect(actual))
- .replace(/#{exp}/g, inspect(expected));
-
- return flagMsg ? flagMsg + ': ' + msg : msg;
-};
-
-}); // module: chai/utils/getMessage.js
-
-require.register("chai/utils/getName.js", function(module, exports, require){
-/*!
- * Chai - getName utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/**
- * # getName(func)
- *
- * Gets the name of a function, in a cross-browser way.
- *
- * @param {Function} a function (usually a constructor)
- */
-
-module.exports = function (func) {
- if (func.name) return func.name;
-
- var match = /^\s?function ([^(]*)\(/.exec(func);
- return match && match[1] ? match[1] : "";
-};
-
-}); // module: chai/utils/getName.js
-
-require.register("chai/utils/getPathValue.js", function(module, exports, require){
-/*!
- * Chai - getPathValue utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * @see https://github.com/logicalparadox/filtr
- * MIT Licensed
- */
-
-/**
- * ### .getPathValue(path, object)
- *
- * This allows the retrieval of values in an
- * object given a string path.
- *
- * var obj = {
- * prop1: {
- * arr: ['a', 'b', 'c']
- * , str: 'Hello'
- * }
- * , prop2: {
- * arr: [ { nested: 'Universe' } ]
- * , str: 'Hello again!'
- * }
- * }
- *
- * The following would be the results.
- *
- * getPathValue('prop1.str', obj); // Hello
- * getPathValue('prop1.att[2]', obj); // b
- * getPathValue('prop2.arr[0].nested', obj); // Universe
- *
- * @param {String} path
- * @param {Object} object
- * @returns {Object} value or `undefined`
- * @name getPathValue
- * @api public
- */
-
-var getPathValue = module.exports = function (path, obj) {
- var parsed = parsePath(path);
- return _getPathValue(parsed, obj);
-};
-
-/*!
- * ## parsePath(path)
- *
- * Helper function used to parse string object
- * paths. Use in conjunction with `_getPathValue`.
- *
- * var parsed = parsePath('myobject.property.subprop');
- *
- * ### Paths:
- *
- * * Can be as near infinitely deep and nested
- * * Arrays are also valid using the formal `myobject.document[3].property`.
- *
- * @param {String} path
- * @returns {Object} parsed
- * @api private
- */
-
-function parsePath (path) {
- var str = path.replace(/\[/g, '.[')
- , parts = str.match(/(\\\.|[^.]+?)+/g);
- return parts.map(function (value) {
- var re = /\[(\d+)\]$/
- , mArr = re.exec(value)
- if (mArr) return { i: parseFloat(mArr[1]) };
- else return { p: value };
- });
-};
-
-/*!
- * ## _getPathValue(parsed, obj)
- *
- * Helper companion function for `.parsePath` that returns
- * the value located at the parsed address.
- *
- * var value = getPathValue(parsed, obj);
- *
- * @param {Object} parsed definition from `parsePath`.
- * @param {Object} object to search against
- * @returns {Object|Undefined} value
- * @api private
- */
-
-function _getPathValue (parsed, obj) {
- var tmp = obj
- , res;
- for (var i = 0, l = parsed.length; i < l; i++) {
- var part = parsed[i];
- if (tmp) {
- if ('undefined' !== typeof part.p)
- tmp = tmp[part.p];
- else if ('undefined' !== typeof part.i)
- tmp = tmp[part.i];
- if (i == (l - 1)) res = tmp;
- } else {
- res = undefined;
- }
- }
- return res;
-};
-
-}); // module: chai/utils/getPathValue.js
-
-require.register("chai/utils/index.js", function(module, exports, require){
-/*!
- * chai
- * Copyright(c) 2011 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/*!
- * Main exports
- */
-
-var exports = module.exports = {};
-
-/*!
- * test utility
- */
-
-exports.test = require('./test');
-
-/*!
- * message utility
- */
-
-exports.getMessage = require('./getMessage');
-
-/*!
- * actual utility
- */
-
-exports.getActual = require('./getActual');
-
-/*!
- * Inspect util
- */
-
-exports.inspect = require('./inspect');
-
-/*!
- * Flag utility
- */
-
-exports.flag = require('./flag');
-
-/*!
- * Flag transferring utility
- */
-
-exports.transferFlags = require('./transferFlags');
-
-/*!
- * Deep equal utility
- */
-
-exports.eql = require('./eql');
-
-/*!
- * Deep path value
- */
-
-exports.getPathValue = require('./getPathValue');
-
-/*!
- * Function name
- */
-
-exports.getName = require('./getName');
-
-/*!
- * add Property
- */
-
-exports.addProperty = require('./addProperty');
-
-/*!
- * add Method
- */
-
-exports.addMethod = require('./addMethod');
-
-/*!
- * overwrite Property
- */
-
-exports.overwriteProperty = require('./overwriteProperty');
-
-/*!
- * overwrite Method
- */
-
-exports.overwriteMethod = require('./overwriteMethod');
-
-/*!
- * Add a chainable method
- */
-
-exports.addChainableMethod = require('./addChainableMethod');
-
-
-}); // module: chai/utils/index.js
-
-require.register("chai/utils/inspect.js", function(module, exports, require){
-// This is (almost) directly from Node.js utils
-// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js
-
-var getName = require('./getName');
-
-module.exports = inspect;
-
-/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Boolean} showHidden Flag that shows hidden (not enumerable)
- * properties of objects.
- * @param {Number} depth Depth in which to descend in object. Default is 2.
- * @param {Boolean} colors Flag to turn on ANSI escape codes to color the
- * output. Default is false (no coloring).
- */
-function inspect(obj, showHidden, depth, colors) {
- var ctx = {
- showHidden: showHidden,
- seen: [],
- stylize: function (str) { return str; }
- };
- return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth));
-}
-
-function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (value && typeof value.inspect === 'function' &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- return value.inspect(recurseTimes);
- }
-
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
-
- // Look up the keys of the object.
- var visibleKeys = Object.keys(value);
- var keys = ctx.showHidden ? Object.getOwnPropertyNames(value) : visibleKeys;
-
- // Some type of object without properties can be shortcutted.
- // In IE, errors have a single `stack` property, or if they are vanilla `Error`,
- // a `stack` plus `description` property; ignore those for consistency.
- if (keys.length === 0 || (isError(value) && (
- (keys.length === 1 && keys[0] === 'stack') ||
- (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack')
- ))) {
- if (typeof value === 'function') {
- var name = getName(value);
- var nameSuffix = name ? ': ' + name : '';
- return ctx.stylize('[Function' + nameSuffix + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toUTCString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
-
- var base = '', array = false, braces = ['{', '}'];
-
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
-
- // Make functions say that they are functions
- if (typeof value === 'function') {
- var name = getName(value);
- var nameSuffix = name ? ': ' + name : '';
- base = ' [Function' + nameSuffix + ']';
- }
-
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
-
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
-
- // Make error with message first say the error
- if (isError(value)) {
- return formatError(value);
- }
-
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
-
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
-
- ctx.seen.push(value);
-
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
-
- ctx.seen.pop();
-
- return reduceToSingleString(output, base, braces);
-}
-
-
-function formatPrimitive(ctx, value) {
- switch (typeof value) {
- case 'undefined':
- return ctx.stylize('undefined', 'undefined');
-
- case 'string':
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
-
- case 'number':
- return ctx.stylize('' + value, 'number');
-
- case 'boolean':
- return ctx.stylize('' + value, 'boolean');
- }
- // For some reason typeof null is "object", so special case here.
- if (value === null) {
- return ctx.stylize('null', 'null');
- }
-}
-
-
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
-}
-
-
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (Object.prototype.hasOwnProperty.call(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
-}
-
-
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str;
- if (value.__lookupGetter__) {
- if (value.__lookupGetter__(key)) {
- if (value.__lookupSetter__(key)) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (value.__lookupSetter__(key)) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- }
- if (visibleKeys.indexOf(key) < 0) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(value[key]) < 0) {
- if (recurseTimes === null) {
- str = formatValue(ctx, value[key], null);
- } else {
- str = formatValue(ctx, value[key], recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (typeof name === 'undefined') {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
-
- return name + ': ' + str;
-}
-
-
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.length + 1;
- }, 0);
-
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
-
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
-
-function isArray(ar) {
- return Array.isArray(ar) ||
- (typeof ar === 'object' && objectToString(ar) === '[object Array]');
-}
-
-function isRegExp(re) {
- return typeof re === 'object' && objectToString(re) === '[object RegExp]';
-}
-
-function isDate(d) {
- return typeof d === 'object' && objectToString(d) === '[object Date]';
-}
-
-function isError(e) {
- return typeof e === 'object' && objectToString(e) === '[object Error]';
-}
-
-function objectToString(o) {
- return Object.prototype.toString.call(o);
-}
-
-}); // module: chai/utils/inspect.js
-
-require.register("chai/utils/overwriteMethod.js", function(module, exports, require){
-/*!
- * Chai - overwriteMethod utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/**
- * ### overwriteMethod (ctx, name, fn)
- *
- * Overwites an already existing method and provides
- * access to previous function. Must return function
- * to be used for name.
- *
- * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) {
- * return function (str) {
- * var obj = utils.flag(this, 'object');
- * if (obj instanceof Foo) {
- * new chai.Assertion(obj.value).to.equal(str);
- * } else {
- * _super.apply(this, arguments);
- * }
- * }
- * });
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- * chai.Assertion.overwriteMethod('foo', fn);
- *
- * Then can be used as any other assertion.
- *
- * expect(myFoo).to.equal('bar');
- *
- * @param {Object} ctx object whose method is to be overwritten
- * @param {String} name of method to overwrite
- * @param {Function} method function that returns a function to be used for name
- * @name overwriteMethod
- * @api public
- */
-
-module.exports = function (ctx, name, method) {
- var _method = ctx[name]
- , _super = function () { return this; };
-
- if (_method && 'function' === typeof _method)
- _super = _method;
-
- ctx[name] = function () {
- var result = method(_super).apply(this, arguments);
- return result === undefined ? this : result;
- }
-};
-
-}); // module: chai/utils/overwriteMethod.js
-
-require.register("chai/utils/overwriteProperty.js", function(module, exports, require){
-/*!
- * Chai - overwriteProperty utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/**
- * ### overwriteProperty (ctx, name, fn)
- *
- * Overwites an already existing property getter and provides
- * access to previous value. Must return function to use as getter.
- *
- * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) {
- * return function () {
- * var obj = utils.flag(this, 'object');
- * if (obj instanceof Foo) {
- * new chai.Assertion(obj.name).to.equal('bar');
- * } else {
- * _super.call(this);
- * }
- * }
- * });
- *
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- * chai.Assertion.overwriteProperty('foo', fn);
- *
- * Then can be used as any other assertion.
- *
- * expect(myFoo).to.be.ok;
- *
- * @param {Object} ctx object whose property is to be overwritten
- * @param {String} name of property to overwrite
- * @param {Function} getter function that returns a getter function to be used for name
- * @name overwriteProperty
- * @api public
- */
-
-module.exports = function (ctx, name, getter) {
- var _get = Object.getOwnPropertyDescriptor(ctx, name)
- , _super = function () {};
-
- if (_get && 'function' === typeof _get.get)
- _super = _get.get
-
- Object.defineProperty(ctx, name,
- { get: function () {
- var result = getter(_super).call(this);
- return result === undefined ? this : result;
- }
- , configurable: true
- });
-};
-
-}); // module: chai/utils/overwriteProperty.js
-
-require.register("chai/utils/test.js", function(module, exports, require){
-/*!
- * Chai - test utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/*!
- * Module dependancies
- */
-
-var flag = require('./flag');
-
-/**
- * # test(object, expression)
- *
- * Test and object for expression.
- *
- * @param {Object} object (constructed Assertion)
- * @param {Arguments} chai.Assertion.prototype.assert arguments
- */
-
-module.exports = function (obj, args) {
- var negate = flag(obj, 'negate')
- , expr = args[0];
- return negate ? !expr : expr;
-};
-
-}); // module: chai/utils/test.js
-
-require.register("chai/utils/transferFlags.js", function(module, exports, require){
-/*!
- * Chai - transferFlags utility
- * Copyright(c) 2012 Jake Luer <[email protected]>
- * MIT Licensed
- */
-
-/**
- * ### transferFlags(assertion, object, includeAll = true)
- *
- * Transfer all the flags for `assertion` to `object`. If
- * `includeAll` is set to `false`, then the base Chai
- * assertion flags (namely `object`, `ssfi`, and `message`)
- * will not be transferred.
- *
- *
- * var newAssertion = new Assertion();
- * utils.transferFlags(assertion, newAssertion);
- *
- * var anotherAsseriton = new Assertion(myObj);
- * utils.transferFlags(assertion, anotherAssertion, false);
- *
- * @param {Assertion} assertion the assertion to transfer the flags from
- * @param {Object} object the object to transfer the flags too; usually a new assertion
- * @param {Boolean} includeAll
- * @name getAllFlags
- * @api private
- */
-
-module.exports = function (assertion, object, includeAll) {
- var flags = assertion.__flags || (assertion.__flags = Object.create(null));
-
- if (!object.__flags) {
- object.__flags = Object.create(null);
- }
-
- includeAll = arguments.length === 3 ? includeAll : true;
-
- for (var flag in flags) {
- if (includeAll ||
- (flag !== 'object' && flag !== 'ssfi' && flag != 'message')) {
- object.__flags[flag] = flags[flag];
- }
- }
-};
-
-}); // module: chai/utils/transferFlags.js
-
-
- return require('chai');
-});
\ No newline at end of file
diff --git a/ckan/public-bs2/base/test/vendor/less.js b/ckan/public-bs2/base/test/vendor/less.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/vendor/less.js
+++ /dev/null
@@ -1,3478 +0,0 @@
-//
-// LESS - Leaner CSS v1.3.0
-// http://lesscss.org
-//
-// Copyright (c) 2009-2011, Alexis Sellier
-// Licensed under the Apache 2.0 License.
-//
-(function (window, undefined) {
-//
-// Stub out `require` in the browser
-//
-function require(arg) {
- return window.less[arg.split('/')[1]];
-};
-
-// amd.js
-//
-// Define Less as an AMD module.
-if (typeof define === "function" && define.amd) {
- define("less", [], function () { return less; } );
-}
-
-// ecma-5.js
-//
-// -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
-// -- tlrobinson Tom Robinson
-// dantman Daniel Friesen
-
-//
-// Array
-//
-if (!Array.isArray) {
- Array.isArray = function(obj) {
- return Object.prototype.toString.call(obj) === "[object Array]" ||
- (obj instanceof Array);
- };
-}
-if (!Array.prototype.forEach) {
- Array.prototype.forEach = function(block, thisObject) {
- var len = this.length >>> 0;
- for (var i = 0; i < len; i++) {
- if (i in this) {
- block.call(thisObject, this[i], i, this);
- }
- }
- };
-}
-if (!Array.prototype.map) {
- Array.prototype.map = function(fun /*, thisp*/) {
- var len = this.length >>> 0;
- var res = new Array(len);
- var thisp = arguments[1];
-
- for (var i = 0; i < len; i++) {
- if (i in this) {
- res[i] = fun.call(thisp, this[i], i, this);
- }
- }
- return res;
- };
-}
-if (!Array.prototype.filter) {
- Array.prototype.filter = function (block /*, thisp */) {
- var values = [];
- var thisp = arguments[1];
- for (var i = 0; i < this.length; i++) {
- if (block.call(thisp, this[i])) {
- values.push(this[i]);
- }
- }
- return values;
- };
-}
-if (!Array.prototype.reduce) {
- Array.prototype.reduce = function(fun /*, initial*/) {
- var len = this.length >>> 0;
- var i = 0;
-
- // no value to return if no initial value and an empty array
- if (len === 0 && arguments.length === 1) throw new TypeError();
-
- if (arguments.length >= 2) {
- var rv = arguments[1];
- } else {
- do {
- if (i in this) {
- rv = this[i++];
- break;
- }
- // if array contains no values, no initial value to return
- if (++i >= len) throw new TypeError();
- } while (true);
- }
- for (; i < len; i++) {
- if (i in this) {
- rv = fun.call(null, rv, this[i], i, this);
- }
- }
- return rv;
- };
-}
-if (!Array.prototype.indexOf) {
- Array.prototype.indexOf = function (value /*, fromIndex */ ) {
- var length = this.length;
- var i = arguments[1] || 0;
-
- if (!length) return -1;
- if (i >= length) return -1;
- if (i < 0) i += length;
-
- for (; i < length; i++) {
- if (!Object.prototype.hasOwnProperty.call(this, i)) { continue }
- if (value === this[i]) return i;
- }
- return -1;
- };
-}
-
-//
-// Object
-//
-if (!Object.keys) {
- Object.keys = function (object) {
- var keys = [];
- for (var name in object) {
- if (Object.prototype.hasOwnProperty.call(object, name)) {
- keys.push(name);
- }
- }
- return keys;
- };
-}
-
-//
-// String
-//
-if (!String.prototype.trim) {
- String.prototype.trim = function () {
- return String(this).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
- };
-}
-var less, tree;
-
-if (typeof environment === "object" && ({}).toString.call(environment) === "[object Environment]") {
- // Rhino
- // Details on how to detect Rhino: https://github.com/ringo/ringojs/issues/88
- if (typeof(window) === 'undefined') { less = {} }
- else { less = window.less = {} }
- tree = less.tree = {};
- less.mode = 'rhino';
-} else if (typeof(window) === 'undefined') {
- // Node.js
- less = exports,
- tree = require('./tree');
- less.mode = 'node';
-} else {
- // Browser
- if (typeof(window.less) === 'undefined') { window.less = {} }
- less = window.less,
- tree = window.less.tree = {};
- less.mode = 'browser';
-}
-//
-// less.js - parser
-//
-// A relatively straight-forward predictive parser.
-// There is no tokenization/lexing stage, the input is parsed
-// in one sweep.
-//
-// To make the parser fast enough to run in the browser, several
-// optimization had to be made:
-//
-// - Matching and slicing on a huge input is often cause of slowdowns.
-// The solution is to chunkify the input into smaller strings.
-// The chunks are stored in the `chunks` var,
-// `j` holds the current chunk index, and `current` holds
-// the index of the current chunk in relation to `input`.
-// This gives us an almost 4x speed-up.
-//
-// - In many cases, we don't need to match individual tokens;
-// for example, if a value doesn't hold any variables, operations
-// or dynamic references, the parser can effectively 'skip' it,
-// treating it as a literal.
-// An example would be '1px solid #000' - which evaluates to itself,
-// we don't need to know what the individual components are.
-// The drawback, of course is that you don't get the benefits of
-// syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
-// and a smaller speed-up in the code-gen.
-//
-//
-// Token matching is done with the `$` function, which either takes
-// a terminal string or regexp, or a non-terminal function to call.
-// It also takes care of moving all the indices forwards.
-//
-//
-less.Parser = function Parser(env) {
- var input, // LeSS input string
- i, // current index in `input`
- j, // current chunk
- temp, // temporarily holds a chunk's state, for backtracking
- memo, // temporarily holds `i`, when backtracking
- furthest, // furthest index the parser has gone to
- chunks, // chunkified input
- current, // index of current chunk, in `input`
- parser;
-
- var that = this;
-
- // This function is called after all files
- // have been imported through `@import`.
- var finish = function () {};
-
- var imports = this.imports = {
- paths: env && env.paths || [], // Search paths, when importing
- queue: [], // Files which haven't been imported yet
- files: {}, // Holds the imported parse trees
- contents: {}, // Holds the imported file contents
- mime: env && env.mime, // MIME type of .less files
- error: null, // Error in parsing/evaluating an import
- push: function (path, callback) {
- var that = this;
- this.queue.push(path);
-
- //
- // Import a file asynchronously
- //
- less.Parser.importer(path, this.paths, function (e, root, contents) {
- that.queue.splice(that.queue.indexOf(path), 1); // Remove the path from the queue
- that.files[path] = root; // Store the root
- that.contents[path] = contents;
-
- if (e && !that.error) { that.error = e }
- callback(e, root);
-
- if (that.queue.length === 0) { finish() } // Call `finish` if we're done importing
- }, env);
- }
- };
-
- function save() { temp = chunks[j], memo = i, current = i }
- function restore() { chunks[j] = temp, i = memo, current = i }
-
- function sync() {
- if (i > current) {
- chunks[j] = chunks[j].slice(i - current);
- current = i;
- }
- }
- //
- // Parse from a token, regexp or string, and move forward if match
- //
- function $(tok) {
- var match, args, length, c, index, endIndex, k, mem;
-
- //
- // Non-terminal
- //
- if (tok instanceof Function) {
- return tok.call(parser.parsers);
- //
- // Terminal
- //
- // Either match a single character in the input,
- // or match a regexp in the current chunk (chunk[j]).
- //
- } else if (typeof(tok) === 'string') {
- match = input.charAt(i) === tok ? tok : null;
- length = 1;
- sync ();
- } else {
- sync ();
-
- if (match = tok.exec(chunks[j])) {
- length = match[0].length;
- } else {
- return null;
- }
- }
-
- // The match is confirmed, add the match length to `i`,
- // and consume any extra white-space characters (' ' || '\n')
- // which come after that. The reason for this is that LeSS's
- // grammar is mostly white-space insensitive.
- //
- if (match) {
- mem = i += length;
- endIndex = i + chunks[j].length - length;
-
- while (i < endIndex) {
- c = input.charCodeAt(i);
- if (! (c === 32 || c === 10 || c === 9)) { break }
- i++;
- }
- chunks[j] = chunks[j].slice(length + (i - mem));
- current = i;
-
- if (chunks[j].length === 0 && j < chunks.length - 1) { j++ }
-
- if(typeof(match) === 'string') {
- return match;
- } else {
- return match.length === 1 ? match[0] : match;
- }
- }
- }
-
- function expect(arg, msg) {
- var result = $(arg);
- if (! result) {
- error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + input.charAt(i) + "'"
- : "unexpected token"));
- } else {
- return result;
- }
- }
-
- function error(msg, type) {
- throw { index: i, type: type || 'Syntax', message: msg };
- }
-
- // Same as $(), but don't change the state of the parser,
- // just return the match.
- function peek(tok) {
- if (typeof(tok) === 'string') {
- return input.charAt(i) === tok;
- } else {
- if (tok.test(chunks[j])) {
- return true;
- } else {
- return false;
- }
- }
- }
-
- function basename(pathname) {
- if (less.mode === 'node') {
- return require('path').basename(pathname);
- } else {
- return pathname.match(/[^\/]+$/)[0];
- }
- }
-
- function getInput(e, env) {
- if (e.filename && env.filename && (e.filename !== env.filename)) {
- return parser.imports.contents[basename(e.filename)] || "";
- } else {
- return input;
- }
- }
-
- function getLocation(index, input) {
- for (var n = index, column = -1;
- n >= 0 && input.charAt(n) !== '\n';
- n--) { column++ }
-
- return { line: typeof(index) === 'number' ? (input.slice(0, index).match(/\n/g) || "").length : null,
- column: column };
- }
-
- function LessError(e, env) {
- var input = getInput(e, env),
- loc = getLocation(e.index, input),
- line = loc.line,
- col = loc.column,
- lines = input.split('\n');
-
- this.type = e.type || 'Syntax';
- this.message = e.message;
- this.filename = e.filename || env.filename;
- this.index = e.index;
- this.line = typeof(line) === 'number' ? line + 1 : null;
- this.callLine = e.call && (getLocation(e.call, input).line + 1);
- this.callExtract = lines[getLocation(e.call, input).line];
- this.stack = e.stack;
- this.column = col;
- this.extract = [
- lines[line - 1],
- lines[line],
- lines[line + 1]
- ];
- }
-
- this.env = env = env || {};
-
- // The optimization level dictates the thoroughness of the parser,
- // the lower the number, the less nodes it will create in the tree.
- // This could matter for debugging, or if you want to access
- // the individual nodes in the tree.
- this.optimization = ('optimization' in this.env) ? this.env.optimization : 1;
-
- this.env.filename = this.env.filename || null;
-
- //
- // The Parser
- //
- return parser = {
-
- imports: imports,
- //
- // Parse an input string into an abstract syntax tree,
- // call `callback` when done.
- //
- parse: function (str, callback) {
- var root, start, end, zone, line, lines, buff = [], c, error = null;
-
- i = j = current = furthest = 0;
- input = str.replace(/\r\n/g, '\n');
-
- // Split the input into chunks.
- chunks = (function (chunks) {
- var j = 0,
- skip = /[^"'`\{\}\/\(\)\\]+/g,
- comment = /\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g,
- string = /"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|`((?:[^`\\\r\n]|\\.)*)`/g,
- level = 0,
- match,
- chunk = chunks[0],
- inParam;
-
- for (var i = 0, c, cc; i < input.length; i++) {
- skip.lastIndex = i;
- if (match = skip.exec(input)) {
- if (match.index === i) {
- i += match[0].length;
- chunk.push(match[0]);
- }
- }
- c = input.charAt(i);
- comment.lastIndex = string.lastIndex = i;
-
- if (match = string.exec(input)) {
- if (match.index === i) {
- i += match[0].length;
- chunk.push(match[0]);
- c = input.charAt(i);
- }
- }
-
- if (!inParam && c === '/') {
- cc = input.charAt(i + 1);
- if (cc === '/' || cc === '*') {
- if (match = comment.exec(input)) {
- if (match.index === i) {
- i += match[0].length;
- chunk.push(match[0]);
- c = input.charAt(i);
- }
- }
- }
- }
-
- switch (c) {
- case '{': if (! inParam) { level ++; chunk.push(c); break }
- case '}': if (! inParam) { level --; chunk.push(c); chunks[++j] = chunk = []; break }
- case '(': if (! inParam) { inParam = true; chunk.push(c); break }
- case ')': if ( inParam) { inParam = false; chunk.push(c); break }
- default: chunk.push(c);
- }
- }
- if (level > 0) {
- error = new(LessError)({
- index: i,
- type: 'Parse',
- message: "missing closing `}`",
- filename: env.filename
- }, env);
- }
-
- return chunks.map(function (c) { return c.join('') });;
- })([[]]);
-
- if (error) {
- return callback(error);
- }
-
- // Start with the primary rule.
- // The whole syntax tree is held under a Ruleset node,
- // with the `root` property set to true, so no `{}` are
- // output. The callback is called when the input is parsed.
- try {
- root = new(tree.Ruleset)([], $(this.parsers.primary));
- root.root = true;
- } catch (e) {
- return callback(new(LessError)(e, env));
- }
-
- root.toCSS = (function (evaluate) {
- var line, lines, column;
-
- return function (options, variables) {
- var frames = [], importError;
-
- options = options || {};
- //
- // Allows setting variables with a hash, so:
- //
- // `{ color: new(tree.Color)('#f01') }` will become:
- //
- // new(tree.Rule)('@color',
- // new(tree.Value)([
- // new(tree.Expression)([
- // new(tree.Color)('#f01')
- // ])
- // ])
- // )
- //
- if (typeof(variables) === 'object' && !Array.isArray(variables)) {
- variables = Object.keys(variables).map(function (k) {
- var value = variables[k];
-
- if (! (value instanceof tree.Value)) {
- if (! (value instanceof tree.Expression)) {
- value = new(tree.Expression)([value]);
- }
- value = new(tree.Value)([value]);
- }
- return new(tree.Rule)('@' + k, value, false, 0);
- });
- frames = [new(tree.Ruleset)(null, variables)];
- }
-
- try {
- var css = evaluate.call(this, { frames: frames })
- .toCSS([], { compress: options.compress || false });
- } catch (e) {
- throw new(LessError)(e, env);
- }
-
- if ((importError = parser.imports.error)) { // Check if there was an error during importing
- if (importError instanceof LessError) throw importError;
- else throw new(LessError)(importError, env);
- }
-
- if (options.yuicompress && less.mode === 'node') {
- return require('./cssmin').compressor.cssmin(css);
- } else if (options.compress) {
- return css.replace(/(\s)+/g, "$1");
- } else {
- return css;
- }
- };
- })(root.eval);
-
- // If `i` is smaller than the `input.length - 1`,
- // it means the parser wasn't able to parse the whole
- // string, so we've got a parsing error.
- //
- // We try to extract a \n delimited string,
- // showing the line where the parse error occured.
- // We split it up into two parts (the part which parsed,
- // and the part which didn't), so we can color them differently.
- if (i < input.length - 1) {
- i = furthest;
- lines = input.split('\n');
- line = (input.slice(0, i).match(/\n/g) || "").length + 1;
-
- for (var n = i, column = -1; n >= 0 && input.charAt(n) !== '\n'; n--) { column++ }
-
- error = {
- type: "Parse",
- message: "Syntax Error on line " + line,
- index: i,
- filename: env.filename,
- line: line,
- column: column,
- extract: [
- lines[line - 2],
- lines[line - 1],
- lines[line]
- ]
- };
- }
-
- if (this.imports.queue.length > 0) {
- finish = function () { callback(error, root) };
- } else {
- callback(error, root);
- }
- },
-
- //
- // Here in, the parsing rules/functions
- //
- // The basic structure of the syntax tree generated is as follows:
- //
- // Ruleset -> Rule -> Value -> Expression -> Entity
- //
- // Here's some LESS code:
- //
- // .class {
- // color: #fff;
- // border: 1px solid #000;
- // width: @w + 4px;
- // > .child {...}
- // }
- //
- // And here's what the parse tree might look like:
- //
- // Ruleset (Selector '.class', [
- // Rule ("color", Value ([Expression [Color #fff]]))
- // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
- // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]]))
- // Ruleset (Selector [Element '>', '.child'], [...])
- // ])
- //
- // In general, most rules will try to parse a token with the `$()` function, and if the return
- // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
- // first, before parsing, that's when we use `peek()`.
- //
- parsers: {
- //
- // The `primary` rule is the *entry* and *exit* point of the parser.
- // The rules here can appear at any level of the parse tree.
- //
- // The recursive nature of the grammar is an interplay between the `block`
- // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
- // as represented by this simplified grammar:
- //
- // primary → (ruleset | rule)+
- // ruleset → selector+ block
- // block → '{' primary '}'
- //
- // Only at one point is the primary rule not called from the
- // block rule: at the root level.
- //
- primary: function () {
- var node, root = [];
-
- while ((node = $(this.mixin.definition) || $(this.rule) || $(this.ruleset) ||
- $(this.mixin.call) || $(this.comment) || $(this.directive))
- || $(/^[\s\n]+/)) {
- node && root.push(node);
- }
- return root;
- },
-
- // We create a Comment node for CSS comments `/* */`,
- // but keep the LeSS comments `//` silent, by just skipping
- // over them.
- comment: function () {
- var comment;
-
- if (input.charAt(i) !== '/') return;
-
- if (input.charAt(i + 1) === '/') {
- return new(tree.Comment)($(/^\/\/.*/), true);
- } else if (comment = $(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/)) {
- return new(tree.Comment)(comment);
- }
- },
-
- //
- // Entities are tokens which can be found inside an Expression
- //
- entities: {
- //
- // A string, which supports escaping " and '
- //
- // "milky way" 'he\'s the one!'
- //
- quoted: function () {
- var str, j = i, e;
-
- if (input.charAt(j) === '~') { j++, e = true } // Escaped strings
- if (input.charAt(j) !== '"' && input.charAt(j) !== "'") return;
-
- e && $('~');
-
- if (str = $(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/)) {
- return new(tree.Quoted)(str[0], str[1] || str[2], e);
- }
- },
-
- //
- // A catch-all word, such as:
- //
- // black border-collapse
- //
- keyword: function () {
- var k;
-
- if (k = $(/^[_A-Za-z-][_A-Za-z0-9-]*/)) {
- if (tree.colors.hasOwnProperty(k)) {
- // detect named color
- return new(tree.Color)(tree.colors[k].slice(1));
- } else {
- return new(tree.Keyword)(k);
- }
- }
- },
-
- //
- // A function call
- //
- // rgb(255, 0, 255)
- //
- // We also try to catch IE's `alpha()`, but let the `alpha` parser
- // deal with the details.
- //
- // The arguments are parsed with the `entities.arguments` parser.
- //
- call: function () {
- var name, args, index = i;
-
- if (! (name = /^([\w-]+|%|progid:[\w\.]+)\(/.exec(chunks[j]))) return;
-
- name = name[1].toLowerCase();
-
- if (name === 'url') { return null }
- else { i += name.length }
-
- if (name === 'alpha') { return $(this.alpha) }
-
- $('('); // Parse the '(' and consume whitespace.
-
- args = $(this.entities.arguments);
-
- if (! $(')')) return;
-
- if (name) { return new(tree.Call)(name, args, index, env.filename) }
- },
- arguments: function () {
- var args = [], arg;
-
- while (arg = $(this.entities.assignment) || $(this.expression)) {
- args.push(arg);
- if (! $(',')) { break }
- }
- return args;
- },
- literal: function () {
- return $(this.entities.dimension) ||
- $(this.entities.color) ||
- $(this.entities.quoted);
- },
-
- // Assignments are argument entities for calls.
- // They are present in ie filter properties as shown below.
- //
- // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
- //
-
- assignment: function () {
- var key, value;
- if ((key = $(/^\w+(?=\s?=)/i)) && $('=') && (value = $(this.entity))) {
- return new(tree.Assignment)(key, value);
- }
- },
-
- //
- // Parse url() tokens
- //
- // We use a specific rule for urls, because they don't really behave like
- // standard function calls. The difference is that the argument doesn't have
- // to be enclosed within a string, so it can't be parsed as an Expression.
- //
- url: function () {
- var value;
-
- if (input.charAt(i) !== 'u' || !$(/^url\(/)) return;
- value = $(this.entities.quoted) || $(this.entities.variable) ||
- $(this.entities.dataURI) || $(/^[-\w%@$\/.&=:;#+?~]+/) || "";
-
- expect(')');
-
- return new(tree.URL)((value.value || value.data || value instanceof tree.Variable)
- ? value : new(tree.Anonymous)(value), imports.paths);
- },
-
- dataURI: function () {
- var obj;
-
- if ($(/^data:/)) {
- obj = {};
- obj.mime = $(/^[^\/]+\/[^,;)]+/) || '';
- obj.charset = $(/^;\s*charset=[^,;)]+/) || '';
- obj.base64 = $(/^;\s*base64/) || '';
- obj.data = $(/^,\s*[^)]+/);
-
- if (obj.data) { return obj }
- }
- },
-
- //
- // A Variable entity, such as `@fink`, in
- //
- // width: @fink + 2px
- //
- // We use a different parser for variable definitions,
- // see `parsers.variable`.
- //
- variable: function () {
- var name, index = i;
-
- if (input.charAt(i) === '@' && (name = $(/^@@?[\w-]+/))) {
- return new(tree.Variable)(name, index, env.filename);
- }
- },
-
- //
- // A Hexadecimal color
- //
- // #4F3C2F
- //
- // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
- //
- color: function () {
- var rgb;
-
- if (input.charAt(i) === '#' && (rgb = $(/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})/))) {
- return new(tree.Color)(rgb[1]);
- }
- },
-
- //
- // A Dimension, that is, a number and a unit
- //
- // 0.5em 95%
- //
- dimension: function () {
- var value, c = input.charCodeAt(i);
- if ((c > 57 || c < 45) || c === 47) return;
-
- if (value = $(/^(-?\d*\.?\d+)(px|%|em|rem|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn)?/)) {
- return new(tree.Dimension)(value[1], value[2]);
- }
- },
-
- //
- // JavaScript code to be evaluated
- //
- // `window.location.href`
- //
- javascript: function () {
- var str, j = i, e;
-
- if (input.charAt(j) === '~') { j++, e = true } // Escaped strings
- if (input.charAt(j) !== '`') { return }
-
- e && $('~');
-
- if (str = $(/^`([^`]*)`/)) {
- return new(tree.JavaScript)(str[1], i, e);
- }
- }
- },
-
- //
- // The variable part of a variable definition. Used in the `rule` parser
- //
- // @fink:
- //
- variable: function () {
- var name;
-
- if (input.charAt(i) === '@' && (name = $(/^(@[\w-]+)\s*:/))) { return name[1] }
- },
-
- //
- // A font size/line-height shorthand
- //
- // small/12px
- //
- // We need to peek first, or we'll match on keywords and dimensions
- //
- shorthand: function () {
- var a, b;
-
- if (! peek(/^[@\w.%-]+\/[@\w.-]+/)) return;
-
- if ((a = $(this.entity)) && $('/') && (b = $(this.entity))) {
- return new(tree.Shorthand)(a, b);
- }
- },
-
- //
- // Mixins
- //
- mixin: {
- //
- // A Mixin call, with an optional argument list
- //
- // #mixins > .square(#fff);
- // .rounded(4px, black);
- // .button;
- //
- // The `while` loop is there because mixins can be
- // namespaced, but we only support the child and descendant
- // selector for now.
- //
- call: function () {
- var elements = [], e, c, args, index = i, s = input.charAt(i), important = false;
-
- if (s !== '.' && s !== '#') { return }
-
- while (e = $(/^[#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/)) {
- elements.push(new(tree.Element)(c, e, i));
- c = $('>');
- }
- $('(') && (args = $(this.entities.arguments)) && $(')');
-
- if ($(this.important)) {
- important = true;
- }
-
- if (elements.length > 0 && ($(';') || peek('}'))) {
- return new(tree.mixin.Call)(elements, args || [], index, env.filename, important);
- }
- },
-
- //
- // A Mixin definition, with a list of parameters
- //
- // .rounded (@radius: 2px, @color) {
- // ...
- // }
- //
- // Until we have a finer grained state-machine, we have to
- // do a look-ahead, to make sure we don't have a mixin call.
- // See the `rule` function for more information.
- //
- // We start by matching `.rounded (`, and then proceed on to
- // the argument list, which has optional default values.
- // We store the parameters in `params`, with a `value` key,
- // if there is a value, such as in the case of `@radius`.
- //
- // Once we've got our params list, and a closing `)`, we parse
- // the `{...}` block.
- //
- definition: function () {
- var name, params = [], match, ruleset, param, value, cond, variadic = false;
- if ((input.charAt(i) !== '.' && input.charAt(i) !== '#') ||
- peek(/^[^{]*(;|})/)) return;
-
- save();
-
- if (match = $(/^([#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+)\s*\(/)) {
- name = match[1];
-
- do {
- if (input.charAt(i) === '.' && $(/^\.{3}/)) {
- variadic = true;
- break;
- } else if (param = $(this.entities.variable) || $(this.entities.literal)
- || $(this.entities.keyword)) {
- // Variable
- if (param instanceof tree.Variable) {
- if ($(':')) {
- value = expect(this.expression, 'expected expression');
- params.push({ name: param.name, value: value });
- } else if ($(/^\.{3}/)) {
- params.push({ name: param.name, variadic: true });
- variadic = true;
- break;
- } else {
- params.push({ name: param.name });
- }
- } else {
- params.push({ value: param });
- }
- } else {
- break;
- }
- } while ($(','))
-
- expect(')');
-
- if ($(/^when/)) { // Guard
- cond = expect(this.conditions, 'expected condition');
- }
-
- ruleset = $(this.block);
-
- if (ruleset) {
- return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic);
- } else {
- restore();
- }
- }
- }
- },
-
- //
- // Entities are the smallest recognized token,
- // and can be found inside a rule's value.
- //
- entity: function () {
- return $(this.entities.literal) || $(this.entities.variable) || $(this.entities.url) ||
- $(this.entities.call) || $(this.entities.keyword) || $(this.entities.javascript) ||
- $(this.comment);
- },
-
- //
- // A Rule terminator. Note that we use `peek()` to check for '}',
- // because the `block` rule will be expecting it, but we still need to make sure
- // it's there, if ';' was ommitted.
- //
- end: function () {
- return $(';') || peek('}');
- },
-
- //
- // IE's alpha function
- //
- // alpha(opacity=88)
- //
- alpha: function () {
- var value;
-
- if (! $(/^\(opacity=/i)) return;
- if (value = $(/^\d+/) || $(this.entities.variable)) {
- expect(')');
- return new(tree.Alpha)(value);
- }
- },
-
- //
- // A Selector Element
- //
- // div
- // + h1
- // #socks
- // input[type="text"]
- //
- // Elements are the building blocks for Selectors,
- // they are made out of a `Combinator` (see combinator rule),
- // and an element name, such as a tag a class, or `*`.
- //
- element: function () {
- var e, t, c, v;
-
- c = $(this.combinator);
- e = $(/^(?:\d+\.\d+|\d+)%/) || $(/^(?:[.#]?|:*)(?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/) ||
- $('*') || $(this.attribute) || $(/^\([^)@]+\)/);
-
- if (! e) {
- $('(') && (v = $(this.entities.variable)) && $(')') && (e = new(tree.Paren)(v));
- }
-
- if (e) { return new(tree.Element)(c, e, i) }
-
- if (c.value && c.value.charAt(0) === '&') {
- return new(tree.Element)(c, null, i);
- }
- },
-
- //
- // Combinators combine elements together, in a Selector.
- //
- // Because our parser isn't white-space sensitive, special care
- // has to be taken, when parsing the descendant combinator, ` `,
- // as it's an empty space. We have to check the previous character
- // in the input, to see if it's a ` ` character. More info on how
- // we deal with this in *combinator.js*.
- //
- combinator: function () {
- var match, c = input.charAt(i);
-
- if (c === '>' || c === '+' || c === '~') {
- i++;
- while (input.charAt(i) === ' ') { i++ }
- return new(tree.Combinator)(c);
- } else if (c === '&') {
- match = '&';
- i++;
- if(input.charAt(i) === ' ') {
- match = '& ';
- }
- while (input.charAt(i) === ' ') { i++ }
- return new(tree.Combinator)(match);
- } else if (input.charAt(i - 1) === ' ') {
- return new(tree.Combinator)(" ");
- } else {
- return new(tree.Combinator)(null);
- }
- },
-
- //
- // A CSS Selector
- //
- // .class > div + h1
- // li a:hover
- //
- // Selectors are made out of one or more Elements, see above.
- //
- selector: function () {
- var sel, e, elements = [], c, match;
-
- if ($('(')) {
- sel = $(this.entity);
- expect(')');
- return new(tree.Selector)([new(tree.Element)('', sel, i)]);
- }
-
- while (e = $(this.element)) {
- c = input.charAt(i);
- elements.push(e)
- if (c === '{' || c === '}' || c === ';' || c === ',') { break }
- }
-
- if (elements.length > 0) { return new(tree.Selector)(elements) }
- },
- tag: function () {
- return $(/^[a-zA-Z][a-zA-Z-]*[0-9]?/) || $('*');
- },
- attribute: function () {
- var attr = '', key, val, op;
-
- if (! $('[')) return;
-
- if (key = $(/^[a-zA-Z-]+/) || $(this.entities.quoted)) {
- if ((op = $(/^[|~*$^]?=/)) &&
- (val = $(this.entities.quoted) || $(/^[\w-]+/))) {
- attr = [key, op, val.toCSS ? val.toCSS() : val].join('');
- } else { attr = key }
- }
-
- if (! $(']')) return;
-
- if (attr) { return "[" + attr + "]" }
- },
-
- //
- // The `block` rule is used by `ruleset` and `mixin.definition`.
- // It's a wrapper around the `primary` rule, with added `{}`.
- //
- block: function () {
- var content;
-
- if ($('{') && (content = $(this.primary)) && $('}')) {
- return content;
- }
- },
-
- //
- // div, .class, body > p {...}
- //
- ruleset: function () {
- var selectors = [], s, rules, match;
- save();
-
- while (s = $(this.selector)) {
- selectors.push(s);
- $(this.comment);
- if (! $(',')) { break }
- $(this.comment);
- }
-
- if (selectors.length > 0 && (rules = $(this.block))) {
- return new(tree.Ruleset)(selectors, rules, env.strictImports);
- } else {
- // Backtrack
- furthest = i;
- restore();
- }
- },
- rule: function () {
- var name, value, c = input.charAt(i), important, match;
- save();
-
- if (c === '.' || c === '#' || c === '&') { return }
-
- if (name = $(this.variable) || $(this.property)) {
- if ((name.charAt(0) != '@') && (match = /^([^@+\/'"*`(;{}-]*);/.exec(chunks[j]))) {
- i += match[0].length - 1;
- value = new(tree.Anonymous)(match[1]);
- } else if (name === "font") {
- value = $(this.font);
- } else {
- value = $(this.value);
- }
- important = $(this.important);
-
- if (value && $(this.end)) {
- return new(tree.Rule)(name, value, important, memo);
- } else {
- furthest = i;
- restore();
- }
- }
- },
-
- //
- // An @import directive
- //
- // @import "lib";
- //
- // Depending on our environemnt, importing is done differently:
- // In the browser, it's an XHR request, in Node, it would be a
- // file-system operation. The function used for importing is
- // stored in `import`, which we pass to the Import constructor.
- //
- "import": function () {
- var path, features, index = i;
- if ($(/^@import\s+/) &&
- (path = $(this.entities.quoted) || $(this.entities.url))) {
- features = $(this.mediaFeatures);
- if ($(';')) {
- return new(tree.Import)(path, imports, features, index);
- }
- }
- },
-
- mediaFeature: function () {
- var e, p, nodes = [];
-
- do {
- if (e = $(this.entities.keyword)) {
- nodes.push(e);
- } else if ($('(')) {
- p = $(this.property);
- e = $(this.entity);
- if ($(')')) {
- if (p && e) {
- nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, i, true)));
- } else if (e) {
- nodes.push(new(tree.Paren)(e));
- } else {
- return null;
- }
- } else { return null }
- }
- } while (e);
-
- if (nodes.length > 0) {
- return new(tree.Expression)(nodes);
- }
- },
-
- mediaFeatures: function () {
- var e, features = [];
-
- do {
- if (e = $(this.mediaFeature)) {
- features.push(e);
- if (! $(',')) { break }
- } else if (e = $(this.entities.variable)) {
- features.push(e);
- if (! $(',')) { break }
- }
- } while (e);
-
- return features.length > 0 ? features : null;
- },
-
- media: function () {
- var features, rules;
-
- if ($(/^@media/)) {
- features = $(this.mediaFeatures);
-
- if (rules = $(this.block)) {
- return new(tree.Media)(rules, features);
- }
- }
- },
-
- //
- // A CSS Directive
- //
- // @charset "utf-8";
- //
- directive: function () {
- var name, value, rules, types, e, nodes;
-
- if (input.charAt(i) !== '@') return;
-
- if (value = $(this['import']) || $(this.media)) {
- return value;
- } else if (name = $(/^@page|@keyframes/) || $(/^@(?:-webkit-|-moz-|-o-|-ms-)[a-z0-9-]+/)) {
- types = ($(/^[^{]+/) || '').trim();
- if (rules = $(this.block)) {
- return new(tree.Directive)(name + " " + types, rules);
- }
- } else if (name = $(/^@[-a-z]+/)) {
- if (name === '@font-face') {
- if (rules = $(this.block)) {
- return new(tree.Directive)(name, rules);
- }
- } else if ((value = $(this.entity)) && $(';')) {
- return new(tree.Directive)(name, value);
- }
- }
- },
- font: function () {
- var value = [], expression = [], weight, shorthand, font, e;
-
- while (e = $(this.shorthand) || $(this.entity)) {
- expression.push(e);
- }
- value.push(new(tree.Expression)(expression));
-
- if ($(',')) {
- while (e = $(this.expression)) {
- value.push(e);
- if (! $(',')) { break }
- }
- }
- return new(tree.Value)(value);
- },
-
- //
- // A Value is a comma-delimited list of Expressions
- //
- // font-family: Baskerville, Georgia, serif;
- //
- // In a Rule, a Value represents everything after the `:`,
- // and before the `;`.
- //
- value: function () {
- var e, expressions = [], important;
-
- while (e = $(this.expression)) {
- expressions.push(e);
- if (! $(',')) { break }
- }
-
- if (expressions.length > 0) {
- return new(tree.Value)(expressions);
- }
- },
- important: function () {
- if (input.charAt(i) === '!') {
- return $(/^! *important/);
- }
- },
- sub: function () {
- var e;
-
- if ($('(') && (e = $(this.expression)) && $(')')) {
- return e;
- }
- },
- multiplication: function () {
- var m, a, op, operation;
- if (m = $(this.operand)) {
- while (!peek(/^\/\*/) && (op = ($('/') || $('*'))) && (a = $(this.operand))) {
- operation = new(tree.Operation)(op, [operation || m, a]);
- }
- return operation || m;
- }
- },
- addition: function () {
- var m, a, op, operation;
- if (m = $(this.multiplication)) {
- while ((op = $(/^[-+]\s+/) || (input.charAt(i - 1) != ' ' && ($('+') || $('-')))) &&
- (a = $(this.multiplication))) {
- operation = new(tree.Operation)(op, [operation || m, a]);
- }
- return operation || m;
- }
- },
- conditions: function () {
- var a, b, index = i, condition;
-
- if (a = $(this.condition)) {
- while ($(',') && (b = $(this.condition))) {
- condition = new(tree.Condition)('or', condition || a, b, index);
- }
- return condition || a;
- }
- },
- condition: function () {
- var a, b, c, op, index = i, negate = false;
-
- if ($(/^not/)) { negate = true }
- expect('(');
- if (a = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) {
- if (op = $(/^(?:>=|=<|[<=>])/)) {
- if (b = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) {
- c = new(tree.Condition)(op, a, b, index, negate);
- } else {
- error('expected expression');
- }
- } else {
- c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate);
- }
- expect(')');
- return $(/^and/) ? new(tree.Condition)('and', c, $(this.condition)) : c;
- }
- },
-
- //
- // An operand is anything that can be part of an operation,
- // such as a Color, or a Variable
- //
- operand: function () {
- var negate, p = input.charAt(i + 1);
-
- if (input.charAt(i) === '-' && (p === '@' || p === '(')) { negate = $('-') }
- var o = $(this.sub) || $(this.entities.dimension) ||
- $(this.entities.color) || $(this.entities.variable) ||
- $(this.entities.call);
- return negate ? new(tree.Operation)('*', [new(tree.Dimension)(-1), o])
- : o;
- },
-
- //
- // Expressions either represent mathematical operations,
- // or white-space delimited Entities.
- //
- // 1px solid black
- // @var * 2
- //
- expression: function () {
- var e, delim, entities = [], d;
-
- while (e = $(this.addition) || $(this.entity)) {
- entities.push(e);
- }
- if (entities.length > 0) {
- return new(tree.Expression)(entities);
- }
- },
- property: function () {
- var name;
-
- if (name = $(/^(\*?-?[-a-z_0-9]+)\s*:/)) {
- return name[1];
- }
- }
- }
- };
-};
-
-if (less.mode === 'browser' || less.mode === 'rhino') {
- //
- // Used by `@import` directives
- //
- less.Parser.importer = function (path, paths, callback, env) {
- if (!/^([a-z]+:)?\//.test(path) && paths.length > 0) {
- path = paths[0] + path;
- }
- // We pass `true` as 3rd argument, to force the reload of the import.
- // This is so we can get the syntax tree as opposed to just the CSS output,
- // as we need this to evaluate the current stylesheet.
- loadStyleSheet({ href: path, title: path, type: env.mime }, function (e) {
- if (e && typeof(env.errback) === "function") {
- env.errback.call(null, path, paths, callback, env);
- } else {
- callback.apply(null, arguments);
- }
- }, true);
- };
-}
-
-(function (tree) {
-
-tree.functions = {
- rgb: function (r, g, b) {
- return this.rgba(r, g, b, 1.0);
- },
- rgba: function (r, g, b, a) {
- var rgb = [r, g, b].map(function (c) { return number(c) }),
- a = number(a);
- return new(tree.Color)(rgb, a);
- },
- hsl: function (h, s, l) {
- return this.hsla(h, s, l, 1.0);
- },
- hsla: function (h, s, l, a) {
- h = (number(h) % 360) / 360;
- s = number(s); l = number(l); a = number(a);
-
- var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
- var m1 = l * 2 - m2;
-
- return this.rgba(hue(h + 1/3) * 255,
- hue(h) * 255,
- hue(h - 1/3) * 255,
- a);
-
- function hue(h) {
- h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
- if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
- else if (h * 2 < 1) return m2;
- else if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;
- else return m1;
- }
- },
- hue: function (color) {
- return new(tree.Dimension)(Math.round(color.toHSL().h));
- },
- saturation: function (color) {
- return new(tree.Dimension)(Math.round(color.toHSL().s * 100), '%');
- },
- lightness: function (color) {
- return new(tree.Dimension)(Math.round(color.toHSL().l * 100), '%');
- },
- alpha: function (color) {
- return new(tree.Dimension)(color.toHSL().a);
- },
- saturate: function (color, amount) {
- var hsl = color.toHSL();
-
- hsl.s += amount.value / 100;
- hsl.s = clamp(hsl.s);
- return hsla(hsl);
- },
- desaturate: function (color, amount) {
- var hsl = color.toHSL();
-
- hsl.s -= amount.value / 100;
- hsl.s = clamp(hsl.s);
- return hsla(hsl);
- },
- lighten: function (color, amount) {
- var hsl = color.toHSL();
-
- hsl.l += amount.value / 100;
- hsl.l = clamp(hsl.l);
- return hsla(hsl);
- },
- darken: function (color, amount) {
- var hsl = color.toHSL();
-
- hsl.l -= amount.value / 100;
- hsl.l = clamp(hsl.l);
- return hsla(hsl);
- },
- fadein: function (color, amount) {
- var hsl = color.toHSL();
-
- hsl.a += amount.value / 100;
- hsl.a = clamp(hsl.a);
- return hsla(hsl);
- },
- fadeout: function (color, amount) {
- var hsl = color.toHSL();
-
- hsl.a -= amount.value / 100;
- hsl.a = clamp(hsl.a);
- return hsla(hsl);
- },
- fade: function (color, amount) {
- var hsl = color.toHSL();
-
- hsl.a = amount.value / 100;
- hsl.a = clamp(hsl.a);
- return hsla(hsl);
- },
- spin: function (color, amount) {
- var hsl = color.toHSL();
- var hue = (hsl.h + amount.value) % 360;
-
- hsl.h = hue < 0 ? 360 + hue : hue;
-
- return hsla(hsl);
- },
- //
- // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein
- // http://sass-lang.com
- //
- mix: function (color1, color2, weight) {
- var p = weight.value / 100.0;
- var w = p * 2 - 1;
- var a = color1.toHSL().a - color2.toHSL().a;
-
- var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
- var w2 = 1 - w1;
-
- var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
- color1.rgb[1] * w1 + color2.rgb[1] * w2,
- color1.rgb[2] * w1 + color2.rgb[2] * w2];
-
- var alpha = color1.alpha * p + color2.alpha * (1 - p);
-
- return new(tree.Color)(rgb, alpha);
- },
- greyscale: function (color) {
- return this.desaturate(color, new(tree.Dimension)(100));
- },
- e: function (str) {
- return new(tree.Anonymous)(str instanceof tree.JavaScript ? str.evaluated : str);
- },
- escape: function (str) {
- return new(tree.Anonymous)(encodeURI(str.value).replace(/=/g, "%3D").replace(/:/g, "%3A").replace(/#/g, "%23").replace(/;/g, "%3B").replace(/\(/g, "%28").replace(/\)/g, "%29"));
- },
- '%': function (quoted /* arg, arg, ...*/) {
- var args = Array.prototype.slice.call(arguments, 1),
- str = quoted.value;
-
- for (var i = 0; i < args.length; i++) {
- str = str.replace(/%[sda]/i, function(token) {
- var value = token.match(/s/i) ? args[i].value : args[i].toCSS();
- return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
- });
- }
- str = str.replace(/%%/g, '%');
- return new(tree.Quoted)('"' + str + '"', str);
- },
- round: function (n) {
- return this._math('round', n);
- },
- ceil: function (n) {
- return this._math('ceil', n);
- },
- floor: function (n) {
- return this._math('floor', n);
- },
- _math: function (fn, n) {
- if (n instanceof tree.Dimension) {
- return new(tree.Dimension)(Math[fn](number(n)), n.unit);
- } else if (typeof(n) === 'number') {
- return Math[fn](n);
- } else {
- throw { type: "Argument", message: "argument must be a number" };
- }
- },
- argb: function (color) {
- return new(tree.Anonymous)(color.toARGB());
-
- },
- percentage: function (n) {
- return new(tree.Dimension)(n.value * 100, '%');
- },
- color: function (n) {
- if (n instanceof tree.Quoted) {
- return new(tree.Color)(n.value.slice(1));
- } else {
- throw { type: "Argument", message: "argument must be a string" };
- }
- },
- iscolor: function (n) {
- return this._isa(n, tree.Color);
- },
- isnumber: function (n) {
- return this._isa(n, tree.Dimension);
- },
- isstring: function (n) {
- return this._isa(n, tree.Quoted);
- },
- iskeyword: function (n) {
- return this._isa(n, tree.Keyword);
- },
- isurl: function (n) {
- return this._isa(n, tree.URL);
- },
- ispixel: function (n) {
- return (n instanceof tree.Dimension) && n.unit === 'px' ? tree.True : tree.False;
- },
- ispercentage: function (n) {
- return (n instanceof tree.Dimension) && n.unit === '%' ? tree.True : tree.False;
- },
- isem: function (n) {
- return (n instanceof tree.Dimension) && n.unit === 'em' ? tree.True : tree.False;
- },
- _isa: function (n, Type) {
- return (n instanceof Type) ? tree.True : tree.False;
- }
-};
-
-function hsla(hsla) {
- return tree.functions.hsla(hsla.h, hsla.s, hsla.l, hsla.a);
-}
-
-function number(n) {
- if (n instanceof tree.Dimension) {
- return parseFloat(n.unit == '%' ? n.value / 100 : n.value);
- } else if (typeof(n) === 'number') {
- return n;
- } else {
- throw {
- error: "RuntimeError",
- message: "color functions take numbers as parameters"
- };
- }
-}
-
-function clamp(val) {
- return Math.min(1, Math.max(0, val));
-}
-
-})(require('./tree'));
-(function (tree) {
- tree.colors = {
- 'aliceblue':'#f0f8ff',
- 'antiquewhite':'#faebd7',
- 'aqua':'#00ffff',
- 'aquamarine':'#7fffd4',
- 'azure':'#f0ffff',
- 'beige':'#f5f5dc',
- 'bisque':'#ffe4c4',
- 'black':'#000000',
- 'blanchedalmond':'#ffebcd',
- 'blue':'#0000ff',
- 'blueviolet':'#8a2be2',
- 'brown':'#a52a2a',
- 'burlywood':'#deb887',
- 'cadetblue':'#5f9ea0',
- 'chartreuse':'#7fff00',
- 'chocolate':'#d2691e',
- 'coral':'#ff7f50',
- 'cornflowerblue':'#6495ed',
- 'cornsilk':'#fff8dc',
- 'crimson':'#dc143c',
- 'cyan':'#00ffff',
- 'darkblue':'#00008b',
- 'darkcyan':'#008b8b',
- 'darkgoldenrod':'#b8860b',
- 'darkgray':'#a9a9a9',
- 'darkgrey':'#a9a9a9',
- 'darkgreen':'#006400',
- 'darkkhaki':'#bdb76b',
- 'darkmagenta':'#8b008b',
- 'darkolivegreen':'#556b2f',
- 'darkorange':'#ff8c00',
- 'darkorchid':'#9932cc',
- 'darkred':'#8b0000',
- 'darksalmon':'#e9967a',
- 'darkseagreen':'#8fbc8f',
- 'darkslateblue':'#483d8b',
- 'darkslategray':'#2f4f4f',
- 'darkslategrey':'#2f4f4f',
- 'darkturquoise':'#00ced1',
- 'darkviolet':'#9400d3',
- 'deeppink':'#ff1493',
- 'deepskyblue':'#00bfff',
- 'dimgray':'#696969',
- 'dimgrey':'#696969',
- 'dodgerblue':'#1e90ff',
- 'firebrick':'#b22222',
- 'floralwhite':'#fffaf0',
- 'forestgreen':'#228b22',
- 'fuchsia':'#ff00ff',
- 'gainsboro':'#dcdcdc',
- 'ghostwhite':'#f8f8ff',
- 'gold':'#ffd700',
- 'goldenrod':'#daa520',
- 'gray':'#808080',
- 'grey':'#808080',
- 'green':'#008000',
- 'greenyellow':'#adff2f',
- 'honeydew':'#f0fff0',
- 'hotpink':'#ff69b4',
- 'indianred':'#cd5c5c',
- 'indigo':'#4b0082',
- 'ivory':'#fffff0',
- 'khaki':'#f0e68c',
- 'lavender':'#e6e6fa',
- 'lavenderblush':'#fff0f5',
- 'lawngreen':'#7cfc00',
- 'lemonchiffon':'#fffacd',
- 'lightblue':'#add8e6',
- 'lightcoral':'#f08080',
- 'lightcyan':'#e0ffff',
- 'lightgoldenrodyellow':'#fafad2',
- 'lightgray':'#d3d3d3',
- 'lightgrey':'#d3d3d3',
- 'lightgreen':'#90ee90',
- 'lightpink':'#ffb6c1',
- 'lightsalmon':'#ffa07a',
- 'lightseagreen':'#20b2aa',
- 'lightskyblue':'#87cefa',
- 'lightslategray':'#778899',
- 'lightslategrey':'#778899',
- 'lightsteelblue':'#b0c4de',
- 'lightyellow':'#ffffe0',
- 'lime':'#00ff00',
- 'limegreen':'#32cd32',
- 'linen':'#faf0e6',
- 'magenta':'#ff00ff',
- 'maroon':'#800000',
- 'mediumaquamarine':'#66cdaa',
- 'mediumblue':'#0000cd',
- 'mediumorchid':'#ba55d3',
- 'mediumpurple':'#9370d8',
- 'mediumseagreen':'#3cb371',
- 'mediumslateblue':'#7b68ee',
- 'mediumspringgreen':'#00fa9a',
- 'mediumturquoise':'#48d1cc',
- 'mediumvioletred':'#c71585',
- 'midnightblue':'#191970',
- 'mintcream':'#f5fffa',
- 'mistyrose':'#ffe4e1',
- 'moccasin':'#ffe4b5',
- 'navajowhite':'#ffdead',
- 'navy':'#000080',
- 'oldlace':'#fdf5e6',
- 'olive':'#808000',
- 'olivedrab':'#6b8e23',
- 'orange':'#ffa500',
- 'orangered':'#ff4500',
- 'orchid':'#da70d6',
- 'palegoldenrod':'#eee8aa',
- 'palegreen':'#98fb98',
- 'paleturquoise':'#afeeee',
- 'palevioletred':'#d87093',
- 'papayawhip':'#ffefd5',
- 'peachpuff':'#ffdab9',
- 'peru':'#cd853f',
- 'pink':'#ffc0cb',
- 'plum':'#dda0dd',
- 'powderblue':'#b0e0e6',
- 'purple':'#800080',
- 'red':'#ff0000',
- 'rosybrown':'#bc8f8f',
- 'royalblue':'#4169e1',
- 'saddlebrown':'#8b4513',
- 'salmon':'#fa8072',
- 'sandybrown':'#f4a460',
- 'seagreen':'#2e8b57',
- 'seashell':'#fff5ee',
- 'sienna':'#a0522d',
- 'silver':'#c0c0c0',
- 'skyblue':'#87ceeb',
- 'slateblue':'#6a5acd',
- 'slategray':'#708090',
- 'slategrey':'#708090',
- 'snow':'#fffafa',
- 'springgreen':'#00ff7f',
- 'steelblue':'#4682b4',
- 'tan':'#d2b48c',
- 'teal':'#008080',
- 'thistle':'#d8bfd8',
- 'tomato':'#ff6347',
- 'turquoise':'#40e0d0',
- 'violet':'#ee82ee',
- 'wheat':'#f5deb3',
- 'white':'#ffffff',
- 'whitesmoke':'#f5f5f5',
- 'yellow':'#ffff00',
- 'yellowgreen':'#9acd32'
- };
-})(require('./tree'));
-(function (tree) {
-
-tree.Alpha = function (val) {
- this.value = val;
-};
-tree.Alpha.prototype = {
- toCSS: function () {
- return "alpha(opacity=" +
- (this.value.toCSS ? this.value.toCSS() : this.value) + ")";
- },
- eval: function (env) {
- if (this.value.eval) { this.value = this.value.eval(env) }
- return this;
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Anonymous = function (string) {
- this.value = string.value || string;
-};
-tree.Anonymous.prototype = {
- toCSS: function () {
- return this.value;
- },
- eval: function () { return this }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Assignment = function (key, val) {
- this.key = key;
- this.value = val;
-};
-tree.Assignment.prototype = {
- toCSS: function () {
- return this.key + '=' + (this.value.toCSS ? this.value.toCSS() : this.value);
- },
- eval: function (env) {
- if (this.value.eval) { this.value = this.value.eval(env) }
- return this;
- }
-};
-
-})(require('../tree'));(function (tree) {
-
-//
-// A function call node.
-//
-tree.Call = function (name, args, index, filename) {
- this.name = name;
- this.args = args;
- this.index = index;
- this.filename = filename;
-};
-tree.Call.prototype = {
- //
- // When evaluating a function call,
- // we either find the function in `tree.functions` [1],
- // in which case we call it, passing the evaluated arguments,
- // or we simply print it out as it appeared originally [2].
- //
- // The *functions.js* file contains the built-in functions.
- //
- // The reason why we evaluate the arguments, is in the case where
- // we try to pass a variable to a function, like: `saturate(@color)`.
- // The function should receive the value, not the variable.
- //
- eval: function (env) {
- var args = this.args.map(function (a) { return a.eval(env) });
-
- if (this.name in tree.functions) { // 1.
- try {
- return tree.functions[this.name].apply(tree.functions, args);
- } catch (e) {
- throw { type: e.type || "Runtime",
- message: "error evaluating function `" + this.name + "`" +
- (e.message ? ': ' + e.message : ''),
- index: this.index, filename: this.filename };
- }
- } else { // 2.
- return new(tree.Anonymous)(this.name +
- "(" + args.map(function (a) { return a.toCSS() }).join(', ') + ")");
- }
- },
-
- toCSS: function (env) {
- return this.eval(env).toCSS();
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-//
-// RGB Colors - #ff0014, #eee
-//
-tree.Color = function (rgb, a) {
- //
- // The end goal here, is to parse the arguments
- // into an integer triplet, such as `128, 255, 0`
- //
- // This facilitates operations and conversions.
- //
- if (Array.isArray(rgb)) {
- this.rgb = rgb;
- } else if (rgb.length == 6) {
- this.rgb = rgb.match(/.{2}/g).map(function (c) {
- return parseInt(c, 16);
- });
- } else {
- this.rgb = rgb.split('').map(function (c) {
- return parseInt(c + c, 16);
- });
- }
- this.alpha = typeof(a) === 'number' ? a : 1;
-};
-tree.Color.prototype = {
- eval: function () { return this },
-
- //
- // If we have some transparency, the only way to represent it
- // is via `rgba`. Otherwise, we use the hex representation,
- // which has better compatibility with older browsers.
- // Values are capped between `0` and `255`, rounded and zero-padded.
- //
- toCSS: function () {
- if (this.alpha < 1.0) {
- return "rgba(" + this.rgb.map(function (c) {
- return Math.round(c);
- }).concat(this.alpha).join(', ') + ")";
- } else {
- return '#' + this.rgb.map(function (i) {
- i = Math.round(i);
- i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16);
- return i.length === 1 ? '0' + i : i;
- }).join('');
- }
- },
-
- //
- // Operations have to be done per-channel, if not,
- // channels will spill onto each other. Once we have
- // our result, in the form of an integer triplet,
- // we create a new Color node to hold the result.
- //
- operate: function (op, other) {
- var result = [];
-
- if (! (other instanceof tree.Color)) {
- other = other.toColor();
- }
-
- for (var c = 0; c < 3; c++) {
- result[c] = tree.operate(op, this.rgb[c], other.rgb[c]);
- }
- return new(tree.Color)(result, this.alpha + other.alpha);
- },
-
- toHSL: function () {
- var r = this.rgb[0] / 255,
- g = this.rgb[1] / 255,
- b = this.rgb[2] / 255,
- a = this.alpha;
-
- var max = Math.max(r, g, b), min = Math.min(r, g, b);
- var h, s, l = (max + min) / 2, d = max - min;
-
- if (max === min) {
- h = s = 0;
- } else {
- s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
-
- switch (max) {
- case r: h = (g - b) / d + (g < b ? 6 : 0); break;
- case g: h = (b - r) / d + 2; break;
- case b: h = (r - g) / d + 4; break;
- }
- h /= 6;
- }
- return { h: h * 360, s: s, l: l, a: a };
- },
- toARGB: function () {
- var argb = [Math.round(this.alpha * 255)].concat(this.rgb);
- return '#' + argb.map(function (i) {
- i = Math.round(i);
- i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16);
- return i.length === 1 ? '0' + i : i;
- }).join('');
- }
-};
-
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Comment = function (value, silent) {
- this.value = value;
- this.silent = !!silent;
-};
-tree.Comment.prototype = {
- toCSS: function (env) {
- return env.compress ? '' : this.value;
- },
- eval: function () { return this }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Condition = function (op, l, r, i, negate) {
- this.op = op.trim();
- this.lvalue = l;
- this.rvalue = r;
- this.index = i;
- this.negate = negate;
-};
-tree.Condition.prototype.eval = function (env) {
- var a = this.lvalue.eval(env),
- b = this.rvalue.eval(env);
-
- var i = this.index, result;
-
- var result = (function (op) {
- switch (op) {
- case 'and':
- return a && b;
- case 'or':
- return a || b;
- default:
- if (a.compare) {
- result = a.compare(b);
- } else if (b.compare) {
- result = b.compare(a);
- } else {
- throw { type: "Type",
- message: "Unable to perform comparison",
- index: i };
- }
- switch (result) {
- case -1: return op === '<' || op === '=<';
- case 0: return op === '=' || op === '>=' || op === '=<';
- case 1: return op === '>' || op === '>=';
- }
- }
- })(this.op);
- return this.negate ? !result : result;
-};
-
-})(require('../tree'));
-(function (tree) {
-
-//
-// A number with a unit
-//
-tree.Dimension = function (value, unit) {
- this.value = parseFloat(value);
- this.unit = unit || null;
-};
-
-tree.Dimension.prototype = {
- eval: function () { return this },
- toColor: function () {
- return new(tree.Color)([this.value, this.value, this.value]);
- },
- toCSS: function () {
- var css = this.value + this.unit;
- return css;
- },
-
- // In an operation between two Dimensions,
- // we default to the first Dimension's unit,
- // so `1px + 2em` will yield `3px`.
- // In the future, we could implement some unit
- // conversions such that `100cm + 10mm` would yield
- // `101cm`.
- operate: function (op, other) {
- return new(tree.Dimension)
- (tree.operate(op, this.value, other.value),
- this.unit || other.unit);
- },
-
- // TODO: Perform unit conversion before comparing
- compare: function (other) {
- if (other instanceof tree.Dimension) {
- if (other.value > this.value) {
- return -1;
- } else if (other.value < this.value) {
- return 1;
- } else {
- return 0;
- }
- } else {
- return -1;
- }
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Directive = function (name, value, features) {
- this.name = name;
-
- if (Array.isArray(value)) {
- this.ruleset = new(tree.Ruleset)([], value);
- this.ruleset.allowImports = true;
- } else {
- this.value = value;
- }
-};
-tree.Directive.prototype = {
- toCSS: function (ctx, env) {
- if (this.ruleset) {
- this.ruleset.root = true;
- return this.name + (env.compress ? '{' : ' {\n ') +
- this.ruleset.toCSS(ctx, env).trim().replace(/\n/g, '\n ') +
- (env.compress ? '}': '\n}\n');
- } else {
- return this.name + ' ' + this.value.toCSS() + ';\n';
- }
- },
- eval: function (env) {
- env.frames.unshift(this);
- this.ruleset = this.ruleset && this.ruleset.eval(env);
- env.frames.shift();
- return this;
- },
- variable: function (name) { return tree.Ruleset.prototype.variable.call(this.ruleset, name) },
- find: function () { return tree.Ruleset.prototype.find.apply(this.ruleset, arguments) },
- rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.ruleset) }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Element = function (combinator, value, index) {
- this.combinator = combinator instanceof tree.Combinator ?
- combinator : new(tree.Combinator)(combinator);
-
- if (typeof(value) === 'string') {
- this.value = value.trim();
- } else if (value) {
- this.value = value;
- } else {
- this.value = "";
- }
- this.index = index;
-};
-tree.Element.prototype.eval = function (env) {
- return new(tree.Element)(this.combinator,
- this.value.eval ? this.value.eval(env) : this.value,
- this.index);
-};
-tree.Element.prototype.toCSS = function (env) {
- return this.combinator.toCSS(env || {}) + (this.value.toCSS ? this.value.toCSS(env) : this.value);
-};
-
-tree.Combinator = function (value) {
- if (value === ' ') {
- this.value = ' ';
- } else if (value === '& ') {
- this.value = '& ';
- } else {
- this.value = value ? value.trim() : "";
- }
-};
-tree.Combinator.prototype.toCSS = function (env) {
- return {
- '' : '',
- ' ' : ' ',
- '&' : '',
- '& ' : ' ',
- ':' : ' :',
- '+' : env.compress ? '+' : ' + ',
- '~' : env.compress ? '~' : ' ~ ',
- '>' : env.compress ? '>' : ' > '
- }[this.value];
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Expression = function (value) { this.value = value };
-tree.Expression.prototype = {
- eval: function (env) {
- if (this.value.length > 1) {
- return new(tree.Expression)(this.value.map(function (e) {
- return e.eval(env);
- }));
- } else if (this.value.length === 1) {
- return this.value[0].eval(env);
- } else {
- return this;
- }
- },
- toCSS: function (env) {
- return this.value.map(function (e) {
- return e.toCSS ? e.toCSS(env) : '';
- }).join(' ');
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-//
-// CSS @import node
-//
-// The general strategy here is that we don't want to wait
-// for the parsing to be completed, before we start importing
-// the file. That's because in the context of a browser,
-// most of the time will be spent waiting for the server to respond.
-//
-// On creation, we push the import path to our import queue, though
-// `import,push`, we also pass it a callback, which it'll call once
-// the file has been fetched, and parsed.
-//
-tree.Import = function (path, imports, features, index) {
- var that = this;
-
- this.index = index;
- this._path = path;
- this.features = features && new(tree.Value)(features);
-
- // The '.less' extension is optional
- if (path instanceof tree.Quoted) {
- this.path = /\.(le?|c)ss(\?.*)?$/.test(path.value) ? path.value : path.value + '.less';
- } else {
- this.path = path.value.value || path.value;
- }
-
- this.css = /css(\?.*)?$/.test(this.path);
-
- // Only pre-compile .less files
- if (! this.css) {
- imports.push(this.path, function (e, root) {
- if (e) { e.index = index }
- that.root = root || new(tree.Ruleset)([], []);
- });
- }
-};
-
-//
-// The actual import node doesn't return anything, when converted to CSS.
-// The reason is that it's used at the evaluation stage, so that the rules
-// it imports can be treated like any other rules.
-//
-// In `eval`, we make sure all Import nodes get evaluated, recursively, so
-// we end up with a flat structure, which can easily be imported in the parent
-// ruleset.
-//
-tree.Import.prototype = {
- toCSS: function (env) {
- var features = this.features ? ' ' + this.features.toCSS(env) : '';
-
- if (this.css) {
- return "@import " + this._path.toCSS() + features + ';\n';
- } else {
- return "";
- }
- },
- eval: function (env) {
- var ruleset, features = this.features && this.features.eval(env);
-
- if (this.css) {
- return this;
- } else {
- ruleset = new(tree.Ruleset)([], this.root.rules.slice(0));
-
- for (var i = 0; i < ruleset.rules.length; i++) {
- if (ruleset.rules[i] instanceof tree.Import) {
- Array.prototype
- .splice
- .apply(ruleset.rules,
- [i, 1].concat(ruleset.rules[i].eval(env)));
- }
- }
- return this.features ? new(tree.Media)(ruleset.rules, this.features.value) : ruleset.rules;
- }
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.JavaScript = function (string, index, escaped) {
- this.escaped = escaped;
- this.expression = string;
- this.index = index;
-};
-tree.JavaScript.prototype = {
- eval: function (env) {
- var result,
- that = this,
- context = {};
-
- var expression = this.expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
- return tree.jsify(new(tree.Variable)('@' + name, that.index).eval(env));
- });
-
- try {
- expression = new(Function)('return (' + expression + ')');
- } catch (e) {
- throw { message: "JavaScript evaluation error: `" + expression + "`" ,
- index: this.index };
- }
-
- for (var k in env.frames[0].variables()) {
- context[k.slice(1)] = {
- value: env.frames[0].variables()[k].value,
- toJS: function () {
- return this.value.eval(env).toCSS();
- }
- };
- }
-
- try {
- result = expression.call(context);
- } catch (e) {
- throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message + "'" ,
- index: this.index };
- }
- if (typeof(result) === 'string') {
- return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index);
- } else if (Array.isArray(result)) {
- return new(tree.Anonymous)(result.join(', '));
- } else {
- return new(tree.Anonymous)(result);
- }
- }
-};
-
-})(require('../tree'));
-
-(function (tree) {
-
-tree.Keyword = function (value) { this.value = value };
-tree.Keyword.prototype = {
- eval: function () { return this },
- toCSS: function () { return this.value },
- compare: function (other) {
- if (other instanceof tree.Keyword) {
- return other.value === this.value ? 0 : 1;
- } else {
- return -1;
- }
- }
-};
-
-tree.True = new(tree.Keyword)('true');
-tree.False = new(tree.Keyword)('false');
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Media = function (value, features) {
- var el = new(tree.Element)('&', null, 0),
- selectors = [new(tree.Selector)([el])];
-
- this.features = new(tree.Value)(features);
- this.ruleset = new(tree.Ruleset)(selectors, value);
- this.ruleset.allowImports = true;
-};
-tree.Media.prototype = {
- toCSS: function (ctx, env) {
- var features = this.features.toCSS(env);
-
- this.ruleset.root = (ctx.length === 0 || ctx[0].multiMedia);
- return '@media ' + features + (env.compress ? '{' : ' {\n ') +
- this.ruleset.toCSS(ctx, env).trim().replace(/\n/g, '\n ') +
- (env.compress ? '}': '\n}\n');
- },
- eval: function (env) {
- if (!env.mediaBlocks) {
- env.mediaBlocks = [];
- env.mediaPath = [];
- }
-
- var blockIndex = env.mediaBlocks.length;
- env.mediaPath.push(this);
- env.mediaBlocks.push(this);
-
- var media = new(tree.Media)([], []);
- media.features = this.features.eval(env);
-
- env.frames.unshift(this.ruleset);
- media.ruleset = this.ruleset.eval(env);
- env.frames.shift();
-
- env.mediaBlocks[blockIndex] = media;
- env.mediaPath.pop();
-
- return env.mediaPath.length === 0 ? media.evalTop(env) :
- media.evalNested(env)
- },
- variable: function (name) { return tree.Ruleset.prototype.variable.call(this.ruleset, name) },
- find: function () { return tree.Ruleset.prototype.find.apply(this.ruleset, arguments) },
- rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.ruleset) },
-
- evalTop: function (env) {
- var result = this;
-
- // Render all dependent Media blocks.
- if (env.mediaBlocks.length > 1) {
- var el = new(tree.Element)('&', null, 0);
- var selectors = [new(tree.Selector)([el])];
- result = new(tree.Ruleset)(selectors, env.mediaBlocks);
- result.multiMedia = true;
- }
-
- delete env.mediaBlocks;
- delete env.mediaPath;
-
- return result;
- },
- evalNested: function (env) {
- var i, value,
- path = env.mediaPath.concat([this]);
-
- // Extract the media-query conditions separated with `,` (OR).
- for (i = 0; i < path.length; i++) {
- value = path[i].features instanceof tree.Value ?
- path[i].features.value : path[i].features;
- path[i] = Array.isArray(value) ? value : [value];
- }
-
- // Trace all permutations to generate the resulting media-query.
- //
- // (a, b and c) with nested (d, e) ->
- // a and d
- // a and e
- // b and c and d
- // b and c and e
- this.features = new(tree.Value)(this.permute(path).map(function (path) {
- path = path.map(function (fragment) {
- return fragment.toCSS ? fragment : new(tree.Anonymous)(fragment);
- });
-
- for(i = path.length - 1; i > 0; i--) {
- path.splice(i, 0, new(tree.Anonymous)("and"));
- }
-
- return new(tree.Expression)(path);
- }));
-
- // Fake a tree-node that doesn't output anything.
- return new(tree.Ruleset)([], []);
- },
- permute: function (arr) {
- if (arr.length === 0) {
- return [];
- } else if (arr.length === 1) {
- return arr[0];
- } else {
- var result = [];
- var rest = this.permute(arr.slice(1));
- for (var i = 0; i < rest.length; i++) {
- for (var j = 0; j < arr[0].length; j++) {
- result.push([arr[0][j]].concat(rest[i]));
- }
- }
- return result;
- }
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.mixin = {};
-tree.mixin.Call = function (elements, args, index, filename, important) {
- this.selector = new(tree.Selector)(elements);
- this.arguments = args;
- this.index = index;
- this.filename = filename;
- this.important = important;
-};
-tree.mixin.Call.prototype = {
- eval: function (env) {
- var mixins, args, rules = [], match = false;
-
- for (var i = 0; i < env.frames.length; i++) {
- if ((mixins = env.frames[i].find(this.selector)).length > 0) {
- args = this.arguments && this.arguments.map(function (a) { return a.eval(env) });
- for (var m = 0; m < mixins.length; m++) {
- if (mixins[m].match(args, env)) {
- try {
- Array.prototype.push.apply(
- rules, mixins[m].eval(env, this.arguments, this.important).rules);
- match = true;
- } catch (e) {
- throw { message: e.message, index: this.index, filename: this.filename, stack: e.stack };
- }
- }
- }
- if (match) {
- return rules;
- } else {
- throw { type: 'Runtime',
- message: 'No matching definition was found for `' +
- this.selector.toCSS().trim() + '(' +
- this.arguments.map(function (a) {
- return a.toCSS();
- }).join(', ') + ")`",
- index: this.index, filename: this.filename };
- }
- }
- }
- throw { type: 'Name',
- message: this.selector.toCSS().trim() + " is undefined",
- index: this.index, filename: this.filename };
- }
-};
-
-tree.mixin.Definition = function (name, params, rules, condition, variadic) {
- this.name = name;
- this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])];
- this.params = params;
- this.condition = condition;
- this.variadic = variadic;
- this.arity = params.length;
- this.rules = rules;
- this._lookups = {};
- this.required = params.reduce(function (count, p) {
- if (!p.name || (p.name && !p.value)) { return count + 1 }
- else { return count }
- }, 0);
- this.parent = tree.Ruleset.prototype;
- this.frames = [];
-};
-tree.mixin.Definition.prototype = {
- toCSS: function () { return "" },
- variable: function (name) { return this.parent.variable.call(this, name) },
- variables: function () { return this.parent.variables.call(this) },
- find: function () { return this.parent.find.apply(this, arguments) },
- rulesets: function () { return this.parent.rulesets.apply(this) },
-
- evalParams: function (env, args) {
- var frame = new(tree.Ruleset)(null, []), varargs;
-
- for (var i = 0, val, name; i < this.params.length; i++) {
- if (name = this.params[i].name) {
- if (this.params[i].variadic && args) {
- varargs = [];
- for (var j = i; j < args.length; j++) {
- varargs.push(args[j].eval(env));
- }
- frame.rules.unshift(new(tree.Rule)(name, new(tree.Expression)(varargs).eval(env)));
- } else if (val = (args && args[i]) || this.params[i].value) {
- frame.rules.unshift(new(tree.Rule)(name, val.eval(env)));
- } else {
- throw { type: 'Runtime', message: "wrong number of arguments for " + this.name +
- ' (' + args.length + ' for ' + this.arity + ')' };
- }
- }
- }
- return frame;
- },
- eval: function (env, args, important) {
- var frame = this.evalParams(env, args), context, _arguments = [], rules, start;
-
- for (var i = 0; i < Math.max(this.params.length, args && args.length); i++) {
- _arguments.push(args[i] || this.params[i].value);
- }
- frame.rules.unshift(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env)));
-
- rules = important ?
- this.rules.map(function (r) {
- return new(tree.Rule)(r.name, r.value, '!important', r.index);
- }) : this.rules.slice(0);
-
- return new(tree.Ruleset)(null, rules).eval({
- frames: [this, frame].concat(this.frames, env.frames)
- });
- },
- match: function (args, env) {
- var argsLength = (args && args.length) || 0, len, frame;
-
- if (! this.variadic) {
- if (argsLength < this.required) { return false }
- if (argsLength > this.params.length) { return false }
- if ((this.required > 0) && (argsLength > this.params.length)) { return false }
- }
-
- if (this.condition && !this.condition.eval({
- frames: [this.evalParams(env, args)].concat(env.frames)
- })) { return false }
-
- len = Math.min(argsLength, this.arity);
-
- for (var i = 0; i < len; i++) {
- if (!this.params[i].name) {
- if (args[i].eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) {
- return false;
- }
- }
- }
- return true;
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Operation = function (op, operands) {
- this.op = op.trim();
- this.operands = operands;
-};
-tree.Operation.prototype.eval = function (env) {
- var a = this.operands[0].eval(env),
- b = this.operands[1].eval(env),
- temp;
-
- if (a instanceof tree.Dimension && b instanceof tree.Color) {
- if (this.op === '*' || this.op === '+') {
- temp = b, b = a, a = temp;
- } else {
- throw { name: "OperationError",
- message: "Can't substract or divide a color from a number" };
- }
- }
- return a.operate(this.op, b);
-};
-
-tree.operate = function (op, a, b) {
- switch (op) {
- case '+': return a + b;
- case '-': return a - b;
- case '*': return a * b;
- case '/': return a / b;
- }
-};
-
-})(require('../tree'));
-
-(function (tree) {
-
-tree.Paren = function (node) {
- this.value = node;
-};
-tree.Paren.prototype = {
- toCSS: function (env) {
- return '(' + this.value.toCSS(env) + ')';
- },
- eval: function (env) {
- return new(tree.Paren)(this.value.eval(env));
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Quoted = function (str, content, escaped, i) {
- this.escaped = escaped;
- this.value = content || '';
- this.quote = str.charAt(0);
- this.index = i;
-};
-tree.Quoted.prototype = {
- toCSS: function () {
- if (this.escaped) {
- return this.value;
- } else {
- return this.quote + this.value + this.quote;
- }
- },
- eval: function (env) {
- var that = this;
- var value = this.value.replace(/`([^`]+)`/g, function (_, exp) {
- return new(tree.JavaScript)(exp, that.index, true).eval(env).value;
- }).replace(/@\{([\w-]+)\}/g, function (_, name) {
- var v = new(tree.Variable)('@' + name, that.index).eval(env);
- return ('value' in v) ? v.value : v.toCSS();
- });
- return new(tree.Quoted)(this.quote + value + this.quote, value, this.escaped, this.index);
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Rule = function (name, value, important, index, inline) {
- this.name = name;
- this.value = (value instanceof tree.Value) ? value : new(tree.Value)([value]);
- this.important = important ? ' ' + important.trim() : '';
- this.index = index;
- this.inline = inline || false;
-
- if (name.charAt(0) === '@') {
- this.variable = true;
- } else { this.variable = false }
-};
-tree.Rule.prototype.toCSS = function (env) {
- if (this.variable) { return "" }
- else {
- return this.name + (env.compress ? ':' : ': ') +
- this.value.toCSS(env) +
- this.important + (this.inline ? "" : ";");
- }
-};
-
-tree.Rule.prototype.eval = function (context) {
- return new(tree.Rule)(this.name,
- this.value.eval(context),
- this.important,
- this.index, this.inline);
-};
-
-tree.Shorthand = function (a, b) {
- this.a = a;
- this.b = b;
-};
-
-tree.Shorthand.prototype = {
- toCSS: function (env) {
- return this.a.toCSS(env) + "/" + this.b.toCSS(env);
- },
- eval: function () { return this }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Ruleset = function (selectors, rules, strictImports) {
- this.selectors = selectors;
- this.rules = rules;
- this._lookups = {};
- this.strictImports = strictImports;
-};
-tree.Ruleset.prototype = {
- eval: function (env) {
- var selectors = this.selectors && this.selectors.map(function (s) { return s.eval(env) });
- var ruleset = new(tree.Ruleset)(selectors, this.rules.slice(0), this.strictImports);
-
- ruleset.root = this.root;
- ruleset.allowImports = this.allowImports;
-
- // push the current ruleset to the frames stack
- env.frames.unshift(ruleset);
-
- // Evaluate imports
- if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
- for (var i = 0; i < ruleset.rules.length; i++) {
- if (ruleset.rules[i] instanceof tree.Import) {
- Array.prototype.splice
- .apply(ruleset.rules, [i, 1].concat(ruleset.rules[i].eval(env)));
- }
- }
- }
-
- // Store the frames around mixin definitions,
- // so they can be evaluated like closures when the time comes.
- for (var i = 0; i < ruleset.rules.length; i++) {
- if (ruleset.rules[i] instanceof tree.mixin.Definition) {
- ruleset.rules[i].frames = env.frames.slice(0);
- }
- }
-
- // Evaluate mixin calls.
- for (var i = 0; i < ruleset.rules.length; i++) {
- if (ruleset.rules[i] instanceof tree.mixin.Call) {
- Array.prototype.splice
- .apply(ruleset.rules, [i, 1].concat(ruleset.rules[i].eval(env)));
- }
- }
-
- // Evaluate everything else
- for (var i = 0, rule; i < ruleset.rules.length; i++) {
- rule = ruleset.rules[i];
-
- if (! (rule instanceof tree.mixin.Definition)) {
- ruleset.rules[i] = rule.eval ? rule.eval(env) : rule;
- }
- }
-
- // Pop the stack
- env.frames.shift();
-
- return ruleset;
- },
- match: function (args) {
- return !args || args.length === 0;
- },
- variables: function () {
- if (this._variables) { return this._variables }
- else {
- return this._variables = this.rules.reduce(function (hash, r) {
- if (r instanceof tree.Rule && r.variable === true) {
- hash[r.name] = r;
- }
- return hash;
- }, {});
- }
- },
- variable: function (name) {
- return this.variables()[name];
- },
- rulesets: function () {
- if (this._rulesets) { return this._rulesets }
- else {
- return this._rulesets = this.rules.filter(function (r) {
- return (r instanceof tree.Ruleset) || (r instanceof tree.mixin.Definition);
- });
- }
- },
- find: function (selector, self) {
- self = self || this;
- var rules = [], rule, match,
- key = selector.toCSS();
-
- if (key in this._lookups) { return this._lookups[key] }
-
- this.rulesets().forEach(function (rule) {
- if (rule !== self) {
- for (var j = 0; j < rule.selectors.length; j++) {
- if (match = selector.match(rule.selectors[j])) {
- if (selector.elements.length > rule.selectors[j].elements.length) {
- Array.prototype.push.apply(rules, rule.find(
- new(tree.Selector)(selector.elements.slice(1)), self));
- } else {
- rules.push(rule);
- }
- break;
- }
- }
- }
- });
- return this._lookups[key] = rules;
- },
- //
- // Entry point for code generation
- //
- // `context` holds an array of arrays.
- //
- toCSS: function (context, env) {
- var css = [], // The CSS output
- rules = [], // node.Rule instances
- rulesets = [], // node.Ruleset instances
- paths = [], // Current selectors
- selector, // The fully rendered selector
- rule;
-
- if (! this.root) {
- if (context.length === 0) {
- paths = this.selectors.map(function (s) { return [s] });
- } else {
- this.joinSelectors(paths, context, this.selectors);
- }
- }
-
- // Compile rules and rulesets
- for (var i = 0; i < this.rules.length; i++) {
- rule = this.rules[i];
-
- if (rule.rules || (rule instanceof tree.Directive) || (rule instanceof tree.Media)) {
- rulesets.push(rule.toCSS(paths, env));
- } else if (rule instanceof tree.Comment) {
- if (!rule.silent) {
- if (this.root) {
- rulesets.push(rule.toCSS(env));
- } else {
- rules.push(rule.toCSS(env));
- }
- }
- } else {
- if (rule.toCSS && !rule.variable) {
- rules.push(rule.toCSS(env));
- } else if (rule.value && !rule.variable) {
- rules.push(rule.value.toString());
- }
- }
- }
-
- rulesets = rulesets.join('');
-
- // If this is the root node, we don't render
- // a selector, or {}.
- // Otherwise, only output if this ruleset has rules.
- if (this.root) {
- css.push(rules.join(env.compress ? '' : '\n'));
- } else {
- if (rules.length > 0) {
- selector = paths.map(function (p) {
- return p.map(function (s) {
- return s.toCSS(env);
- }).join('').trim();
- }).join( env.compress ? ',' : ',\n');
-
- css.push(selector,
- (env.compress ? '{' : ' {\n ') +
- rules.join(env.compress ? '' : '\n ') +
- (env.compress ? '}' : '\n}\n'));
- }
- }
- css.push(rulesets);
-
- return css.join('') + (env.compress ? '\n' : '');
- },
-
- joinSelectors: function (paths, context, selectors) {
- for (var s = 0; s < selectors.length; s++) {
- this.joinSelector(paths, context, selectors[s]);
- }
- },
-
- joinSelector: function (paths, context, selector) {
- var before = [], after = [], beforeElements = [],
- afterElements = [], hasParentSelector = false, el;
-
- for (var i = 0; i < selector.elements.length; i++) {
- el = selector.elements[i];
- if (el.combinator.value.charAt(0) === '&') {
- hasParentSelector = true;
- }
- if (hasParentSelector) afterElements.push(el);
- else beforeElements.push(el);
- }
-
- if (! hasParentSelector) {
- afterElements = beforeElements;
- beforeElements = [];
- }
-
- if (beforeElements.length > 0) {
- before.push(new(tree.Selector)(beforeElements));
- }
-
- if (afterElements.length > 0) {
- after.push(new(tree.Selector)(afterElements));
- }
-
- for (var c = 0; c < context.length; c++) {
- paths.push(before.concat(context[c]).concat(after));
- }
- }
-};
-})(require('../tree'));
-(function (tree) {
-
-tree.Selector = function (elements) {
- this.elements = elements;
- if (this.elements[0].combinator.value === "") {
- this.elements[0].combinator.value = ' ';
- }
-};
-tree.Selector.prototype.match = function (other) {
- var len = this.elements.length,
- olen = other.elements.length,
- max = Math.min(len, olen);
-
- if (len < olen) {
- return false;
- } else {
- for (var i = 0; i < max; i++) {
- if (this.elements[i].value !== other.elements[i].value) {
- return false;
- }
- }
- }
- return true;
-};
-tree.Selector.prototype.eval = function (env) {
- return new(tree.Selector)(this.elements.map(function (e) {
- return e.eval(env);
- }));
-};
-tree.Selector.prototype.toCSS = function (env) {
- if (this._css) { return this._css }
-
- return this._css = this.elements.map(function (e) {
- if (typeof(e) === 'string') {
- return ' ' + e.trim();
- } else {
- return e.toCSS(env);
- }
- }).join('');
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.URL = function (val, paths) {
- if (val.data) {
- this.attrs = val;
- } else {
- // Add the base path if the URL is relative and we are in the browser
- if (typeof(window) !== 'undefined' && !/^(?:https?:\/\/|file:\/\/|data:|\/)/.test(val.value) && paths.length > 0) {
- val.value = paths[0] + (val.value.charAt(0) === '/' ? val.value.slice(1) : val.value);
- }
- this.value = val;
- this.paths = paths;
- }
-};
-tree.URL.prototype = {
- toCSS: function () {
- return "url(" + (this.attrs ? 'data:' + this.attrs.mime + this.attrs.charset + this.attrs.base64 + this.attrs.data
- : this.value.toCSS()) + ")";
- },
- eval: function (ctx) {
- return this.attrs ? this : new(tree.URL)(this.value.eval(ctx), this.paths);
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Value = function (value) {
- this.value = value;
- this.is = 'value';
-};
-tree.Value.prototype = {
- eval: function (env) {
- if (this.value.length === 1) {
- return this.value[0].eval(env);
- } else {
- return new(tree.Value)(this.value.map(function (v) {
- return v.eval(env);
- }));
- }
- },
- toCSS: function (env) {
- return this.value.map(function (e) {
- return e.toCSS(env);
- }).join(env.compress ? ',' : ', ');
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.Variable = function (name, index, file) { this.name = name, this.index = index, this.file = file };
-tree.Variable.prototype = {
- eval: function (env) {
- var variable, v, name = this.name;
-
- if (name.indexOf('@@') == 0) {
- name = '@' + new(tree.Variable)(name.slice(1)).eval(env).value;
- }
-
- if (variable = tree.find(env.frames, function (frame) {
- if (v = frame.variable(name)) {
- return v.value.eval(env);
- }
- })) { return variable }
- else {
- throw { type: 'Name',
- message: "variable " + name + " is undefined",
- filename: this.file,
- index: this.index };
- }
- }
-};
-
-})(require('../tree'));
-(function (tree) {
-
-tree.find = function (obj, fun) {
- for (var i = 0, r; i < obj.length; i++) {
- if (r = fun.call(obj, obj[i])) { return r }
- }
- return null;
-};
-tree.jsify = function (obj) {
- if (Array.isArray(obj.value) && (obj.value.length > 1)) {
- return '[' + obj.value.map(function (v) { return v.toCSS(false) }).join(', ') + ']';
- } else {
- return obj.toCSS(false);
- }
-};
-
-})(require('./tree'));
-//
-// browser.js - client-side engine
-//
-
-var isFileProtocol = (location.protocol === 'file:' ||
- location.protocol === 'chrome:' ||
- location.protocol === 'chrome-extension:' ||
- location.protocol === 'resource:');
-
-less.env = less.env || (location.hostname == '127.0.0.1' ||
- location.hostname == '0.0.0.0' ||
- location.hostname == 'localhost' ||
- location.port.length > 0 ||
- isFileProtocol ? 'development'
- : 'production');
-
-// Load styles asynchronously (default: false)
-//
-// This is set to `false` by default, so that the body
-// doesn't start loading before the stylesheets are parsed.
-// Setting this to `true` can result in flickering.
-//
-less.async = false;
-
-// Interval between watch polls
-less.poll = less.poll || (isFileProtocol ? 1000 : 1500);
-
-//
-// Watch mode
-//
-less.watch = function () { return this.watchMode = true };
-less.unwatch = function () { return this.watchMode = false };
-
-if (less.env === 'development') {
- less.optimization = 0;
-
- if (/!watch/.test(location.hash)) {
- less.watch();
- }
- less.watchTimer = setInterval(function () {
- if (less.watchMode) {
- loadStyleSheets(function (e, root, _, sheet, env) {
- if (root) {
- createCSS(root.toCSS(), sheet, env.lastModified);
- }
- });
- }
- }, less.poll);
-} else {
- less.optimization = 3;
-}
-
-var cache;
-
-try {
- cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage;
-} catch (_) {
- cache = null;
-}
-
-//
-// Get all <link> tags with the 'rel' attribute set to "stylesheet/less"
-//
-var links = document.getElementsByTagName('link');
-var typePattern = /^text\/(x-)?less$/;
-
-less.sheets = [];
-
-for (var i = 0; i < links.length; i++) {
- if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
- (links[i].type.match(typePattern)))) {
- less.sheets.push(links[i]);
- }
-}
-
-
-less.refresh = function (reload) {
- var startTime, endTime;
- startTime = endTime = new(Date);
-
- loadStyleSheets(function (e, root, _, sheet, env) {
- if (env.local) {
- log("loading " + sheet.href + " from cache.");
- } else {
- log("parsed " + sheet.href + " successfully.");
- createCSS(root.toCSS(), sheet, env.lastModified);
- }
- log("css for " + sheet.href + " generated in " + (new(Date) - endTime) + 'ms');
- (env.remaining === 0) && log("css generated in " + (new(Date) - startTime) + 'ms');
- endTime = new(Date);
- }, reload);
-
- loadStyles();
-};
-less.refreshStyles = loadStyles;
-
-less.refresh(less.env === 'development');
-
-function loadStyles() {
- var styles = document.getElementsByTagName('style');
- for (var i = 0; i < styles.length; i++) {
- if (styles[i].type.match(typePattern)) {
- new(less.Parser)().parse(styles[i].innerHTML || '', function (e, tree) {
- var css = tree.toCSS();
- var style = styles[i];
- style.type = 'text/css';
- if (style.styleSheet) {
- style.styleSheet.cssText = css;
- } else {
- style.innerHTML = css;
- }
- });
- }
- }
-}
-
-function loadStyleSheets(callback, reload) {
- for (var i = 0; i < less.sheets.length; i++) {
- loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1));
- }
-}
-
-function loadStyleSheet(sheet, callback, reload, remaining) {
- var url = window.location.href.replace(/[#?].*$/, '');
- var href = sheet.href.replace(/\?.*$/, '');
- var css = cache && cache.getItem(href);
- var timestamp = cache && cache.getItem(href + ':timestamp');
- var styles = { css: css, timestamp: timestamp };
-
- // Stylesheets in IE don't always return the full path
- if (! /^(https?|file):/.test(href)) {
- if (href.charAt(0) == "/") {
- href = window.location.protocol + "//" + window.location.host + href;
- } else {
- href = url.slice(0, url.lastIndexOf('/') + 1) + href;
- }
- }
- var filename = href.match(/([^\/]+)$/)[1];
-
- xhr(sheet.href, sheet.type, function (data, lastModified) {
- if (!reload && styles && lastModified &&
- (new(Date)(lastModified).valueOf() ===
- new(Date)(styles.timestamp).valueOf())) {
- // Use local copy
- createCSS(styles.css, sheet);
- callback(null, null, data, sheet, { local: true, remaining: remaining });
- } else {
- // Use remote copy (re-parse)
- try {
- new(less.Parser)({
- optimization: less.optimization,
- paths: [href.replace(/[\w\.-]+$/, '')],
- mime: sheet.type,
- filename: filename
- }).parse(data, function (e, root) {
- if (e) { return error(e, href) }
- try {
- callback(e, root, data, sheet, { local: false, lastModified: lastModified, remaining: remaining });
- removeNode(document.getElementById('less-error-message:' + extractId(href)));
- } catch (e) {
- error(e, href);
- }
- });
- } catch (e) {
- error(e, href);
- }
- }
- }, function (status, url) {
- throw new(Error)("Couldn't load " + url + " (" + status + ")");
- });
-}
-
-function extractId(href) {
- return href.replace(/^[a-z]+:\/\/?[^\/]+/, '' ) // Remove protocol & domain
- .replace(/^\//, '' ) // Remove root /
- .replace(/\?.*$/, '' ) // Remove query
- .replace(/\.[^\.\/]+$/, '' ) // Remove file extension
- .replace(/[^\.\w-]+/g, '-') // Replace illegal characters
- .replace(/\./g, ':'); // Replace dots with colons(for valid id)
-}
-
-function createCSS(styles, sheet, lastModified) {
- var css;
-
- // Strip the query-string
- var href = sheet.href ? sheet.href.replace(/\?.*$/, '') : '';
-
- // If there is no title set, use the filename, minus the extension
- var id = 'less:' + (sheet.title || extractId(href));
-
- // If the stylesheet doesn't exist, create a new node
- if ((css = document.getElementById(id)) === null) {
- css = document.createElement('style');
- css.type = 'text/css';
- css.media = sheet.media || 'screen';
- css.id = id;
- document.getElementsByTagName('head')[0].appendChild(css);
- }
-
- if (css.styleSheet) { // IE
- try {
- css.styleSheet.cssText = styles;
- } catch (e) {
- throw new(Error)("Couldn't reassign styleSheet.cssText.");
- }
- } else {
- (function (node) {
- if (css.childNodes.length > 0) {
- if (css.firstChild.nodeValue !== node.nodeValue) {
- css.replaceChild(node, css.firstChild);
- }
- } else {
- css.appendChild(node);
- }
- })(document.createTextNode(styles));
- }
-
- // Don't update the local store if the file wasn't modified
- if (lastModified && cache) {
- log('saving ' + href + ' to cache.');
- cache.setItem(href, styles);
- cache.setItem(href + ':timestamp', lastModified);
- }
-}
-
-function xhr(url, type, callback, errback) {
- var xhr = getXMLHttpRequest();
- var async = isFileProtocol ? false : less.async;
-
- if (typeof(xhr.overrideMimeType) === 'function') {
- xhr.overrideMimeType('text/css');
- }
- xhr.open('GET', url, async);
- xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
- xhr.send(null);
-
- if (isFileProtocol) {
- if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
- callback(xhr.responseText);
- } else {
- errback(xhr.status, url);
- }
- } else if (async) {
- xhr.onreadystatechange = function () {
- if (xhr.readyState == 4) {
- handleResponse(xhr, callback, errback);
- }
- };
- } else {
- handleResponse(xhr, callback, errback);
- }
-
- function handleResponse(xhr, callback, errback) {
- if (xhr.status >= 200 && xhr.status < 300) {
- callback(xhr.responseText,
- xhr.getResponseHeader("Last-Modified"));
- } else if (typeof(errback) === 'function') {
- errback(xhr.status, url);
- }
- }
-}
-
-function getXMLHttpRequest() {
- if (window.XMLHttpRequest) {
- return new(XMLHttpRequest);
- } else {
- try {
- return new(ActiveXObject)("MSXML2.XMLHTTP.3.0");
- } catch (e) {
- log("browser doesn't support AJAX.");
- return null;
- }
- }
-}
-
-function removeNode(node) {
- return node && node.parentNode.removeChild(node);
-}
-
-function log(str) {
- if (less.env == 'development' && typeof(console) !== "undefined") { console.log('less: ' + str) }
-}
-
-function error(e, href) {
- var id = 'less-error-message:' + extractId(href);
- var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
- var elem = document.createElement('div'), timer, content, error = [];
- var filename = e.filename || href;
-
- elem.id = id;
- elem.className = "less-error-message";
-
- content = '<h3>' + (e.message || 'There is an error in your .less file') +
- '</h3>' + '<p>in <a href="' + filename + '">' + filename + "</a> ";
-
- var errorline = function (e, i, classname) {
- if (e.extract[i]) {
- error.push(template.replace(/\{line\}/, parseInt(e.line) + (i - 1))
- .replace(/\{class\}/, classname)
- .replace(/\{content\}/, e.extract[i]));
- }
- };
-
- if (e.stack) {
- content += '<br/>' + e.stack.split('\n').slice(1).join('<br/>');
- } else if (e.extract) {
- errorline(e, 0, '');
- errorline(e, 1, 'line');
- errorline(e, 2, '');
- content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':</p>' +
- '<ul>' + error.join('') + '</ul>';
- }
- elem.innerHTML = content;
-
- // CSS for error messages
- createCSS([
- '.less-error-message ul, .less-error-message li {',
- 'list-style-type: none;',
- 'margin-right: 15px;',
- 'padding: 4px 0;',
- 'margin: 0;',
- '}',
- '.less-error-message label {',
- 'font-size: 12px;',
- 'margin-right: 15px;',
- 'padding: 4px 0;',
- 'color: #cc7777;',
- '}',
- '.less-error-message pre {',
- 'color: #dd6666;',
- 'padding: 4px 0;',
- 'margin: 0;',
- 'display: inline-block;',
- '}',
- '.less-error-message pre.line {',
- 'color: #ff0000;',
- '}',
- '.less-error-message h3 {',
- 'font-size: 20px;',
- 'font-weight: bold;',
- 'padding: 15px 0 5px 0;',
- 'margin: 0;',
- '}',
- '.less-error-message a {',
- 'color: #10a',
- '}',
- '.less-error-message .error {',
- 'color: red;',
- 'font-weight: bold;',
- 'padding-bottom: 2px;',
- 'border-bottom: 1px dashed red;',
- '}'
- ].join('\n'), { title: 'error-message' });
-
- elem.style.cssText = [
- "font-family: Arial, sans-serif",
- "border: 1px solid #e00",
- "background-color: #eee",
- "border-radius: 5px",
- "-webkit-border-radius: 5px",
- "-moz-border-radius: 5px",
- "color: #e00",
- "padding: 15px",
- "margin-bottom: 15px"
- ].join(';');
-
- if (less.env == 'development') {
- timer = setInterval(function () {
- if (document.body) {
- if (document.getElementById(id)) {
- document.body.replaceChild(elem, document.getElementById(id));
- } else {
- document.body.insertBefore(elem, document.body.firstChild);
- }
- clearInterval(timer);
- }
- }, 10);
- }
-}
-
-})(window);
diff --git a/ckan/public-bs2/base/test/vendor/mocha.css b/ckan/public-bs2/base/test/vendor/mocha.css
deleted file mode 100644
--- a/ckan/public-bs2/base/test/vendor/mocha.css
+++ /dev/null
@@ -1,251 +0,0 @@
-@charset "utf-8";
-
-body {
- margin:0;
-}
-
-#mocha {
- font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
- margin: 60px 50px;
-}
-
-#mocha ul, #mocha li {
- margin: 0;
- padding: 0;
-}
-
-#mocha ul {
- list-style: none;
-}
-
-#mocha h1, #mocha h2 {
- margin: 0;
-}
-
-#mocha h1 {
- margin-top: 15px;
- font-size: 1em;
- font-weight: 200;
-}
-
-#mocha h1 a {
- text-decoration: none;
- color: inherit;
-}
-
-#mocha h1 a:hover {
- text-decoration: underline;
-}
-
-#mocha .suite .suite h1 {
- margin-top: 0;
- font-size: .8em;
-}
-
-#mocha .hidden {
- display: none;
-}
-
-#mocha h2 {
- font-size: 12px;
- font-weight: normal;
- cursor: pointer;
-}
-
-#mocha .suite {
- margin-left: 15px;
-}
-
-#mocha .test {
- margin-left: 15px;
- overflow: hidden;
-}
-
-#mocha .test.pending:hover h2::after {
- content: '(pending)';
- font-family: arial, sans-serif;
-}
-
-#mocha .test.pass.medium .duration {
- background: #C09853;
-}
-
-#mocha .test.pass.slow .duration {
- background: #B94A48;
-}
-
-#mocha .test.pass::before {
- content: '✓';
- font-size: 12px;
- display: block;
- float: left;
- margin-right: 5px;
- color: #00d6b2;
-}
-
-#mocha .test.pass .duration {
- font-size: 9px;
- margin-left: 5px;
- padding: 2px 5px;
- color: white;
- -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
- -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
- box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
- -webkit-border-radius: 5px;
- -moz-border-radius: 5px;
- -ms-border-radius: 5px;
- -o-border-radius: 5px;
- border-radius: 5px;
-}
-
-#mocha .test.pass.fast .duration {
- display: none;
-}
-
-#mocha .test.pending {
- color: #0b97c4;
-}
-
-#mocha .test.pending::before {
- content: '◦';
- color: #0b97c4;
-}
-
-#mocha .test.fail {
- color: #c00;
-}
-
-#mocha .test.fail pre {
- color: black;
-}
-
-#mocha .test.fail::before {
- content: '✖';
- font-size: 12px;
- display: block;
- float: left;
- margin-right: 5px;
- color: #c00;
-}
-
-#mocha .test pre.error {
- color: #c00;
- max-height: 300px;
- overflow: auto;
-}
-
-#mocha .test pre {
- display: block;
- float: left;
- clear: left;
- font: 12px/1.5 monaco, monospace;
- margin: 5px;
- padding: 15px;
- border: 1px solid #eee;
- border-bottom-color: #ddd;
- -webkit-border-radius: 3px;
- -webkit-box-shadow: 0 1px 3px #eee;
- -moz-border-radius: 3px;
- -moz-box-shadow: 0 1px 3px #eee;
-}
-
-#mocha .test h2 {
- position: relative;
-}
-
-#mocha .test a.replay {
- position: absolute;
- top: 3px;
- right: 0;
- text-decoration: none;
- vertical-align: middle;
- display: block;
- width: 15px;
- height: 15px;
- line-height: 15px;
- text-align: center;
- background: #eee;
- font-size: 15px;
- -moz-border-radius: 15px;
- border-radius: 15px;
- -webkit-transition: opacity 200ms;
- -moz-transition: opacity 200ms;
- transition: opacity 200ms;
- opacity: 0.3;
- color: #888;
-}
-
-#mocha .test:hover a.replay {
- opacity: 1;
-}
-
-#mocha-report.pass .test.fail {
- display: none;
-}
-
-#mocha-report.fail .test.pass {
- display: none;
-}
-
-#mocha-error {
- color: #c00;
- font-size: 1.5em;
- font-weight: 100;
- letter-spacing: 1px;
-}
-
-#mocha-stats {
- position: fixed;
- top: 15px;
- right: 10px;
- font-size: 12px;
- margin: 0;
- color: #888;
- z-index: 1;
-}
-
-#mocha-stats .progress {
- float: right;
- padding-top: 0;
-}
-
-#mocha-stats em {
- color: black;
-}
-
-#mocha-stats a {
- text-decoration: none;
- color: inherit;
-}
-
-#mocha-stats a:hover {
- border-bottom: 1px solid #eee;
-}
-
-#mocha-stats li {
- display: inline-block;
- margin: 0 5px;
- list-style: none;
- padding-top: 11px;
-}
-
-#mocha-stats canvas {
- width: 40px;
- height: 40px;
-}
-
-#mocha code .comment { color: #ddd }
-#mocha code .init { color: #2F6FAD }
-#mocha code .string { color: #5890AD }
-#mocha code .keyword { color: #8A6343 }
-#mocha code .number { color: #2F6FAD }
-
-@media screen and (max-device-width: 480px) {
- #mocha {
- margin: 60px 0px;
- }
-
- #mocha #stats {
- position: absolute;
- }
-}
\ No newline at end of file
diff --git a/ckan/public-bs2/base/test/vendor/mocha.js b/ckan/public-bs2/base/test/vendor/mocha.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/vendor/mocha.js
+++ /dev/null
@@ -1,5428 +0,0 @@
-;(function(){
-
-// CommonJS require()
-
-function require(p){
- var path = require.resolve(p)
- , mod = require.modules[path];
- if (!mod) throw new Error('failed to require "' + p + '"');
- if (!mod.exports) {
- mod.exports = {};
- mod.call(mod.exports, mod, mod.exports, require.relative(path));
- }
- return mod.exports;
- }
-
-require.modules = {};
-
-require.resolve = function (path){
- var orig = path
- , reg = path + '.js'
- , index = path + '/index.js';
- return require.modules[reg] && reg
- || require.modules[index] && index
- || orig;
- };
-
-require.register = function (path, fn){
- require.modules[path] = fn;
- };
-
-require.relative = function (parent) {
- return function(p){
- if ('.' != p.charAt(0)) return require(p);
-
- var path = parent.split('/')
- , segs = p.split('/');
- path.pop();
-
- for (var i = 0; i < segs.length; i++) {
- var seg = segs[i];
- if ('..' == seg) path.pop();
- else if ('.' != seg) path.push(seg);
- }
-
- return require(path.join('/'));
- };
- };
-
-
-require.register("browser/debug.js", function(module, exports, require){
-
-module.exports = function(type){
- return function(){
- }
-};
-
-}); // module: browser/debug.js
-
-require.register("browser/diff.js", function(module, exports, require){
-/* See license.txt for terms of usage */
-
-/*
- * Text diff implementation.
- *
- * This library supports the following APIS:
- * JsDiff.diffChars: Character by character diff
- * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
- * JsDiff.diffLines: Line based diff
- *
- * JsDiff.diffCss: Diff targeted at CSS content
- *
- * These methods are based on the implementation proposed in
- * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
- * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
- */
-var JsDiff = (function() {
- function clonePath(path) {
- return { newPos: path.newPos, components: path.components.slice(0) };
- }
- function removeEmpty(array) {
- var ret = [];
- for (var i = 0; i < array.length; i++) {
- if (array[i]) {
- ret.push(array[i]);
- }
- }
- return ret;
- }
- function escapeHTML(s) {
- var n = s;
- n = n.replace(/&/g, "&");
- n = n.replace(/</g, "<");
- n = n.replace(/>/g, ">");
- n = n.replace(/"/g, """);
-
- return n;
- }
-
-
- var fbDiff = function(ignoreWhitespace) {
- this.ignoreWhitespace = ignoreWhitespace;
- };
- fbDiff.prototype = {
- diff: function(oldString, newString) {
- // Handle the identity case (this is due to unrolling editLength == 0
- if (newString == oldString) {
- return [{ value: newString }];
- }
- if (!newString) {
- return [{ value: oldString, removed: true }];
- }
- if (!oldString) {
- return [{ value: newString, added: true }];
- }
-
- newString = this.tokenize(newString);
- oldString = this.tokenize(oldString);
-
- var newLen = newString.length, oldLen = oldString.length;
- var maxEditLength = newLen + oldLen;
- var bestPath = [{ newPos: -1, components: [] }];
-
- // Seed editLength = 0
- var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
- if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
- return bestPath[0].components;
- }
-
- for (var editLength = 1; editLength <= maxEditLength; editLength++) {
- for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
- var basePath;
- var addPath = bestPath[diagonalPath-1],
- removePath = bestPath[diagonalPath+1];
- oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
- if (addPath) {
- // No one else is going to attempt to use this value, clear it
- bestPath[diagonalPath-1] = undefined;
- }
-
- var canAdd = addPath && addPath.newPos+1 < newLen;
- var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
- if (!canAdd && !canRemove) {
- bestPath[diagonalPath] = undefined;
- continue;
- }
-
- // Select the diagonal that we want to branch from. We select the prior
- // path whose position in the new string is the farthest from the origin
- // and does not pass the bounds of the diff graph
- if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
- basePath = clonePath(removePath);
- this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
- } else {
- basePath = clonePath(addPath);
- basePath.newPos++;
- this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
- }
-
- var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
-
- if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
- return basePath.components;
- } else {
- bestPath[diagonalPath] = basePath;
- }
- }
- }
- },
-
- pushComponent: function(components, value, added, removed) {
- var last = components[components.length-1];
- if (last && last.added === added && last.removed === removed) {
- // We need to clone here as the component clone operation is just
- // as shallow array clone
- components[components.length-1] =
- {value: this.join(last.value, value), added: added, removed: removed };
- } else {
- components.push({value: value, added: added, removed: removed });
- }
- },
- extractCommon: function(basePath, newString, oldString, diagonalPath) {
- var newLen = newString.length,
- oldLen = oldString.length,
- newPos = basePath.newPos,
- oldPos = newPos - diagonalPath;
- while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
- newPos++;
- oldPos++;
-
- this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
- }
- basePath.newPos = newPos;
- return oldPos;
- },
-
- equals: function(left, right) {
- var reWhitespace = /\S/;
- if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
- return true;
- } else {
- return left == right;
- }
- },
- join: function(left, right) {
- return left + right;
- },
- tokenize: function(value) {
- return value;
- }
- };
-
- var CharDiff = new fbDiff();
-
- var WordDiff = new fbDiff(true);
- WordDiff.tokenize = function(value) {
- return removeEmpty(value.split(/(\s+|\b)/));
- };
-
- var CssDiff = new fbDiff(true);
- CssDiff.tokenize = function(value) {
- return removeEmpty(value.split(/([{}:;,]|\s+)/));
- };
-
- var LineDiff = new fbDiff();
- LineDiff.tokenize = function(value) {
- return value.split(/^/m);
- };
-
- return {
- diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
- diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
- diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
-
- diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
-
- createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
- var ret = [];
-
- ret.push("Index: " + fileName);
- ret.push("===================================================================");
- ret.push("--- " + fileName + (typeof oldHeader === "undefined" ? "" : "\t" + oldHeader));
- ret.push("+++ " + fileName + (typeof newHeader === "undefined" ? "" : "\t" + newHeader));
-
- var diff = LineDiff.diff(oldStr, newStr);
- if (!diff[diff.length-1].value) {
- diff.pop(); // Remove trailing newline add
- }
- diff.push({value: "", lines: []}); // Append an empty value to make cleanup easier
-
- function contextLines(lines) {
- return lines.map(function(entry) { return ' ' + entry; });
- }
- function eofNL(curRange, i, current) {
- var last = diff[diff.length-2],
- isLast = i === diff.length-2,
- isLastOfType = i === diff.length-3 && (current.added === !last.added || current.removed === !last.removed);
-
- // Figure out if this is the last line for the given file and missing NL
- if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
- curRange.push('\\ No newline at end of file');
- }
- }
-
- var oldRangeStart = 0, newRangeStart = 0, curRange = [],
- oldLine = 1, newLine = 1;
- for (var i = 0; i < diff.length; i++) {
- var current = diff[i],
- lines = current.lines || current.value.replace(/\n$/, "").split("\n");
- current.lines = lines;
-
- if (current.added || current.removed) {
- if (!oldRangeStart) {
- var prev = diff[i-1];
- oldRangeStart = oldLine;
- newRangeStart = newLine;
-
- if (prev) {
- curRange = contextLines(prev.lines.slice(-4));
- oldRangeStart -= curRange.length;
- newRangeStart -= curRange.length;
- }
- }
- curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?"+":"-") + entry; }));
- eofNL(curRange, i, current);
-
- if (current.added) {
- newLine += lines.length;
- } else {
- oldLine += lines.length;
- }
- } else {
- if (oldRangeStart) {
- // Close out any changes that have been output (or join overlapping)
- if (lines.length <= 8 && i < diff.length-2) {
- // Overlapping
- curRange.push.apply(curRange, contextLines(lines));
- } else {
- // end the range and output
- var contextSize = Math.min(lines.length, 4);
- ret.push(
- "@@ -" + oldRangeStart + "," + (oldLine-oldRangeStart+contextSize)
- + " +" + newRangeStart + "," + (newLine-newRangeStart+contextSize)
- + " @@");
- ret.push.apply(ret, curRange);
- ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
- if (lines.length <= 4) {
- eofNL(ret, i, current);
- }
-
- oldRangeStart = 0; newRangeStart = 0; curRange = [];
- }
- }
- oldLine += lines.length;
- newLine += lines.length;
- }
- }
-
- return ret.join('\n') + '\n';
- },
-
- convertChangesToXML: function(changes){
- var ret = [];
- for ( var i = 0; i < changes.length; i++) {
- var change = changes[i];
- if (change.added) {
- ret.push("<ins>");
- } else if (change.removed) {
- ret.push("<del>");
- }
-
- ret.push(escapeHTML(change.value));
-
- if (change.added) {
- ret.push("</ins>");
- } else if (change.removed) {
- ret.push("</del>");
- }
- }
- return ret.join("");
- }
- };
-})();
-
-if (typeof module !== "undefined") {
- module.exports = JsDiff;
-}
-
-}); // module: browser/diff.js
-
-require.register("browser/events.js", function(module, exports, require){
-
-/**
- * Module exports.
- */
-
-exports.EventEmitter = EventEmitter;
-
-/**
- * Check if `obj` is an array.
- */
-
-function isArray(obj) {
- return '[object Array]' == {}.toString.call(obj);
-}
-
-/**
- * Event emitter constructor.
- *
- * @api public
- */
-
-function EventEmitter(){};
-
-/**
- * Adds a listener.
- *
- * @api public
- */
-
-EventEmitter.prototype.on = function (name, fn) {
- if (!this.$events) {
- this.$events = {};
- }
-
- if (!this.$events[name]) {
- this.$events[name] = fn;
- } else if (isArray(this.$events[name])) {
- this.$events[name].push(fn);
- } else {
- this.$events[name] = [this.$events[name], fn];
- }
-
- return this;
-};
-
-EventEmitter.prototype.addListener = EventEmitter.prototype.on;
-
-/**
- * Adds a volatile listener.
- *
- * @api public
- */
-
-EventEmitter.prototype.once = function (name, fn) {
- var self = this;
-
- function on () {
- self.removeListener(name, on);
- fn.apply(this, arguments);
- };
-
- on.listener = fn;
- this.on(name, on);
-
- return this;
-};
-
-/**
- * Removes a listener.
- *
- * @api public
- */
-
-EventEmitter.prototype.removeListener = function (name, fn) {
- if (this.$events && this.$events[name]) {
- var list = this.$events[name];
-
- if (isArray(list)) {
- var pos = -1;
-
- for (var i = 0, l = list.length; i < l; i++) {
- if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
- pos = i;
- break;
- }
- }
-
- if (pos < 0) {
- return this;
- }
-
- list.splice(pos, 1);
-
- if (!list.length) {
- delete this.$events[name];
- }
- } else if (list === fn || (list.listener && list.listener === fn)) {
- delete this.$events[name];
- }
- }
-
- return this;
-};
-
-/**
- * Removes all listeners for an event.
- *
- * @api public
- */
-
-EventEmitter.prototype.removeAllListeners = function (name) {
- if (name === undefined) {
- this.$events = {};
- return this;
- }
-
- if (this.$events && this.$events[name]) {
- this.$events[name] = null;
- }
-
- return this;
-};
-
-/**
- * Gets all listeners for a certain event.
- *
- * @api public
- */
-
-EventEmitter.prototype.listeners = function (name) {
- if (!this.$events) {
- this.$events = {};
- }
-
- if (!this.$events[name]) {
- this.$events[name] = [];
- }
-
- if (!isArray(this.$events[name])) {
- this.$events[name] = [this.$events[name]];
- }
-
- return this.$events[name];
-};
-
-/**
- * Emits an event.
- *
- * @api public
- */
-
-EventEmitter.prototype.emit = function (name) {
- if (!this.$events) {
- return false;
- }
-
- var handler = this.$events[name];
-
- if (!handler) {
- return false;
- }
-
- var args = [].slice.call(arguments, 1);
-
- if ('function' == typeof handler) {
- handler.apply(this, args);
- } else if (isArray(handler)) {
- var listeners = handler.slice();
-
- for (var i = 0, l = listeners.length; i < l; i++) {
- listeners[i].apply(this, args);
- }
- } else {
- return false;
- }
-
- return true;
-};
-}); // module: browser/events.js
-
-require.register("browser/fs.js", function(module, exports, require){
-
-}); // module: browser/fs.js
-
-require.register("browser/path.js", function(module, exports, require){
-
-}); // module: browser/path.js
-
-require.register("browser/progress.js", function(module, exports, require){
-
-/**
- * Expose `Progress`.
- */
-
-module.exports = Progress;
-
-/**
- * Initialize a new `Progress` indicator.
- */
-
-function Progress() {
- this.percent = 0;
- this.size(0);
- this.fontSize(11);
- this.font('helvetica, arial, sans-serif');
-}
-
-/**
- * Set progress size to `n`.
- *
- * @param {Number} n
- * @return {Progress} for chaining
- * @api public
- */
-
-Progress.prototype.size = function(n){
- this._size = n;
- return this;
-};
-
-/**
- * Set text to `str`.
- *
- * @param {String} str
- * @return {Progress} for chaining
- * @api public
- */
-
-Progress.prototype.text = function(str){
- this._text = str;
- return this;
-};
-
-/**
- * Set font size to `n`.
- *
- * @param {Number} n
- * @return {Progress} for chaining
- * @api public
- */
-
-Progress.prototype.fontSize = function(n){
- this._fontSize = n;
- return this;
-};
-
-/**
- * Set font `family`.
- *
- * @param {String} family
- * @return {Progress} for chaining
- */
-
-Progress.prototype.font = function(family){
- this._font = family;
- return this;
-};
-
-/**
- * Update percentage to `n`.
- *
- * @param {Number} n
- * @return {Progress} for chaining
- */
-
-Progress.prototype.update = function(n){
- this.percent = n;
- return this;
-};
-
-/**
- * Draw on `ctx`.
- *
- * @param {CanvasRenderingContext2d} ctx
- * @return {Progress} for chaining
- */
-
-Progress.prototype.draw = function(ctx){
- var percent = Math.min(this.percent, 100)
- , size = this._size
- , half = size / 2
- , x = half
- , y = half
- , rad = half - 1
- , fontSize = this._fontSize;
-
- ctx.font = fontSize + 'px ' + this._font;
-
- var angle = Math.PI * 2 * (percent / 100);
- ctx.clearRect(0, 0, size, size);
-
- // outer circle
- ctx.strokeStyle = '#9f9f9f';
- ctx.beginPath();
- ctx.arc(x, y, rad, 0, angle, false);
- ctx.stroke();
-
- // inner circle
- ctx.strokeStyle = '#eee';
- ctx.beginPath();
- ctx.arc(x, y, rad - 1, 0, angle, true);
- ctx.stroke();
-
- // text
- var text = this._text || (percent | 0) + '%'
- , w = ctx.measureText(text).width;
-
- ctx.fillText(
- text
- , x - w / 2 + 1
- , y + fontSize / 2 - 1);
-
- return this;
-};
-
-}); // module: browser/progress.js
-
-require.register("browser/tty.js", function(module, exports, require){
-
-exports.isatty = function(){
- return true;
-};
-
-exports.getWindowSize = function(){
- if ('innerHeight' in global) {
- return [global.innerHeight, global.innerWidth];
- } else {
- // In a Web Worker, the DOM Window is not available.
- return [640, 480];
- }
-};
-
-}); // module: browser/tty.js
-
-require.register("context.js", function(module, exports, require){
-
-/**
- * Expose `Context`.
- */
-
-module.exports = Context;
-
-/**
- * Initialize a new `Context`.
- *
- * @api private
- */
-
-function Context(){}
-
-/**
- * Set or get the context `Runnable` to `runnable`.
- *
- * @param {Runnable} runnable
- * @return {Context}
- * @api private
- */
-
-Context.prototype.runnable = function(runnable){
- if (0 == arguments.length) return this._runnable;
- this.test = this._runnable = runnable;
- return this;
-};
-
-/**
- * Set test timeout `ms`.
- *
- * @param {Number} ms
- * @return {Context} self
- * @api private
- */
-
-Context.prototype.timeout = function(ms){
- this.runnable().timeout(ms);
- return this;
-};
-
-/**
- * Set test slowness threshold `ms`.
- *
- * @param {Number} ms
- * @return {Context} self
- * @api private
- */
-
-Context.prototype.slow = function(ms){
- this.runnable().slow(ms);
- return this;
-};
-
-/**
- * Inspect the context void of `._runnable`.
- *
- * @return {String}
- * @api private
- */
-
-Context.prototype.inspect = function(){
- return JSON.stringify(this, function(key, val){
- if ('_runnable' == key) return;
- if ('test' == key) return;
- return val;
- }, 2);
-};
-
-}); // module: context.js
-
-require.register("hook.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Runnable = require('./runnable');
-
-/**
- * Expose `Hook`.
- */
-
-module.exports = Hook;
-
-/**
- * Initialize a new `Hook` with the given `title` and callback `fn`.
- *
- * @param {String} title
- * @param {Function} fn
- * @api private
- */
-
-function Hook(title, fn) {
- Runnable.call(this, title, fn);
- this.type = 'hook';
-}
-
-/**
- * Inherit from `Runnable.prototype`.
- */
-
-function F(){};
-F.prototype = Runnable.prototype;
-Hook.prototype = new F;
-Hook.prototype.constructor = Hook;
-
-
-/**
- * Get or set the test `err`.
- *
- * @param {Error} err
- * @return {Error}
- * @api public
- */
-
-Hook.prototype.error = function(err){
- if (0 == arguments.length) {
- var err = this._error;
- this._error = null;
- return err;
- }
-
- this._error = err;
-};
-
-}); // module: hook.js
-
-require.register("interfaces/bdd.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
- , Test = require('../test');
-
-/**
- * BDD-style interface:
- *
- * describe('Array', function(){
- * describe('#indexOf()', function(){
- * it('should return -1 when not present', function(){
- *
- * });
- *
- * it('should return the index when present', function(){
- *
- * });
- * });
- * });
- *
- */
-
-module.exports = function(suite){
- var suites = [suite];
-
- suite.on('pre-require', function(context, file, mocha){
-
- /**
- * Execute before running tests.
- */
-
- context.before = function(fn){
- suites[0].beforeAll(fn);
- };
-
- /**
- * Execute after running tests.
- */
-
- context.after = function(fn){
- suites[0].afterAll(fn);
- };
-
- /**
- * Execute before each test case.
- */
-
- context.beforeEach = function(fn){
- suites[0].beforeEach(fn);
- };
-
- /**
- * Execute after each test case.
- */
-
- context.afterEach = function(fn){
- suites[0].afterEach(fn);
- };
-
- /**
- * Describe a "suite" with the given `title`
- * and callback `fn` containing nested suites
- * and/or tests.
- */
-
- context.describe = context.context = function(title, fn){
- var suite = Suite.create(suites[0], title);
- suites.unshift(suite);
- fn.call(suite);
- suites.shift();
- return suite;
- };
-
- /**
- * Pending describe.
- */
-
- context.xdescribe =
- context.xcontext =
- context.describe.skip = function(title, fn){
- var suite = Suite.create(suites[0], title);
- suite.pending = true;
- suites.unshift(suite);
- fn.call(suite);
- suites.shift();
- };
-
- /**
- * Exclusive suite.
- */
-
- context.describe.only = function(title, fn){
- var suite = context.describe(title, fn);
- mocha.grep(suite.fullTitle());
- };
-
- /**
- * Describe a specification or test-case
- * with the given `title` and callback `fn`
- * acting as a thunk.
- */
-
- context.it = context.specify = function(title, fn){
- var suite = suites[0];
- if (suite.pending) var fn = null;
- var test = new Test(title, fn);
- suite.addTest(test);
- return test;
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.it.only = function(title, fn){
- var test = context.it(title, fn);
- mocha.grep(test.fullTitle());
- };
-
- /**
- * Pending test case.
- */
-
- context.xit =
- context.xspecify =
- context.it.skip = function(title){
- context.it(title);
- };
- });
-};
-
-}); // module: interfaces/bdd.js
-
-require.register("interfaces/exports.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
- , Test = require('../test');
-
-/**
- * TDD-style interface:
- *
- * exports.Array = {
- * '#indexOf()': {
- * 'should return -1 when the value is not present': function(){
- *
- * },
- *
- * 'should return the correct index when the value is present': function(){
- *
- * }
- * }
- * };
- *
- */
-
-module.exports = function(suite){
- var suites = [suite];
-
- suite.on('require', visit);
-
- function visit(obj) {
- var suite;
- for (var key in obj) {
- if ('function' == typeof obj[key]) {
- var fn = obj[key];
- switch (key) {
- case 'before':
- suites[0].beforeAll(fn);
- break;
- case 'after':
- suites[0].afterAll(fn);
- break;
- case 'beforeEach':
- suites[0].beforeEach(fn);
- break;
- case 'afterEach':
- suites[0].afterEach(fn);
- break;
- default:
- suites[0].addTest(new Test(key, fn));
- }
- } else {
- var suite = Suite.create(suites[0], key);
- suites.unshift(suite);
- visit(obj[key]);
- suites.shift();
- }
- }
- }
-};
-
-}); // module: interfaces/exports.js
-
-require.register("interfaces/index.js", function(module, exports, require){
-
-exports.bdd = require('./bdd');
-exports.tdd = require('./tdd');
-exports.qunit = require('./qunit');
-exports.exports = require('./exports');
-
-}); // module: interfaces/index.js
-
-require.register("interfaces/qunit.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
- , Test = require('../test');
-
-/**
- * QUnit-style interface:
- *
- * suite('Array');
- *
- * test('#length', function(){
- * var arr = [1,2,3];
- * ok(arr.length == 3);
- * });
- *
- * test('#indexOf()', function(){
- * var arr = [1,2,3];
- * ok(arr.indexOf(1) == 0);
- * ok(arr.indexOf(2) == 1);
- * ok(arr.indexOf(3) == 2);
- * });
- *
- * suite('String');
- *
- * test('#length', function(){
- * ok('foo'.length == 3);
- * });
- *
- */
-
-module.exports = function(suite){
- var suites = [suite];
-
- suite.on('pre-require', function(context, file, mocha){
-
- /**
- * Execute before running tests.
- */
-
- context.before = function(fn){
- suites[0].beforeAll(fn);
- };
-
- /**
- * Execute after running tests.
- */
-
- context.after = function(fn){
- suites[0].afterAll(fn);
- };
-
- /**
- * Execute before each test case.
- */
-
- context.beforeEach = function(fn){
- suites[0].beforeEach(fn);
- };
-
- /**
- * Execute after each test case.
- */
-
- context.afterEach = function(fn){
- suites[0].afterEach(fn);
- };
-
- /**
- * Describe a "suite" with the given `title`.
- */
-
- context.suite = function(title){
- if (suites.length > 1) suites.shift();
- var suite = Suite.create(suites[0], title);
- suites.unshift(suite);
- return suite;
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.suite.only = function(title, fn){
- var suite = context.suite(title, fn);
- mocha.grep(suite.fullTitle());
- };
-
- /**
- * Describe a specification or test-case
- * with the given `title` and callback `fn`
- * acting as a thunk.
- */
-
- context.test = function(title, fn){
- var test = new Test(title, fn);
- suites[0].addTest(test);
- return test;
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.test.only = function(title, fn){
- var test = context.test(title, fn);
- mocha.grep(test.fullTitle());
- };
-
- /**
- * Pending test case.
- */
-
- context.test.skip = function(title){
- context.test(title);
- };
- });
-};
-
-}); // module: interfaces/qunit.js
-
-require.register("interfaces/tdd.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
- , Test = require('../test');
-
-/**
- * TDD-style interface:
- *
- * suite('Array', function(){
- * suite('#indexOf()', function(){
- * suiteSetup(function(){
- *
- * });
- *
- * test('should return -1 when not present', function(){
- *
- * });
- *
- * test('should return the index when present', function(){
- *
- * });
- *
- * suiteTeardown(function(){
- *
- * });
- * });
- * });
- *
- */
-
-module.exports = function(suite){
- var suites = [suite];
-
- suite.on('pre-require', function(context, file, mocha){
-
- /**
- * Execute before each test case.
- */
-
- context.setup = function(fn){
- suites[0].beforeEach(fn);
- };
-
- /**
- * Execute after each test case.
- */
-
- context.teardown = function(fn){
- suites[0].afterEach(fn);
- };
-
- /**
- * Execute before the suite.
- */
-
- context.suiteSetup = function(fn){
- suites[0].beforeAll(fn);
- };
-
- /**
- * Execute after the suite.
- */
-
- context.suiteTeardown = function(fn){
- suites[0].afterAll(fn);
- };
-
- /**
- * Describe a "suite" with the given `title`
- * and callback `fn` containing nested suites
- * and/or tests.
- */
-
- context.suite = function(title, fn){
- var suite = Suite.create(suites[0], title);
- suites.unshift(suite);
- fn.call(suite);
- suites.shift();
- return suite;
- };
-
- /**
- * Pending suite.
- */
- context.suite.skip = function(title, fn) {
- var suite = Suite.create(suites[0], title);
- suite.pending = true;
- suites.unshift(suite);
- fn.call(suite);
- suites.shift();
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.suite.only = function(title, fn){
- var suite = context.suite(title, fn);
- mocha.grep(suite.fullTitle());
- };
-
- /**
- * Describe a specification or test-case
- * with the given `title` and callback `fn`
- * acting as a thunk.
- */
-
- context.test = function(title, fn){
- var suite = suites[0];
- if (suite.pending) var fn = null;
- var test = new Test(title, fn);
- suite.addTest(test);
- return test;
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.test.only = function(title, fn){
- var test = context.test(title, fn);
- mocha.grep(test.fullTitle());
- };
-
- /**
- * Pending test case.
- */
-
- context.test.skip = function(title){
- context.test(title);
- };
- });
-};
-
-}); // module: interfaces/tdd.js
-
-require.register("mocha.js", function(module, exports, require){
-/*!
- * mocha
- * Copyright(c) 2011 TJ Holowaychuk <[email protected]>
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var path = require('browser/path')
- , utils = require('./utils');
-
-/**
- * Expose `Mocha`.
- */
-
-exports = module.exports = Mocha;
-
-/**
- * Expose internals.
- */
-
-exports.utils = utils;
-exports.interfaces = require('./interfaces');
-exports.reporters = require('./reporters');
-exports.Runnable = require('./runnable');
-exports.Context = require('./context');
-exports.Runner = require('./runner');
-exports.Suite = require('./suite');
-exports.Hook = require('./hook');
-exports.Test = require('./test');
-
-/**
- * Return image `name` path.
- *
- * @param {String} name
- * @return {String}
- * @api private
- */
-
-function image(name) {
- return __dirname + '/../images/' + name + '.png';
-}
-
-/**
- * Setup mocha with `options`.
- *
- * Options:
- *
- * - `ui` name "bdd", "tdd", "exports" etc
- * - `reporter` reporter instance, defaults to `mocha.reporters.Dot`
- * - `globals` array of accepted globals
- * - `timeout` timeout in milliseconds
- * - `bail` bail on the first test failure
- * - `slow` milliseconds to wait before considering a test slow
- * - `ignoreLeaks` ignore global leaks
- * - `grep` string or regexp to filter tests with
- *
- * @param {Object} options
- * @api public
- */
-
-function Mocha(options) {
- options = options || {};
- this.files = [];
- this.options = options;
- this.grep(options.grep);
- this.suite = new exports.Suite('', new exports.Context);
- this.ui(options.ui);
- this.bail(options.bail);
- this.reporter(options.reporter);
- if (options.timeout) this.timeout(options.timeout);
- if (options.slow) this.slow(options.slow);
-}
-
-/**
- * Enable or disable bailing on the first failure.
- *
- * @param {Boolean} [bail]
- * @api public
- */
-
-Mocha.prototype.bail = function(bail){
- if (0 == arguments.length) bail = true;
- this.suite.bail(bail);
- return this;
-};
-
-/**
- * Add test `file`.
- *
- * @param {String} file
- * @api public
- */
-
-Mocha.prototype.addFile = function(file){
- this.files.push(file);
- return this;
-};
-
-/**
- * Set reporter to `reporter`, defaults to "dot".
- *
- * @param {String|Function} reporter name or constructor
- * @api public
- */
-
-Mocha.prototype.reporter = function(reporter){
- if ('function' == typeof reporter) {
- this._reporter = reporter;
- } else {
- reporter = reporter || 'dot';
- try {
- this._reporter = require('./reporters/' + reporter);
- } catch (err) {
- this._reporter = require(reporter);
- }
- if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"');
- }
- return this;
-};
-
-/**
- * Set test UI `name`, defaults to "bdd".
- *
- * @param {String} bdd
- * @api public
- */
-
-Mocha.prototype.ui = function(name){
- name = name || 'bdd';
- this._ui = exports.interfaces[name];
- if (!this._ui) throw new Error('invalid interface "' + name + '"');
- this._ui = this._ui(this.suite);
- return this;
-};
-
-/**
- * Load registered files.
- *
- * @api private
- */
-
-Mocha.prototype.loadFiles = function(fn){
- var self = this;
- var suite = this.suite;
- var pending = this.files.length;
- this.files.forEach(function(file){
- file = path.resolve(file);
- suite.emit('pre-require', global, file, self);
- suite.emit('require', require(file), file, self);
- suite.emit('post-require', global, file, self);
- --pending || (fn && fn());
- });
-};
-
-/**
- * Enable growl support.
- *
- * @api private
- */
-
-Mocha.prototype._growl = function(runner, reporter) {
- var notify = require('growl');
-
- runner.on('end', function(){
- var stats = reporter.stats;
- if (stats.failures) {
- var msg = stats.failures + ' of ' + runner.total + ' tests failed';
- notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
- } else {
- notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
- name: 'mocha'
- , title: 'Passed'
- , image: image('ok')
- });
- }
- });
-};
-
-/**
- * Add regexp to grep, if `re` is a string it is escaped.
- *
- * @param {RegExp|String} re
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.grep = function(re){
- this.options.grep = 'string' == typeof re
- ? new RegExp(utils.escapeRegexp(re))
- : re;
- return this;
-};
-
-/**
- * Invert `.grep()` matches.
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.invert = function(){
- this.options.invert = true;
- return this;
-};
-
-/**
- * Ignore global leaks.
- *
- * @param {Boolean} ignore
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.ignoreLeaks = function(ignore){
- this.options.ignoreLeaks = !!ignore;
- return this;
-};
-
-/**
- * Enable global leak checking.
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.checkLeaks = function(){
- this.options.ignoreLeaks = false;
- return this;
-};
-
-/**
- * Enable growl support.
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.growl = function(){
- this.options.growl = true;
- return this;
-};
-
-/**
- * Ignore `globals` array or string.
- *
- * @param {Array|String} globals
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.globals = function(globals){
- this.options.globals = (this.options.globals || []).concat(globals);
- return this;
-};
-
-/**
- * Set the timeout in milliseconds.
- *
- * @param {Number} timeout
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.timeout = function(timeout){
- this.suite.timeout(timeout);
- return this;
-};
-
-/**
- * Set slowness threshold in milliseconds.
- *
- * @param {Number} slow
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.slow = function(slow){
- this.suite.slow(slow);
- return this;
-};
-
-/**
- * Makes all tests async (accepting a callback)
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.asyncOnly = function(){
- this.options.asyncOnly = true;
- return this;
-};
-
-/**
- * Run tests and invoke `fn()` when complete.
- *
- * @param {Function} fn
- * @return {Runner}
- * @api public
- */
-
-Mocha.prototype.run = function(fn){
- if (this.files.length) this.loadFiles();
- var suite = this.suite;
- var options = this.options;
- var runner = new exports.Runner(suite);
- var reporter = new this._reporter(runner);
- runner.ignoreLeaks = false !== options.ignoreLeaks;
- runner.asyncOnly = options.asyncOnly;
- if (options.grep) runner.grep(options.grep, options.invert);
- if (options.globals) runner.globals(options.globals);
- if (options.growl) this._growl(runner, reporter);
- return runner.run(fn);
-};
-
-}); // module: mocha.js
-
-require.register("ms.js", function(module, exports, require){
-
-/**
- * Helpers.
- */
-
-var s = 1000;
-var m = s * 60;
-var h = m * 60;
-var d = h * 24;
-
-/**
- * Parse or format the given `val`.
- *
- * @param {String|Number} val
- * @return {String|Number}
- * @api public
- */
-
-module.exports = function(val){
- if ('string' == typeof val) return parse(val);
- return format(val);
-}
-
-/**
- * Parse the given `str` and return milliseconds.
- *
- * @param {String} str
- * @return {Number}
- * @api private
- */
-
-function parse(str) {
- var m = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
- if (!m) return;
- var n = parseFloat(m[1]);
- var type = (m[2] || 'ms').toLowerCase();
- switch (type) {
- case 'years':
- case 'year':
- case 'y':
- return n * 31557600000;
- case 'days':
- case 'day':
- case 'd':
- return n * 86400000;
- case 'hours':
- case 'hour':
- case 'h':
- return n * 3600000;
- case 'minutes':
- case 'minute':
- case 'm':
- return n * 60000;
- case 'seconds':
- case 'second':
- case 's':
- return n * 1000;
- case 'ms':
- return n;
- }
-}
-
-/**
- * Format the given `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api public
- */
-
-function format(ms) {
- if (ms == d) return Math.round(ms / d) + ' day';
- if (ms > d) return Math.round(ms / d) + ' days';
- if (ms == h) return Math.round(ms / h) + ' hour';
- if (ms > h) return Math.round(ms / h) + ' hours';
- if (ms == m) return Math.round(ms / m) + ' minute';
- if (ms > m) return Math.round(ms / m) + ' minutes';
- if (ms == s) return Math.round(ms / s) + ' second';
- if (ms > s) return Math.round(ms / s) + ' seconds';
- return ms + ' ms';
-}
-}); // module: ms.js
-
-require.register("reporters/base.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var tty = require('browser/tty')
- , diff = require('browser/diff')
- , ms = require('../ms');
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
- , setTimeout = global.setTimeout
- , setInterval = global.setInterval
- , clearTimeout = global.clearTimeout
- , clearInterval = global.clearInterval;
-
-/**
- * Check if both stdio streams are associated with a tty.
- */
-
-var isatty = tty.isatty(1) && tty.isatty(2);
-
-/**
- * Expose `Base`.
- */
-
-exports = module.exports = Base;
-
-/**
- * Enable coloring by default.
- */
-
-exports.useColors = isatty;
-
-/**
- * Default color map.
- */
-
-exports.colors = {
- 'pass': 90
- , 'fail': 31
- , 'bright pass': 92
- , 'bright fail': 91
- , 'bright yellow': 93
- , 'pending': 36
- , 'suite': 0
- , 'error title': 0
- , 'error message': 31
- , 'error stack': 90
- , 'checkmark': 32
- , 'fast': 90
- , 'medium': 33
- , 'slow': 31
- , 'green': 32
- , 'light': 90
- , 'diff gutter': 90
- , 'diff added': 42
- , 'diff removed': 41
-};
-
-/**
- * Default symbol map.
- */
-
-exports.symbols = {
- ok: '✓',
- err: '✖',
- dot: '․'
-};
-
-// With node.js on Windows: use symbols available in terminal default fonts
-if ('win32' == process.platform) {
- exports.symbols.ok = '\u221A';
- exports.symbols.err = '\u00D7';
- exports.symbols.dot = '.';
-}
-
-/**
- * Color `str` with the given `type`,
- * allowing colors to be disabled,
- * as well as user-defined color
- * schemes.
- *
- * @param {String} type
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-var color = exports.color = function(type, str) {
- if (!exports.useColors) return str;
- return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
-};
-
-/**
- * Expose term window size, with some
- * defaults for when stderr is not a tty.
- */
-
-exports.window = {
- width: isatty
- ? process.stdout.getWindowSize
- ? process.stdout.getWindowSize(1)[0]
- : tty.getWindowSize()[1]
- : 75
-};
-
-/**
- * Expose some basic cursor interactions
- * that are common among reporters.
- */
-
-exports.cursor = {
- hide: function(){
- process.stdout.write('\u001b[?25l');
- },
-
- show: function(){
- process.stdout.write('\u001b[?25h');
- },
-
- deleteLine: function(){
- process.stdout.write('\u001b[2K');
- },
-
- beginningOfLine: function(){
- process.stdout.write('\u001b[0G');
- },
-
- CR: function(){
- exports.cursor.deleteLine();
- exports.cursor.beginningOfLine();
- }
-};
-
-/**
- * Outut the given `failures` as a list.
- *
- * @param {Array} failures
- * @api public
- */
-
-exports.list = function(failures){
- console.error();
- failures.forEach(function(test, i){
- // format
- var fmt = color('error title', ' %s) %s:\n')
- + color('error message', ' %s')
- + color('error stack', '\n%s\n');
-
- // msg
- var err = test.err
- , message = err.message || ''
- , stack = err.stack || message
- , index = stack.indexOf(message) + message.length
- , msg = stack.slice(0, index)
- , actual = err.actual
- , expected = err.expected
- , escape = true;
-
- // uncaught
- if (err.uncaught) {
- msg = 'Uncaught ' + msg;
- }
-
- // explicitly show diff
- if (err.showDiff && sameType(actual, expected)) {
- escape = false;
- err.actual = actual = stringify(actual);
- err.expected = expected = stringify(expected);
- }
-
- // actual / expected diff
- if ('string' == typeof actual && 'string' == typeof expected) {
- msg = errorDiff(err, 'Words', escape);
-
- // linenos
- var lines = msg.split('\n');
- if (lines.length > 4) {
- var width = String(lines.length).length;
- msg = lines.map(function(str, i){
- return pad(++i, width) + ' |' + ' ' + str;
- }).join('\n');
- }
-
- // legend
- msg = '\n'
- + color('diff removed', 'actual')
- + ' '
- + color('diff added', 'expected')
- + '\n\n'
- + msg
- + '\n';
-
- // indent
- msg = msg.replace(/^/gm, ' ');
-
- fmt = color('error title', ' %s) %s:\n%s')
- + color('error stack', '\n%s\n');
- }
-
- // indent stack trace without msg
- stack = stack.slice(index ? index + 1 : index)
- .replace(/^/gm, ' ');
-
- console.error(fmt, (i + 1), test.fullTitle(), msg, stack);
- });
-};
-
-/**
- * Initialize a new `Base` reporter.
- *
- * All other reporters generally
- * inherit from this reporter, providing
- * stats such as test duration, number
- * of tests passed / failed etc.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Base(runner) {
- var self = this
- , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }
- , failures = this.failures = [];
-
- if (!runner) return;
- this.runner = runner;
-
- runner.stats = stats;
-
- runner.on('start', function(){
- stats.start = new Date;
- });
-
- runner.on('suite', function(suite){
- stats.suites = stats.suites || 0;
- suite.root || stats.suites++;
- });
-
- runner.on('test end', function(test){
- stats.tests = stats.tests || 0;
- stats.tests++;
- });
-
- runner.on('pass', function(test){
- stats.passes = stats.passes || 0;
-
- var medium = test.slow() / 2;
- test.speed = test.duration > test.slow()
- ? 'slow'
- : test.duration > medium
- ? 'medium'
- : 'fast';
-
- stats.passes++;
- });
-
- runner.on('fail', function(test, err){
- stats.failures = stats.failures || 0;
- stats.failures++;
- test.err = err;
- failures.push(test);
- });
-
- runner.on('end', function(){
- stats.end = new Date;
- stats.duration = new Date - stats.start;
- });
-
- runner.on('pending', function(){
- stats.pending++;
- });
-}
-
-/**
- * Output common epilogue used by many of
- * the bundled reporters.
- *
- * @api public
- */
-
-Base.prototype.epilogue = function(){
- var stats = this.stats;
- var tests;
- var fmt;
-
- console.log();
-
- // passes
- fmt = color('bright pass', ' ')
- + color('green', ' %d passing')
- + color('light', ' (%s)');
-
- console.log(fmt,
- stats.passes || 0,
- ms(stats.duration));
-
- // pending
- if (stats.pending) {
- fmt = color('pending', ' ')
- + color('pending', ' %d pending');
-
- console.log(fmt, stats.pending);
- }
-
- // failures
- if (stats.failures) {
- fmt = color('fail', ' %d failing');
-
- console.error(fmt,
- stats.failures);
-
- Base.list(this.failures);
- console.error();
- }
-
- console.log();
-};
-
-/**
- * Pad the given `str` to `len`.
- *
- * @param {String} str
- * @param {String} len
- * @return {String}
- * @api private
- */
-
-function pad(str, len) {
- str = String(str);
- return Array(len - str.length + 1).join(' ') + str;
-}
-
-/**
- * Return a character diff for `err`.
- *
- * @param {Error} err
- * @return {String}
- * @api private
- */
-
-function errorDiff(err, type, escape) {
- return diff['diff' + type](err.actual, err.expected).map(function(str){
- if (escape) {
- str.value = str.value
- .replace(/\t/g, '<tab>')
- .replace(/\r/g, '<CR>')
- .replace(/\n/g, '<LF>\n');
- }
- if (str.added) return colorLines('diff added', str.value);
- if (str.removed) return colorLines('diff removed', str.value);
- return str.value;
- }).join('');
-}
-
-/**
- * Color lines for `str`, using the color `name`.
- *
- * @param {String} name
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-function colorLines(name, str) {
- return str.split('\n').map(function(str){
- return color(name, str);
- }).join('\n');
-}
-
-/**
- * Stringify `obj`.
- *
- * @param {Mixed} obj
- * @return {String}
- * @api private
- */
-
-function stringify(obj) {
- if (obj instanceof RegExp) return obj.toString();
- return JSON.stringify(obj, null, 2);
-}
-
-/**
- * Check that a / b have the same type.
- *
- * @param {Object} a
- * @param {Object} b
- * @return {Boolean}
- * @api private
- */
-
-function sameType(a, b) {
- a = Object.prototype.toString.call(a);
- b = Object.prototype.toString.call(b);
- return a == b;
-}
-
-}); // module: reporters/base.js
-
-require.register("reporters/doc.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , utils = require('../utils');
-
-/**
- * Expose `Doc`.
- */
-
-exports = module.exports = Doc;
-
-/**
- * Initialize a new `Doc` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Doc(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , total = runner.total
- , indents = 2;
-
- function indent() {
- return Array(indents).join(' ');
- }
-
- runner.on('suite', function(suite){
- if (suite.root) return;
- ++indents;
- console.log('%s<section class="suite">', indent());
- ++indents;
- console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
- console.log('%s<dl>', indent());
- });
-
- runner.on('suite end', function(suite){
- if (suite.root) return;
- console.log('%s</dl>', indent());
- --indents;
- console.log('%s</section>', indent());
- --indents;
- });
-
- runner.on('pass', function(test){
- console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title));
- var code = utils.escape(utils.clean(test.fn.toString()));
- console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
- });
-}
-
-}); // module: reporters/doc.js
-
-require.register("reporters/dot.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , color = Base.color;
-
-/**
- * Expose `Dot`.
- */
-
-exports = module.exports = Dot;
-
-/**
- * Initialize a new `Dot` matrix test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Dot(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , width = Base.window.width * .75 | 0
- , n = 0;
-
- runner.on('start', function(){
- process.stdout.write('\n ');
- });
-
- runner.on('pending', function(test){
- process.stdout.write(color('pending', Base.symbols.dot));
- });
-
- runner.on('pass', function(test){
- if (++n % width == 0) process.stdout.write('\n ');
- if ('slow' == test.speed) {
- process.stdout.write(color('bright yellow', Base.symbols.dot));
- } else {
- process.stdout.write(color(test.speed, Base.symbols.dot));
- }
- });
-
- runner.on('fail', function(test, err){
- if (++n % width == 0) process.stdout.write('\n ');
- process.stdout.write(color('fail', Base.symbols.dot));
- });
-
- runner.on('end', function(){
- console.log();
- self.epilogue();
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-Dot.prototype = new F;
-Dot.prototype.constructor = Dot;
-
-}); // module: reporters/dot.js
-
-require.register("reporters/html-cov.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var JSONCov = require('./json-cov')
- , fs = require('browser/fs');
-
-/**
- * Expose `HTMLCov`.
- */
-
-exports = module.exports = HTMLCov;
-
-/**
- * Initialize a new `JsCoverage` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function HTMLCov(runner) {
- var jade = require('jade')
- , file = __dirname + '/templates/coverage.jade'
- , str = fs.readFileSync(file, 'utf8')
- , fn = jade.compile(str, { filename: file })
- , self = this;
-
- JSONCov.call(this, runner, false);
-
- runner.on('end', function(){
- process.stdout.write(fn({
- cov: self.cov
- , coverageClass: coverageClass
- }));
- });
-}
-
-/**
- * Return coverage class for `n`.
- *
- * @return {String}
- * @api private
- */
-
-function coverageClass(n) {
- if (n >= 75) return 'high';
- if (n >= 50) return 'medium';
- if (n >= 25) return 'low';
- return 'terrible';
-}
-}); // module: reporters/html-cov.js
-
-require.register("reporters/html.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , utils = require('../utils')
- , Progress = require('../browser/progress')
- , escape = utils.escape;
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
- , setTimeout = global.setTimeout
- , setInterval = global.setInterval
- , clearTimeout = global.clearTimeout
- , clearInterval = global.clearInterval;
-
-/**
- * Expose `Doc`.
- */
-
-exports = module.exports = HTML;
-
-/**
- * Stats template.
- */
-
-var statsTemplate = '<ul id="mocha-stats">'
- + '<li class="progress"><canvas width="40" height="40"></canvas></li>'
- + '<li class="passes"><a href="#">passes:</a> <em>0</em></li>'
- + '<li class="failures"><a href="#">failures:</a> <em>0</em></li>'
- + '<li class="duration">duration: <em>0</em>s</li>'
- + '</ul>';
-
-/**
- * Initialize a new `Doc` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function HTML(runner, root) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , total = runner.total
- , stat = fragment(statsTemplate)
- , items = stat.getElementsByTagName('li')
- , passes = items[1].getElementsByTagName('em')[0]
- , passesLink = items[1].getElementsByTagName('a')[0]
- , failures = items[2].getElementsByTagName('em')[0]
- , failuresLink = items[2].getElementsByTagName('a')[0]
- , duration = items[3].getElementsByTagName('em')[0]
- , canvas = stat.getElementsByTagName('canvas')[0]
- , report = fragment('<ul id="mocha-report"></ul>')
- , stack = [report]
- , progress
- , ctx
-
- root = root || document.getElementById('mocha');
-
- if (canvas.getContext) {
- var ratio = window.devicePixelRatio || 1;
- canvas.style.width = canvas.width;
- canvas.style.height = canvas.height;
- canvas.width *= ratio;
- canvas.height *= ratio;
- ctx = canvas.getContext('2d');
- ctx.scale(ratio, ratio);
- progress = new Progress;
- }
-
- if (!root) return error('#mocha div missing, add it to your document');
-
- // pass toggle
- on(passesLink, 'click', function(){
- unhide();
- var name = /pass/.test(report.className) ? '' : ' pass';
- report.className = report.className.replace(/fail|pass/g, '') + name;
- if (report.className.trim()) hideSuitesWithout('test pass');
- });
-
- // failure toggle
- on(failuresLink, 'click', function(){
- unhide();
- var name = /fail/.test(report.className) ? '' : ' fail';
- report.className = report.className.replace(/fail|pass/g, '') + name;
- if (report.className.trim()) hideSuitesWithout('test fail');
- });
-
- root.appendChild(stat);
- root.appendChild(report);
-
- if (progress) progress.size(40);
-
- runner.on('suite', function(suite){
- if (suite.root) return;
-
- // suite
- var url = '?grep=' + encodeURIComponent(suite.fullTitle());
- var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title));
-
- // container
- stack[0].appendChild(el);
- stack.unshift(document.createElement('ul'));
- el.appendChild(stack[0]);
- });
-
- runner.on('suite end', function(suite){
- if (suite.root) return;
- stack.shift();
- });
-
- runner.on('fail', function(test, err){
- if ('hook' == test.type) runner.emit('test end', test);
- });
-
- runner.on('test end', function(test){
- // TODO: add to stats
- var percent = stats.tests / this.total * 100 | 0;
- if (progress) progress.update(percent).draw(ctx);
-
- // update stats
- var ms = new Date - stats.start;
- text(passes, stats.passes);
- text(failures, stats.failures);
- text(duration, (ms / 1000).toFixed(2));
-
- // test
- if ('passed' == test.state) {
- var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="?grep=%e" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, encodeURIComponent(test.fullTitle()));
- } else if (test.pending) {
- var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
- } else {
- var el = fragment('<li class="test fail"><h2>%e <a href="?grep=%e" class="replay">‣</a></h2></li>', test.title, encodeURIComponent(test.fullTitle()));
- var str = test.err.stack || test.err.toString();
-
- // FF / Opera do not add the message
- if (!~str.indexOf(test.err.message)) {
- str = test.err.message + '\n' + str;
- }
-
- // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
- // check for the result of the stringifying.
- if ('[object Error]' == str) str = test.err.message;
-
- // Safari doesn't give you a stack. Let's at least provide a source line.
- if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) {
- str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")";
- }
-
- el.appendChild(fragment('<pre class="error">%e</pre>', str));
- }
-
- // toggle code
- // TODO: defer
- if (!test.pending) {
- var h2 = el.getElementsByTagName('h2')[0];
-
- on(h2, 'click', function(){
- pre.style.display = 'none' == pre.style.display
- ? 'block'
- : 'none';
- });
-
- var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString()));
- el.appendChild(pre);
- pre.style.display = 'none';
- }
-
- // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
- if (stack[0]) stack[0].appendChild(el);
- });
-}
-
-/**
- * Display error `msg`.
- */
-
-function error(msg) {
- document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
-}
-
-/**
- * Return a DOM fragment from `html`.
- */
-
-function fragment(html) {
- var args = arguments
- , div = document.createElement('div')
- , i = 1;
-
- div.innerHTML = html.replace(/%([se])/g, function(_, type){
- switch (type) {
- case 's': return String(args[i++]);
- case 'e': return escape(args[i++]);
- }
- });
-
- return div.firstChild;
-}
-
-/**
- * Check for suites that do not have elements
- * with `classname`, and hide them.
- */
-
-function hideSuitesWithout(classname) {
- var suites = document.getElementsByClassName('suite');
- for (var i = 0; i < suites.length; i++) {
- var els = suites[i].getElementsByClassName(classname);
- if (0 == els.length) suites[i].className += ' hidden';
- }
-}
-
-/**
- * Unhide .hidden suites.
- */
-
-function unhide() {
- var els = document.getElementsByClassName('suite hidden');
- for (var i = 0; i < els.length; ++i) {
- els[i].className = els[i].className.replace('suite hidden', 'suite');
- }
-}
-
-/**
- * Set `el` text to `str`.
- */
-
-function text(el, str) {
- if (el.textContent) {
- el.textContent = str;
- } else {
- el.innerText = str;
- }
-}
-
-/**
- * Listen on `event` with callback `fn`.
- */
-
-function on(el, event, fn) {
- if (el.addEventListener) {
- el.addEventListener(event, fn, false);
- } else {
- el.attachEvent('on' + event, fn);
- }
-}
-
-}); // module: reporters/html.js
-
-require.register("reporters/index.js", function(module, exports, require){
-
-exports.Base = require('./base');
-exports.Dot = require('./dot');
-exports.Doc = require('./doc');
-exports.TAP = require('./tap');
-exports.JSON = require('./json');
-exports.HTML = require('./html');
-exports.List = require('./list');
-exports.Min = require('./min');
-exports.Spec = require('./spec');
-exports.Nyan = require('./nyan');
-exports.XUnit = require('./xunit');
-exports.Markdown = require('./markdown');
-exports.Progress = require('./progress');
-exports.Landing = require('./landing');
-exports.JSONCov = require('./json-cov');
-exports.HTMLCov = require('./html-cov');
-exports.JSONStream = require('./json-stream');
-exports.Teamcity = require('./teamcity');
-
-}); // module: reporters/index.js
-
-require.register("reporters/json-cov.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-
-/**
- * Expose `JSONCov`.
- */
-
-exports = module.exports = JSONCov;
-
-/**
- * Initialize a new `JsCoverage` reporter.
- *
- * @param {Runner} runner
- * @param {Boolean} output
- * @api public
- */
-
-function JSONCov(runner, output) {
- var self = this
- , output = 1 == arguments.length ? true : output;
-
- Base.call(this, runner);
-
- var tests = []
- , failures = []
- , passes = [];
-
- runner.on('test end', function(test){
- tests.push(test);
- });
-
- runner.on('pass', function(test){
- passes.push(test);
- });
-
- runner.on('fail', function(test){
- failures.push(test);
- });
-
- runner.on('end', function(){
- var cov = global._$jscoverage || {};
- var result = self.cov = map(cov);
- result.stats = self.stats;
- result.tests = tests.map(clean);
- result.failures = failures.map(clean);
- result.passes = passes.map(clean);
- if (!output) return;
- process.stdout.write(JSON.stringify(result, null, 2 ));
- });
-}
-
-/**
- * Map jscoverage data to a JSON structure
- * suitable for reporting.
- *
- * @param {Object} cov
- * @return {Object}
- * @api private
- */
-
-function map(cov) {
- var ret = {
- instrumentation: 'node-jscoverage'
- , sloc: 0
- , hits: 0
- , misses: 0
- , coverage: 0
- , files: []
- };
-
- for (var filename in cov) {
- var data = coverage(filename, cov[filename]);
- ret.files.push(data);
- ret.hits += data.hits;
- ret.misses += data.misses;
- ret.sloc += data.sloc;
- }
-
- ret.files.sort(function(a, b) {
- return a.filename.localeCompare(b.filename);
- });
-
- if (ret.sloc > 0) {
- ret.coverage = (ret.hits / ret.sloc) * 100;
- }
-
- return ret;
-};
-
-/**
- * Map jscoverage data for a single source file
- * to a JSON structure suitable for reporting.
- *
- * @param {String} filename name of the source file
- * @param {Object} data jscoverage coverage data
- * @return {Object}
- * @api private
- */
-
-function coverage(filename, data) {
- var ret = {
- filename: filename,
- coverage: 0,
- hits: 0,
- misses: 0,
- sloc: 0,
- source: {}
- };
-
- data.source.forEach(function(line, num){
- num++;
-
- if (data[num] === 0) {
- ret.misses++;
- ret.sloc++;
- } else if (data[num] !== undefined) {
- ret.hits++;
- ret.sloc++;
- }
-
- ret.source[num] = {
- source: line
- , coverage: data[num] === undefined
- ? ''
- : data[num]
- };
- });
-
- ret.coverage = ret.hits / ret.sloc * 100;
-
- return ret;
-}
-
-/**
- * Return a plain-object representation of `test`
- * free of cyclic properties etc.
- *
- * @param {Object} test
- * @return {Object}
- * @api private
- */
-
-function clean(test) {
- return {
- title: test.title
- , fullTitle: test.fullTitle()
- , duration: test.duration
- }
-}
-
-}); // module: reporters/json-cov.js
-
-require.register("reporters/json-stream.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , color = Base.color;
-
-/**
- * Expose `List`.
- */
-
-exports = module.exports = List;
-
-/**
- * Initialize a new `List` test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function List(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , total = runner.total;
-
- runner.on('start', function(){
- console.log(JSON.stringify(['start', { total: total }]));
- });
-
- runner.on('pass', function(test){
- console.log(JSON.stringify(['pass', clean(test)]));
- });
-
- runner.on('fail', function(test, err){
- console.log(JSON.stringify(['fail', clean(test)]));
- });
-
- runner.on('end', function(){
- process.stdout.write(JSON.stringify(['end', self.stats]));
- });
-}
-
-/**
- * Return a plain-object representation of `test`
- * free of cyclic properties etc.
- *
- * @param {Object} test
- * @return {Object}
- * @api private
- */
-
-function clean(test) {
- return {
- title: test.title
- , fullTitle: test.fullTitle()
- , duration: test.duration
- }
-}
-}); // module: reporters/json-stream.js
-
-require.register("reporters/json.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `JSON`.
- */
-
-exports = module.exports = JSONReporter;
-
-/**
- * Initialize a new `JSON` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function JSONReporter(runner) {
- var self = this;
- Base.call(this, runner);
-
- var tests = []
- , failures = []
- , passes = [];
-
- runner.on('test end', function(test){
- tests.push(test);
- });
-
- runner.on('pass', function(test){
- passes.push(test);
- });
-
- runner.on('fail', function(test){
- failures.push(test);
- });
-
- runner.on('end', function(){
- var obj = {
- stats: self.stats
- , tests: tests.map(clean)
- , failures: failures.map(clean)
- , passes: passes.map(clean)
- };
-
- process.stdout.write(JSON.stringify(obj, null, 2));
- });
-}
-
-/**
- * Return a plain-object representation of `test`
- * free of cyclic properties etc.
- *
- * @param {Object} test
- * @return {Object}
- * @api private
- */
-
-function clean(test) {
- return {
- title: test.title
- , fullTitle: test.fullTitle()
- , duration: test.duration
- }
-}
-}); // module: reporters/json.js
-
-require.register("reporters/landing.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `Landing`.
- */
-
-exports = module.exports = Landing;
-
-/**
- * Airplane color.
- */
-
-Base.colors.plane = 0;
-
-/**
- * Airplane crash color.
- */
-
-Base.colors['plane crash'] = 31;
-
-/**
- * Runway color.
- */
-
-Base.colors.runway = 90;
-
-/**
- * Initialize a new `Landing` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Landing(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , width = Base.window.width * .75 | 0
- , total = runner.total
- , stream = process.stdout
- , plane = color('plane', '✈')
- , crashed = -1
- , n = 0;
-
- function runway() {
- var buf = Array(width).join('-');
- return ' ' + color('runway', buf);
- }
-
- runner.on('start', function(){
- stream.write('\n ');
- cursor.hide();
- });
-
- runner.on('test end', function(test){
- // check if the plane crashed
- var col = -1 == crashed
- ? width * ++n / total | 0
- : crashed;
-
- // show the crash
- if ('failed' == test.state) {
- plane = color('plane crash', '✈');
- crashed = col;
- }
-
- // render landing strip
- stream.write('\u001b[4F\n\n');
- stream.write(runway());
- stream.write('\n ');
- stream.write(color('runway', Array(col).join('⋅')));
- stream.write(plane)
- stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
- stream.write(runway());
- stream.write('\u001b[0m');
- });
-
- runner.on('end', function(){
- cursor.show();
- console.log();
- self.epilogue();
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-Landing.prototype = new F;
-Landing.prototype.constructor = Landing;
-
-}); // module: reporters/landing.js
-
-require.register("reporters/list.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `List`.
- */
-
-exports = module.exports = List;
-
-/**
- * Initialize a new `List` test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function List(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , n = 0;
-
- runner.on('start', function(){
- console.log();
- });
-
- runner.on('test', function(test){
- process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
- });
-
- runner.on('pending', function(test){
- var fmt = color('checkmark', ' -')
- + color('pending', ' %s');
- console.log(fmt, test.fullTitle());
- });
-
- runner.on('pass', function(test){
- var fmt = color('checkmark', ' '+Base.symbols.dot)
- + color('pass', ' %s: ')
- + color(test.speed, '%dms');
- cursor.CR();
- console.log(fmt, test.fullTitle(), test.duration);
- });
-
- runner.on('fail', function(test, err){
- cursor.CR();
- console.log(color('fail', ' %d) %s'), ++n, test.fullTitle());
- });
-
- runner.on('end', self.epilogue.bind(self));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-List.prototype = new F;
-List.prototype.constructor = List;
-
-
-}); // module: reporters/list.js
-
-require.register("reporters/markdown.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , utils = require('../utils');
-
-/**
- * Expose `Markdown`.
- */
-
-exports = module.exports = Markdown;
-
-/**
- * Initialize a new `Markdown` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Markdown(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , level = 0
- , buf = '';
-
- function title(str) {
- return Array(level).join('#') + ' ' + str;
- }
-
- function indent() {
- return Array(level).join(' ');
- }
-
- function mapTOC(suite, obj) {
- var ret = obj;
- obj = obj[suite.title] = obj[suite.title] || { suite: suite };
- suite.suites.forEach(function(suite){
- mapTOC(suite, obj);
- });
- return ret;
- }
-
- function stringifyTOC(obj, level) {
- ++level;
- var buf = '';
- var link;
- for (var key in obj) {
- if ('suite' == key) continue;
- if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
- if (key) buf += Array(level).join(' ') + link;
- buf += stringifyTOC(obj[key], level);
- }
- --level;
- return buf;
- }
-
- function generateTOC(suite) {
- var obj = mapTOC(suite, {});
- return stringifyTOC(obj, 0);
- }
-
- generateTOC(runner.suite);
-
- runner.on('suite', function(suite){
- ++level;
- var slug = utils.slug(suite.fullTitle());
- buf += '<a name="' + slug + '"></a>' + '\n';
- buf += title(suite.title) + '\n';
- });
-
- runner.on('suite end', function(suite){
- --level;
- });
-
- runner.on('pass', function(test){
- var code = utils.clean(test.fn.toString());
- buf += test.title + '.\n';
- buf += '\n```js\n';
- buf += code + '\n';
- buf += '```\n\n';
- });
-
- runner.on('end', function(){
- process.stdout.write('# TOC\n');
- process.stdout.write(generateTOC(runner.suite));
- process.stdout.write(buf);
- });
-}
-}); // module: reporters/markdown.js
-
-require.register("reporters/min.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-
-/**
- * Expose `Min`.
- */
-
-exports = module.exports = Min;
-
-/**
- * Initialize a new `Min` minimal test reporter (best used with --watch).
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Min(runner) {
- Base.call(this, runner);
-
- runner.on('start', function(){
- // clear screen
- process.stdout.write('\u001b[2J');
- // set cursor position
- process.stdout.write('\u001b[1;3H');
- });
-
- runner.on('end', this.epilogue.bind(this));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-Min.prototype = new F;
-Min.prototype.constructor = Min;
-
-
-}); // module: reporters/min.js
-
-require.register("reporters/nyan.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , color = Base.color;
-
-/**
- * Expose `Dot`.
- */
-
-exports = module.exports = NyanCat;
-
-/**
- * Initialize a new `Dot` matrix test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function NyanCat(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , width = Base.window.width * .75 | 0
- , rainbowColors = this.rainbowColors = self.generateColors()
- , colorIndex = this.colorIndex = 0
- , numerOfLines = this.numberOfLines = 4
- , trajectories = this.trajectories = [[], [], [], []]
- , nyanCatWidth = this.nyanCatWidth = 11
- , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth)
- , scoreboardWidth = this.scoreboardWidth = 5
- , tick = this.tick = 0
- , n = 0;
-
- runner.on('start', function(){
- Base.cursor.hide();
- self.draw('start');
- });
-
- runner.on('pending', function(test){
- self.draw('pending');
- });
-
- runner.on('pass', function(test){
- self.draw('pass');
- });
-
- runner.on('fail', function(test, err){
- self.draw('fail');
- });
-
- runner.on('end', function(){
- Base.cursor.show();
- for (var i = 0; i < self.numberOfLines; i++) write('\n');
- self.epilogue();
- });
-}
-
-/**
- * Draw the nyan cat with runner `status`.
- *
- * @param {String} status
- * @api private
- */
-
-NyanCat.prototype.draw = function(status){
- this.appendRainbow();
- this.drawScoreboard();
- this.drawRainbow();
- this.drawNyanCat(status);
- this.tick = !this.tick;
-};
-
-/**
- * Draw the "scoreboard" showing the number
- * of passes, failures and pending tests.
- *
- * @api private
- */
-
-NyanCat.prototype.drawScoreboard = function(){
- var stats = this.stats;
- var colors = Base.colors;
-
- function draw(color, n) {
- write(' ');
- write('\u001b[' + color + 'm' + n + '\u001b[0m');
- write('\n');
- }
-
- draw(colors.green, stats.passes);
- draw(colors.fail, stats.failures);
- draw(colors.pending, stats.pending);
- write('\n');
-
- this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Append the rainbow.
- *
- * @api private
- */
-
-NyanCat.prototype.appendRainbow = function(){
- var segment = this.tick ? '_' : '-';
- var rainbowified = this.rainbowify(segment);
-
- for (var index = 0; index < this.numberOfLines; index++) {
- var trajectory = this.trajectories[index];
- if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift();
- trajectory.push(rainbowified);
- }
-};
-
-/**
- * Draw the rainbow.
- *
- * @api private
- */
-
-NyanCat.prototype.drawRainbow = function(){
- var self = this;
-
- this.trajectories.forEach(function(line, index) {
- write('\u001b[' + self.scoreboardWidth + 'C');
- write(line.join(''));
- write('\n');
- });
-
- this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Draw the nyan cat with `status`.
- *
- * @param {String} status
- * @api private
- */
-
-NyanCat.prototype.drawNyanCat = function(status) {
- var self = this;
- var startWidth = this.scoreboardWidth + this.trajectories[0].length;
- var color = '\u001b[' + startWidth + 'C';
- var padding = '';
-
- write(color);
- write('_,------,');
- write('\n');
-
- write(color);
- padding = self.tick ? ' ' : ' ';
- write('_|' + padding + '/\\_/\\ ');
- write('\n');
-
- write(color);
- padding = self.tick ? '_' : '__';
- var tail = self.tick ? '~' : '^';
- var face;
- switch (status) {
- case 'pass':
- face = '( ^ .^)';
- break;
- case 'fail':
- face = '( o .o)';
- break;
- default:
- face = '( - .-)';
- }
- write(tail + '|' + padding + face + ' ');
- write('\n');
-
- write(color);
- padding = self.tick ? ' ' : ' ';
- write(padding + '"" "" ');
- write('\n');
-
- this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Move cursor up `n`.
- *
- * @param {Number} n
- * @api private
- */
-
-NyanCat.prototype.cursorUp = function(n) {
- write('\u001b[' + n + 'A');
-};
-
-/**
- * Move cursor down `n`.
- *
- * @param {Number} n
- * @api private
- */
-
-NyanCat.prototype.cursorDown = function(n) {
- write('\u001b[' + n + 'B');
-};
-
-/**
- * Generate rainbow colors.
- *
- * @return {Array}
- * @api private
- */
-
-NyanCat.prototype.generateColors = function(){
- var colors = [];
-
- for (var i = 0; i < (6 * 7); i++) {
- var pi3 = Math.floor(Math.PI / 3);
- var n = (i * (1.0 / 6));
- var r = Math.floor(3 * Math.sin(n) + 3);
- var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
- var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
- colors.push(36 * r + 6 * g + b + 16);
- }
-
- return colors;
-};
-
-/**
- * Apply rainbow to the given `str`.
- *
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-NyanCat.prototype.rainbowify = function(str){
- var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
- this.colorIndex += 1;
- return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
-};
-
-/**
- * Stdout helper.
- */
-
-function write(string) {
- process.stdout.write(string);
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-NyanCat.prototype = new F;
-NyanCat.prototype.constructor = NyanCat;
-
-
-}); // module: reporters/nyan.js
-
-require.register("reporters/progress.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `Progress`.
- */
-
-exports = module.exports = Progress;
-
-/**
- * General progress bar color.
- */
-
-Base.colors.progress = 90;
-
-/**
- * Initialize a new `Progress` bar test reporter.
- *
- * @param {Runner} runner
- * @param {Object} options
- * @api public
- */
-
-function Progress(runner, options) {
- Base.call(this, runner);
-
- var self = this
- , options = options || {}
- , stats = this.stats
- , width = Base.window.width * .50 | 0
- , total = runner.total
- , complete = 0
- , max = Math.max;
-
- // default chars
- options.open = options.open || '[';
- options.complete = options.complete || '▬';
- options.incomplete = options.incomplete || Base.symbols.dot;
- options.close = options.close || ']';
- options.verbose = false;
-
- // tests started
- runner.on('start', function(){
- console.log();
- cursor.hide();
- });
-
- // tests complete
- runner.on('test end', function(){
- complete++;
- var incomplete = total - complete
- , percent = complete / total
- , n = width * percent | 0
- , i = width - n;
-
- cursor.CR();
- process.stdout.write('\u001b[J');
- process.stdout.write(color('progress', ' ' + options.open));
- process.stdout.write(Array(n).join(options.complete));
- process.stdout.write(Array(i).join(options.incomplete));
- process.stdout.write(color('progress', options.close));
- if (options.verbose) {
- process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
- }
- });
-
- // tests are complete, output some stats
- // and the failures if any
- runner.on('end', function(){
- cursor.show();
- console.log();
- self.epilogue();
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-Progress.prototype = new F;
-Progress.prototype.constructor = Progress;
-
-
-}); // module: reporters/progress.js
-
-require.register("reporters/spec.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `Spec`.
- */
-
-exports = module.exports = Spec;
-
-/**
- * Initialize a new `Spec` test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Spec(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , indents = 0
- , n = 0;
-
- function indent() {
- return Array(indents).join(' ')
- }
-
- runner.on('start', function(){
- console.log();
- });
-
- runner.on('suite', function(suite){
- ++indents;
- console.log(color('suite', '%s%s'), indent(), suite.title);
- });
-
- runner.on('suite end', function(suite){
- --indents;
- if (1 == indents) console.log();
- });
-
- runner.on('test', function(test){
- process.stdout.write(indent() + color('pass', ' ◦ ' + test.title + ': '));
- });
-
- runner.on('pending', function(test){
- var fmt = indent() + color('pending', ' - %s');
- console.log(fmt, test.title);
- });
-
- runner.on('pass', function(test){
- if ('fast' == test.speed) {
- var fmt = indent()
- + color('checkmark', ' ' + Base.symbols.ok)
- + color('pass', ' %s ');
- cursor.CR();
- console.log(fmt, test.title);
- } else {
- var fmt = indent()
- + color('checkmark', ' ' + Base.symbols.ok)
- + color('pass', ' %s ')
- + color(test.speed, '(%dms)');
- cursor.CR();
- console.log(fmt, test.title, test.duration);
- }
- });
-
- runner.on('fail', function(test, err){
- cursor.CR();
- console.log(indent() + color('fail', ' %d) %s'), ++n, test.title);
- });
-
- runner.on('end', self.epilogue.bind(self));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-Spec.prototype = new F;
-Spec.prototype.constructor = Spec;
-
-
-}); // module: reporters/spec.js
-
-require.register("reporters/tap.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `TAP`.
- */
-
-exports = module.exports = TAP;
-
-/**
- * Initialize a new `TAP` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function TAP(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , n = 1
- , passes = 0
- , failures = 0;
-
- runner.on('start', function(){
- var total = runner.grepTotal(runner.suite);
- console.log('%d..%d', 1, total);
- });
-
- runner.on('test end', function(){
- ++n;
- });
-
- runner.on('pending', function(test){
- console.log('ok %d %s # SKIP -', n, title(test));
- });
-
- runner.on('pass', function(test){
- passes++;
- console.log('ok %d %s', n, title(test));
- });
-
- runner.on('fail', function(test, err){
- failures++;
- console.log('not ok %d %s', n, title(test));
- if (err.stack) console.log(err.stack.replace(/^/gm, ' '));
- });
-
- runner.on('end', function(){
- console.log('# tests ' + (passes + failures));
- console.log('# pass ' + passes);
- console.log('# fail ' + failures);
- });
-}
-
-/**
- * Return a TAP-safe title of `test`
- *
- * @param {Object} test
- * @return {String}
- * @api private
- */
-
-function title(test) {
- return test.fullTitle().replace(/#/g, '');
-}
-
-}); // module: reporters/tap.js
-
-require.register("reporters/teamcity.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-
-/**
- * Expose `Teamcity`.
- */
-
-exports = module.exports = Teamcity;
-
-/**
- * Initialize a new `Teamcity` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Teamcity(runner) {
- Base.call(this, runner);
- var stats = this.stats;
-
- runner.on('start', function() {
- console.log("##teamcity[testSuiteStarted name='mocha.suite']");
- });
-
- runner.on('test', function(test) {
- console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']");
- });
-
- runner.on('fail', function(test, err) {
- console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']");
- });
-
- runner.on('pending', function(test) {
- console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']");
- });
-
- runner.on('test end', function(test) {
- console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']");
- });
-
- runner.on('end', function() {
- console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']");
- });
-}
-
-/**
- * Escape the given `str`.
- */
-
-function escape(str) {
- return str
- .replace(/\|/g, "||")
- .replace(/\n/g, "|n")
- .replace(/\r/g, "|r")
- .replace(/\[/g, "|[")
- .replace(/\]/g, "|]")
- .replace(/\u0085/g, "|x")
- .replace(/\u2028/g, "|l")
- .replace(/\u2029/g, "|p")
- .replace(/'/g, "|'");
-}
-
-}); // module: reporters/teamcity.js
-
-require.register("reporters/xunit.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , utils = require('../utils')
- , escape = utils.escape;
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
- , setTimeout = global.setTimeout
- , setInterval = global.setInterval
- , clearTimeout = global.clearTimeout
- , clearInterval = global.clearInterval;
-
-/**
- * Expose `XUnit`.
- */
-
-exports = module.exports = XUnit;
-
-/**
- * Initialize a new `XUnit` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function XUnit(runner) {
- Base.call(this, runner);
- var stats = this.stats
- , tests = []
- , self = this;
-
- runner.on('pass', function(test){
- tests.push(test);
- });
-
- runner.on('fail', function(test){
- tests.push(test);
- });
-
- runner.on('end', function(){
- console.log(tag('testsuite', {
- name: 'Mocha Tests'
- , tests: stats.tests
- , failures: stats.failures
- , errors: stats.failures
- , skipped: stats.tests - stats.failures - stats.passes
- , timestamp: (new Date).toUTCString()
- , time: (stats.duration / 1000) || 0
- }, false));
-
- tests.forEach(test);
- console.log('</testsuite>');
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-XUnit.prototype = new F;
-XUnit.prototype.constructor = XUnit;
-
-
-/**
- * Output tag for the given `test.`
- */
-
-function test(test) {
- var attrs = {
- classname: test.parent.fullTitle()
- , name: test.title
- , time: test.duration / 1000
- };
-
- if ('failed' == test.state) {
- var err = test.err;
- attrs.message = escape(err.message);
- console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack))));
- } else if (test.pending) {
- console.log(tag('testcase', attrs, false, tag('skipped', {}, true)));
- } else {
- console.log(tag('testcase', attrs, true) );
- }
-}
-
-/**
- * HTML tag helper.
- */
-
-function tag(name, attrs, close, content) {
- var end = close ? '/>' : '>'
- , pairs = []
- , tag;
-
- for (var key in attrs) {
- pairs.push(key + '="' + escape(attrs[key]) + '"');
- }
-
- tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
- if (content) tag += content + '</' + name + end;
- return tag;
-}
-
-/**
- * Return cdata escaped CDATA `str`.
- */
-
-function cdata(str) {
- return '<![CDATA[' + escape(str) + ']]>';
-}
-
-}); // module: reporters/xunit.js
-
-require.register("runnable.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var EventEmitter = require('browser/events').EventEmitter
- , debug = require('browser/debug')('mocha:runnable')
- , milliseconds = require('./ms');
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
- , setTimeout = global.setTimeout
- , setInterval = global.setInterval
- , clearTimeout = global.clearTimeout
- , clearInterval = global.clearInterval;
-
-/**
- * Object#toString().
- */
-
-var toString = Object.prototype.toString;
-
-/**
- * Expose `Runnable`.
- */
-
-module.exports = Runnable;
-
-/**
- * Initialize a new `Runnable` with the given `title` and callback `fn`.
- *
- * @param {String} title
- * @param {Function} fn
- * @api private
- */
-
-function Runnable(title, fn) {
- this.title = title;
- this.fn = fn;
- this.async = fn && fn.length;
- this.sync = ! this.async;
- this._timeout = 2000;
- this._slow = 75;
- this.timedOut = false;
-}
-
-/**
- * Inherit from `EventEmitter.prototype`.
- */
-
-function F(){};
-F.prototype = EventEmitter.prototype;
-Runnable.prototype = new F;
-Runnable.prototype.constructor = Runnable;
-
-
-/**
- * Set & get timeout `ms`.
- *
- * @param {Number|String} ms
- * @return {Runnable|Number} ms or self
- * @api private
- */
-
-Runnable.prototype.timeout = function(ms){
- if (0 == arguments.length) return this._timeout;
- if ('string' == typeof ms) ms = milliseconds(ms);
- debug('timeout %d', ms);
- this._timeout = ms;
- if (this.timer) this.resetTimeout();
- return this;
-};
-
-/**
- * Set & get slow `ms`.
- *
- * @param {Number|String} ms
- * @return {Runnable|Number} ms or self
- * @api private
- */
-
-Runnable.prototype.slow = function(ms){
- if (0 === arguments.length) return this._slow;
- if ('string' == typeof ms) ms = milliseconds(ms);
- debug('timeout %d', ms);
- this._slow = ms;
- return this;
-};
-
-/**
- * Return the full title generated by recursively
- * concatenating the parent's full title.
- *
- * @return {String}
- * @api public
- */
-
-Runnable.prototype.fullTitle = function(){
- return this.parent.fullTitle() + ' ' + this.title;
-};
-
-/**
- * Clear the timeout.
- *
- * @api private
- */
-
-Runnable.prototype.clearTimeout = function(){
- clearTimeout(this.timer);
-};
-
-/**
- * Inspect the runnable void of private properties.
- *
- * @return {String}
- * @api private
- */
-
-Runnable.prototype.inspect = function(){
- return JSON.stringify(this, function(key, val){
- if ('_' == key[0]) return;
- if ('parent' == key) return '#<Suite>';
- if ('ctx' == key) return '#<Context>';
- return val;
- }, 2);
-};
-
-/**
- * Reset the timeout.
- *
- * @api private
- */
-
-Runnable.prototype.resetTimeout = function(){
- var self = this;
- var ms = this.timeout() || 1e9;
-
- this.clearTimeout();
- this.timer = setTimeout(function(){
- self.callback(new Error('timeout of ' + ms + 'ms exceeded'));
- self.timedOut = true;
- }, ms);
-};
-
-/**
- * Run the test and invoke `fn(err)`.
- *
- * @param {Function} fn
- * @api private
- */
-
-Runnable.prototype.run = function(fn){
- var self = this
- , ms = this.timeout()
- , start = new Date
- , ctx = this.ctx
- , finished
- , emitted;
-
- if (ctx) ctx.runnable(this);
-
- // timeout
- if (this.async) {
- if (ms) {
- this.timer = setTimeout(function(){
- done(new Error('timeout of ' + ms + 'ms exceeded'));
- self.timedOut = true;
- }, ms);
- }
- }
-
- // called multiple times
- function multiple(err) {
- if (emitted) return;
- emitted = true;
- self.emit('error', err || new Error('done() called multiple times'));
- }
-
- // finished
- function done(err) {
- if (self.timedOut) return;
- if (finished) return multiple(err);
- self.clearTimeout();
- self.duration = new Date - start;
- finished = true;
- fn(err);
- }
-
- // for .resetTimeout()
- this.callback = done;
-
- // async
- if (this.async) {
- try {
- this.fn.call(ctx, function(err){
- if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
- if (null != err) return done(new Error('done() invoked with non-Error: ' + err));
- done();
- });
- } catch (err) {
- done(err);
- }
- return;
- }
-
- if (this.asyncOnly) {
- return done(new Error('--async-only option in use without declaring `done()`'));
- }
-
- // sync
- try {
- if (!this.pending) this.fn.call(ctx);
- this.duration = new Date - start;
- fn();
- } catch (err) {
- fn(err);
- }
-};
-
-}); // module: runnable.js
-
-require.register("runner.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var EventEmitter = require('browser/events').EventEmitter
- , debug = require('browser/debug')('mocha:runner')
- , Test = require('./test')
- , utils = require('./utils')
- , filter = utils.filter
- , keys = utils.keys;
-
-/**
- * Non-enumerable globals.
- */
-
-var globals = [
- 'setTimeout',
- 'clearTimeout',
- 'setInterval',
- 'clearInterval',
- 'XMLHttpRequest',
- 'Date'
-];
-
-/**
- * Expose `Runner`.
- */
-
-module.exports = Runner;
-
-/**
- * Initialize a `Runner` for the given `suite`.
- *
- * Events:
- *
- * - `start` execution started
- * - `end` execution complete
- * - `suite` (suite) test suite execution started
- * - `suite end` (suite) all tests (and sub-suites) have finished
- * - `test` (test) test execution started
- * - `test end` (test) test completed
- * - `hook` (hook) hook execution started
- * - `hook end` (hook) hook complete
- * - `pass` (test) test passed
- * - `fail` (test, err) test failed
- * - `pending` (test) test pending
- *
- * @api public
- */
-
-function Runner(suite) {
- var self = this;
- this._globals = [];
- this.suite = suite;
- this.total = suite.total();
- this.failures = 0;
- this.on('test end', function(test){ self.checkGlobals(test); });
- this.on('hook end', function(hook){ self.checkGlobals(hook); });
- this.grep(/.*/);
- this.globals(this.globalProps().concat(['errno']));
-}
-
-/**
- * Wrapper for setImmediate, process.nextTick, or browser polyfill.
- *
- * @param {Function} fn
- * @api private
- */
-
-Runner.immediately = global.setImmediate || process.nextTick;
-
-/**
- * Inherit from `EventEmitter.prototype`.
- */
-
-function F(){};
-F.prototype = EventEmitter.prototype;
-Runner.prototype = new F;
-Runner.prototype.constructor = Runner;
-
-
-/**
- * Run tests with full titles matching `re`. Updates runner.total
- * with number of tests matched.
- *
- * @param {RegExp} re
- * @param {Boolean} invert
- * @return {Runner} for chaining
- * @api public
- */
-
-Runner.prototype.grep = function(re, invert){
- debug('grep %s', re);
- this._grep = re;
- this._invert = invert;
- this.total = this.grepTotal(this.suite);
- return this;
-};
-
-/**
- * Returns the number of tests matching the grep search for the
- * given suite.
- *
- * @param {Suite} suite
- * @return {Number}
- * @api public
- */
-
-Runner.prototype.grepTotal = function(suite) {
- var self = this;
- var total = 0;
-
- suite.eachTest(function(test){
- var match = self._grep.test(test.fullTitle());
- if (self._invert) match = !match;
- if (match) total++;
- });
-
- return total;
-};
-
-/**
- * Return a list of global properties.
- *
- * @return {Array}
- * @api private
- */
-
-Runner.prototype.globalProps = function() {
- var props = utils.keys(global);
-
- // non-enumerables
- for (var i = 0; i < globals.length; ++i) {
- if (~utils.indexOf(props, globals[i])) continue;
- props.push(globals[i]);
- }
-
- return props;
-};
-
-/**
- * Allow the given `arr` of globals.
- *
- * @param {Array} arr
- * @return {Runner} for chaining
- * @api public
- */
-
-Runner.prototype.globals = function(arr){
- if (0 == arguments.length) return this._globals;
- debug('globals %j', arr);
- utils.forEach(arr, function(arr){
- this._globals.push(arr);
- }, this);
- return this;
-};
-
-/**
- * Check for global variable leaks.
- *
- * @api private
- */
-
-Runner.prototype.checkGlobals = function(test){
- if (this.ignoreLeaks) return;
- var ok = this._globals;
- var globals = this.globalProps();
- var isNode = process.kill;
- var leaks;
-
- // check length - 2 ('errno' and 'location' globals)
- if (isNode && 1 == ok.length - globals.length) return
- else if (2 == ok.length - globals.length) return;
-
- leaks = filterLeaks(ok, globals);
- this._globals = this._globals.concat(leaks);
-
- if (leaks.length > 1) {
- this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
- } else if (leaks.length) {
- this.fail(test, new Error('global leak detected: ' + leaks[0]));
- }
-};
-
-/**
- * Fail the given `test`.
- *
- * @param {Test} test
- * @param {Error} err
- * @api private
- */
-
-Runner.prototype.fail = function(test, err){
- ++this.failures;
- test.state = 'failed';
-
- if ('string' == typeof err) {
- err = new Error('the string "' + err + '" was thrown, throw an Error :)');
- }
-
- this.emit('fail', test, err);
-};
-
-/**
- * Fail the given `hook` with `err`.
- *
- * Hook failures (currently) hard-end due
- * to that fact that a failing hook will
- * surely cause subsequent tests to fail,
- * causing jumbled reporting.
- *
- * @param {Hook} hook
- * @param {Error} err
- * @api private
- */
-
-Runner.prototype.failHook = function(hook, err){
- this.fail(hook, err);
- this.emit('end');
-};
-
-/**
- * Run hook `name` callbacks and then invoke `fn()`.
- *
- * @param {String} name
- * @param {Function} function
- * @api private
- */
-
-Runner.prototype.hook = function(name, fn){
- var suite = this.suite
- , hooks = suite['_' + name]
- , self = this
- , timer;
-
- function next(i) {
- var hook = hooks[i];
- if (!hook) return fn();
- if (self.failures && suite.bail()) return fn();
- self.currentRunnable = hook;
-
- hook.ctx.currentTest = self.test;
-
- self.emit('hook', hook);
-
- hook.on('error', function(err){
- self.failHook(hook, err);
- });
-
- hook.run(function(err){
- hook.removeAllListeners('error');
- var testError = hook.error();
- if (testError) self.fail(self.test, testError);
- if (err) return self.failHook(hook, err);
- self.emit('hook end', hook);
- delete hook.ctx.currentTest;
- next(++i);
- });
- }
-
- Runner.immediately(function(){
- next(0);
- });
-};
-
-/**
- * Run hook `name` for the given array of `suites`
- * in order, and callback `fn(err)`.
- *
- * @param {String} name
- * @param {Array} suites
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.hooks = function(name, suites, fn){
- var self = this
- , orig = this.suite;
-
- function next(suite) {
- self.suite = suite;
-
- if (!suite) {
- self.suite = orig;
- return fn();
- }
-
- self.hook(name, function(err){
- if (err) {
- self.suite = orig;
- return fn(err);
- }
-
- next(suites.pop());
- });
- }
-
- next(suites.pop());
-};
-
-/**
- * Run hooks from the top level down.
- *
- * @param {String} name
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.hookUp = function(name, fn){
- var suites = [this.suite].concat(this.parents()).reverse();
- this.hooks(name, suites, fn);
-};
-
-/**
- * Run hooks from the bottom up.
- *
- * @param {String} name
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.hookDown = function(name, fn){
- var suites = [this.suite].concat(this.parents());
- this.hooks(name, suites, fn);
-};
-
-/**
- * Return an array of parent Suites from
- * closest to furthest.
- *
- * @return {Array}
- * @api private
- */
-
-Runner.prototype.parents = function(){
- var suite = this.suite
- , suites = [];
- while (suite = suite.parent) suites.push(suite);
- return suites;
-};
-
-/**
- * Run the current test and callback `fn(err)`.
- *
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.runTest = function(fn){
- var test = this.test
- , self = this;
-
- if (this.asyncOnly) test.asyncOnly = true;
-
- try {
- test.on('error', function(err){
- self.fail(test, err);
- });
- test.run(fn);
- } catch (err) {
- fn(err);
- }
-};
-
-/**
- * Run tests in the given `suite` and invoke
- * the callback `fn()` when complete.
- *
- * @param {Suite} suite
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.runTests = function(suite, fn){
- var self = this
- , tests = suite.tests.slice()
- , test;
-
- function next(err) {
- // if we bail after first err
- if (self.failures && suite._bail) return fn();
-
- // next test
- test = tests.shift();
-
- // all done
- if (!test) return fn();
-
- // grep
- var match = self._grep.test(test.fullTitle());
- if (self._invert) match = !match;
- if (!match) return next();
-
- // pending
- if (test.pending) {
- self.emit('pending', test);
- self.emit('test end', test);
- return next();
- }
-
- // execute test and hook(s)
- self.emit('test', self.test = test);
- self.hookDown('beforeEach', function(){
- self.currentRunnable = self.test;
- self.runTest(function(err){
- test = self.test;
-
- if (err) {
- self.fail(test, err);
- self.emit('test end', test);
- return self.hookUp('afterEach', next);
- }
-
- test.state = 'passed';
- self.emit('pass', test);
- self.emit('test end', test);
- self.hookUp('afterEach', next);
- });
- });
- }
-
- this.next = next;
- next();
-};
-
-/**
- * Run the given `suite` and invoke the
- * callback `fn()` when complete.
- *
- * @param {Suite} suite
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.runSuite = function(suite, fn){
- var total = this.grepTotal(suite)
- , self = this
- , i = 0;
-
- debug('run suite %s', suite.fullTitle());
-
- if (!total) return fn();
-
- this.emit('suite', this.suite = suite);
-
- function next() {
- var curr = suite.suites[i++];
- if (!curr) return done();
- self.runSuite(curr, next);
- }
-
- function done() {
- self.suite = suite;
- self.hook('afterAll', function(){
- self.emit('suite end', suite);
- fn();
- });
- }
-
- this.hook('beforeAll', function(){
- self.runTests(suite, next);
- });
-};
-
-/**
- * Handle uncaught exceptions.
- *
- * @param {Error} err
- * @api private
- */
-
-Runner.prototype.uncaught = function(err){
- debug('uncaught exception %s', err.message);
- var runnable = this.currentRunnable;
- if (!runnable || 'failed' == runnable.state) return;
- runnable.clearTimeout();
- err.uncaught = true;
- this.fail(runnable, err);
-
- // recover from test
- if ('test' == runnable.type) {
- this.emit('test end', runnable);
- this.hookUp('afterEach', this.next);
- return;
- }
-
- // bail on hooks
- this.emit('end');
-};
-
-/**
- * Run the root suite and invoke `fn(failures)`
- * on completion.
- *
- * @param {Function} fn
- * @return {Runner} for chaining
- * @api public
- */
-
-Runner.prototype.run = function(fn){
- var self = this
- , fn = fn || function(){};
-
- function uncaught(err){
- self.uncaught(err);
- }
-
- debug('start');
-
- // callback
- this.on('end', function(){
- debug('end');
- process.removeListener('uncaughtException', uncaught);
- fn(self.failures);
- });
-
- // run suites
- this.emit('start');
- this.runSuite(this.suite, function(){
- debug('finished running');
- self.emit('end');
- });
-
- // uncaught exception
- process.on('uncaughtException', uncaught);
-
- return this;
-};
-
-/**
- * Filter leaks with the given globals flagged as `ok`.
- *
- * @param {Array} ok
- * @param {Array} globals
- * @return {Array}
- * @api private
- */
-
-function filterLeaks(ok, globals) {
- return filter(globals, function(key){
- // Firefox and Chrome exposes iframes as index inside the window object
- if (/^d+/.test(key)) return false;
- var matched = filter(ok, function(ok){
- if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]);
- // Opera and IE expose global variables for HTML element IDs (issue #243)
- if (/^mocha-/.test(key)) return true;
- return key == ok;
- });
- return matched.length == 0 && (!global.navigator || 'onerror' !== key);
- });
-}
-
-}); // module: runner.js
-
-require.register("suite.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var EventEmitter = require('browser/events').EventEmitter
- , debug = require('browser/debug')('mocha:suite')
- , milliseconds = require('./ms')
- , utils = require('./utils')
- , Hook = require('./hook');
-
-/**
- * Expose `Suite`.
- */
-
-exports = module.exports = Suite;
-
-/**
- * Create a new `Suite` with the given `title`
- * and parent `Suite`. When a suite with the
- * same title is already present, that suite
- * is returned to provide nicer reporter
- * and more flexible meta-testing.
- *
- * @param {Suite} parent
- * @param {String} title
- * @return {Suite}
- * @api public
- */
-
-exports.create = function(parent, title){
- var suite = new Suite(title, parent.ctx);
- suite.parent = parent;
- if (parent.pending) suite.pending = true;
- title = suite.fullTitle();
- parent.addSuite(suite);
- return suite;
-};
-
-/**
- * Initialize a new `Suite` with the given
- * `title` and `ctx`.
- *
- * @param {String} title
- * @param {Context} ctx
- * @api private
- */
-
-function Suite(title, ctx) {
- this.title = title;
- this.ctx = ctx;
- this.suites = [];
- this.tests = [];
- this.pending = false;
- this._beforeEach = [];
- this._beforeAll = [];
- this._afterEach = [];
- this._afterAll = [];
- this.root = !title;
- this._timeout = 2000;
- this._slow = 75;
- this._bail = false;
-}
-
-/**
- * Inherit from `EventEmitter.prototype`.
- */
-
-function F(){};
-F.prototype = EventEmitter.prototype;
-Suite.prototype = new F;
-Suite.prototype.constructor = Suite;
-
-
-/**
- * Return a clone of this `Suite`.
- *
- * @return {Suite}
- * @api private
- */
-
-Suite.prototype.clone = function(){
- var suite = new Suite(this.title);
- debug('clone');
- suite.ctx = this.ctx;
- suite.timeout(this.timeout());
- suite.slow(this.slow());
- suite.bail(this.bail());
- return suite;
-};
-
-/**
- * Set timeout `ms` or short-hand such as "2s".
- *
- * @param {Number|String} ms
- * @return {Suite|Number} for chaining
- * @api private
- */
-
-Suite.prototype.timeout = function(ms){
- if (0 == arguments.length) return this._timeout;
- if ('string' == typeof ms) ms = milliseconds(ms);
- debug('timeout %d', ms);
- this._timeout = parseInt(ms, 10);
- return this;
-};
-
-/**
- * Set slow `ms` or short-hand such as "2s".
- *
- * @param {Number|String} ms
- * @return {Suite|Number} for chaining
- * @api private
- */
-
-Suite.prototype.slow = function(ms){
- if (0 === arguments.length) return this._slow;
- if ('string' == typeof ms) ms = milliseconds(ms);
- debug('slow %d', ms);
- this._slow = ms;
- return this;
-};
-
-/**
- * Sets whether to bail after first error.
- *
- * @parma {Boolean} bail
- * @return {Suite|Number} for chaining
- * @api private
- */
-
-Suite.prototype.bail = function(bail){
- if (0 == arguments.length) return this._bail;
- debug('bail %s', bail);
- this._bail = bail;
- return this;
-};
-
-/**
- * Run `fn(test[, done])` before running tests.
- *
- * @param {Function} fn
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.beforeAll = function(fn){
- if (this.pending) return this;
- var hook = new Hook('"before all" hook', fn);
- hook.parent = this;
- hook.timeout(this.timeout());
- hook.slow(this.slow());
- hook.ctx = this.ctx;
- this._beforeAll.push(hook);
- this.emit('beforeAll', hook);
- return this;
-};
-
-/**
- * Run `fn(test[, done])` after running tests.
- *
- * @param {Function} fn
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.afterAll = function(fn){
- if (this.pending) return this;
- var hook = new Hook('"after all" hook', fn);
- hook.parent = this;
- hook.timeout(this.timeout());
- hook.slow(this.slow());
- hook.ctx = this.ctx;
- this._afterAll.push(hook);
- this.emit('afterAll', hook);
- return this;
-};
-
-/**
- * Run `fn(test[, done])` before each test case.
- *
- * @param {Function} fn
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.beforeEach = function(fn){
- if (this.pending) return this;
- var hook = new Hook('"before each" hook', fn);
- hook.parent = this;
- hook.timeout(this.timeout());
- hook.slow(this.slow());
- hook.ctx = this.ctx;
- this._beforeEach.push(hook);
- this.emit('beforeEach', hook);
- return this;
-};
-
-/**
- * Run `fn(test[, done])` after each test case.
- *
- * @param {Function} fn
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.afterEach = function(fn){
- if (this.pending) return this;
- var hook = new Hook('"after each" hook', fn);
- hook.parent = this;
- hook.timeout(this.timeout());
- hook.slow(this.slow());
- hook.ctx = this.ctx;
- this._afterEach.push(hook);
- this.emit('afterEach', hook);
- return this;
-};
-
-/**
- * Add a test `suite`.
- *
- * @param {Suite} suite
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.addSuite = function(suite){
- suite.parent = this;
- suite.timeout(this.timeout());
- suite.slow(this.slow());
- suite.bail(this.bail());
- this.suites.push(suite);
- this.emit('suite', suite);
- return this;
-};
-
-/**
- * Add a `test` to this suite.
- *
- * @param {Test} test
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.addTest = function(test){
- test.parent = this;
- test.timeout(this.timeout());
- test.slow(this.slow());
- test.ctx = this.ctx;
- this.tests.push(test);
- this.emit('test', test);
- return this;
-};
-
-/**
- * Return the full title generated by recursively
- * concatenating the parent's full title.
- *
- * @return {String}
- * @api public
- */
-
-Suite.prototype.fullTitle = function(){
- if (this.parent) {
- var full = this.parent.fullTitle();
- if (full) return full + ' ' + this.title;
- }
- return this.title;
-};
-
-/**
- * Return the total number of tests.
- *
- * @return {Number}
- * @api public
- */
-
-Suite.prototype.total = function(){
- return utils.reduce(this.suites, function(sum, suite){
- return sum + suite.total();
- }, 0) + this.tests.length;
-};
-
-/**
- * Iterates through each suite recursively to find
- * all tests. Applies a function in the format
- * `fn(test)`.
- *
- * @param {Function} fn
- * @return {Suite}
- * @api private
- */
-
-Suite.prototype.eachTest = function(fn){
- utils.forEach(this.tests, fn);
- utils.forEach(this.suites, function(suite){
- suite.eachTest(fn);
- });
- return this;
-};
-
-}); // module: suite.js
-
-require.register("test.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Runnable = require('./runnable');
-
-/**
- * Expose `Test`.
- */
-
-module.exports = Test;
-
-/**
- * Initialize a new `Test` with the given `title` and callback `fn`.
- *
- * @param {String} title
- * @param {Function} fn
- * @api private
- */
-
-function Test(title, fn) {
- Runnable.call(this, title, fn);
- this.pending = !fn;
- this.type = 'test';
-}
-
-/**
- * Inherit from `Runnable.prototype`.
- */
-
-function F(){};
-F.prototype = Runnable.prototype;
-Test.prototype = new F;
-Test.prototype.constructor = Test;
-
-
-}); // module: test.js
-
-require.register("utils.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var fs = require('browser/fs')
- , path = require('browser/path')
- , join = path.join
- , debug = require('browser/debug')('mocha:watch');
-
-/**
- * Ignored directories.
- */
-
-var ignore = ['node_modules', '.git'];
-
-/**
- * Escape special characters in the given string of html.
- *
- * @param {String} html
- * @return {String}
- * @api private
- */
-
-exports.escape = function(html){
- return String(html)
- .replace(/&/g, '&')
- .replace(/"/g, '"')
- .replace(/</g, '<')
- .replace(/>/g, '>');
-};
-
-/**
- * Array#forEach (<=IE8)
- *
- * @param {Array} array
- * @param {Function} fn
- * @param {Object} scope
- * @api private
- */
-
-exports.forEach = function(arr, fn, scope){
- for (var i = 0, l = arr.length; i < l; i++)
- fn.call(scope, arr[i], i);
-};
-
-/**
- * Array#indexOf (<=IE8)
- *
- * @parma {Array} arr
- * @param {Object} obj to find index of
- * @param {Number} start
- * @api private
- */
-
-exports.indexOf = function(arr, obj, start){
- for (var i = start || 0, l = arr.length; i < l; i++) {
- if (arr[i] === obj)
- return i;
- }
- return -1;
-};
-
-/**
- * Array#reduce (<=IE8)
- *
- * @param {Array} array
- * @param {Function} fn
- * @param {Object} initial value
- * @api private
- */
-
-exports.reduce = function(arr, fn, val){
- var rval = val;
-
- for (var i = 0, l = arr.length; i < l; i++) {
- rval = fn(rval, arr[i], i, arr);
- }
-
- return rval;
-};
-
-/**
- * Array#filter (<=IE8)
- *
- * @param {Array} array
- * @param {Function} fn
- * @api private
- */
-
-exports.filter = function(arr, fn){
- var ret = [];
-
- for (var i = 0, l = arr.length; i < l; i++) {
- var val = arr[i];
- if (fn(val, i, arr)) ret.push(val);
- }
-
- return ret;
-};
-
-/**
- * Object.keys (<=IE8)
- *
- * @param {Object} obj
- * @return {Array} keys
- * @api private
- */
-
-exports.keys = Object.keys || function(obj) {
- var keys = []
- , has = Object.prototype.hasOwnProperty // for `window` on <=IE8
-
- for (var key in obj) {
- if (has.call(obj, key)) {
- keys.push(key);
- }
- }
-
- return keys;
-};
-
-/**
- * Watch the given `files` for changes
- * and invoke `fn(file)` on modification.
- *
- * @param {Array} files
- * @param {Function} fn
- * @api private
- */
-
-exports.watch = function(files, fn){
- var options = { interval: 100 };
- files.forEach(function(file){
- debug('file %s', file);
- fs.watchFile(file, options, function(curr, prev){
- if (prev.mtime < curr.mtime) fn(file);
- });
- });
-};
-
-/**
- * Ignored files.
- */
-
-function ignored(path){
- return !~ignore.indexOf(path);
-}
-
-/**
- * Lookup files in the given `dir`.
- *
- * @return {Array}
- * @api private
- */
-
-exports.files = function(dir, ret){
- ret = ret || [];
-
- fs.readdirSync(dir)
- .filter(ignored)
- .forEach(function(path){
- path = join(dir, path);
- if (fs.statSync(path).isDirectory()) {
- exports.files(path, ret);
- } else if (path.match(/\.(js|coffee)$/)) {
- ret.push(path);
- }
- });
-
- return ret;
-};
-
-/**
- * Compute a slug from the given `str`.
- *
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-exports.slug = function(str){
- return str
- .toLowerCase()
- .replace(/ +/g, '-')
- .replace(/[^-\w]/g, '');
-};
-
-/**
- * Strip the function definition from `str`,
- * and re-indent for pre whitespace.
- */
-
-exports.clean = function(str) {
- str = str
- .replace(/^function *\(.*\) *{/, '')
- .replace(/\s+\}$/, '');
-
- var whitespace = str.match(/^\n?(\s*)/)[1]
- , re = new RegExp('^' + whitespace, 'gm');
-
- str = str.replace(re, '');
-
- return exports.trim(str);
-};
-
-/**
- * Escape regular expression characters in `str`.
- *
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-exports.escapeRegexp = function(str){
- return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
-};
-
-/**
- * Trim the given `str`.
- *
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-exports.trim = function(str){
- return str.replace(/^\s+|\s+$/g, '');
-};
-
-/**
- * Parse the given `qs`.
- *
- * @param {String} qs
- * @return {Object}
- * @api private
- */
-
-exports.parseQuery = function(qs){
- return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
- var i = pair.indexOf('=')
- , key = pair.slice(0, i)
- , val = pair.slice(++i);
-
- obj[key] = decodeURIComponent(val);
- return obj;
- }, {});
-};
-
-/**
- * Highlight the given string of `js`.
- *
- * @param {String} js
- * @return {String}
- * @api private
- */
-
-function highlight(js) {
- return js
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
- .replace(/('.*?')/gm, '<span class="string">$1</span>')
- .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
- .replace(/(\d+)/gm, '<span class="number">$1</span>')
- .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
- .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
-}
-
-/**
- * Highlight the contents of tag `name`.
- *
- * @param {String} name
- * @api private
- */
-
-exports.highlightTags = function(name) {
- var code = document.getElementsByTagName(name);
- for (var i = 0, len = code.length; i < len; ++i) {
- code[i].innerHTML = highlight(code[i].innerHTML);
- }
-};
-
-}); // module: utils.js
-// The global object is "self" in Web Workers.
-global = (function() { return this; })();
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date;
-var setTimeout = global.setTimeout;
-var setInterval = global.setInterval;
-var clearTimeout = global.clearTimeout;
-var clearInterval = global.clearInterval;
-
-/**
- * Node shims.
- *
- * These are meant only to allow
- * mocha.js to run untouched, not
- * to allow running node code in
- * the browser.
- */
-
-var process = {};
-process.exit = function(status){};
-process.stdout = {};
-
-/**
- * Remove uncaughtException listener.
- */
-
-process.removeListener = function(e){
- if ('uncaughtException' == e) {
- global.onerror = function() {};
- }
-};
-
-/**
- * Implements uncaughtException listener.
- */
-
-process.on = function(e, fn){
- if ('uncaughtException' == e) {
- global.onerror = function(err, url, line){
- fn(new Error(err + ' (' + url + ':' + line + ')'));
- };
- }
-};
-
-/**
- * Expose mocha.
- */
-
-var Mocha = global.Mocha = require('mocha'),
- mocha = global.mocha = new Mocha({ reporter: 'html' });
-
-var immediateQueue = []
- , immediateTimeout;
-
-function timeslice() {
- var immediateStart = new Date().getTime();
- while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) {
- immediateQueue.shift()();
- }
- if (immediateQueue.length) {
- immediateTimeout = setTimeout(timeslice, 0);
- } else {
- immediateTimeout = null;
- }
-}
-
-/**
- * High-performance override of Runner.immediately.
- */
-
-Mocha.Runner.immediately = function(callback) {
- immediateQueue.push(callback);
- if (!immediateTimeout) {
- immediateTimeout = setTimeout(timeslice, 0);
- }
-};
-
-/**
- * Override ui to ensure that the ui functions are initialized.
- * Normally this would happen in Mocha.prototype.loadFiles.
- */
-
-mocha.ui = function(ui){
- Mocha.prototype.ui.call(this, ui);
- this.suite.emit('pre-require', global, null, this);
- return this;
-};
-
-/**
- * Setup mocha with the given setting options.
- */
-
-mocha.setup = function(opts){
- if ('string' == typeof opts) opts = { ui: opts };
- for (var opt in opts) this[opt](opts[opt]);
- return this;
-};
-
-/**
- * Run mocha, returning the Runner.
- */
-
-mocha.run = function(fn){
- var options = mocha.options;
- mocha.globals('location');
-
- var query = Mocha.utils.parseQuery(global.location.search || '');
- if (query.grep) mocha.grep(query.grep);
- if (query.invert) mocha.invert();
-
- return Mocha.prototype.run.call(mocha, function(){
- // The DOM Document is not available in Web Workers.
- if (global.document) {
- Mocha.utils.highlightTags('code');
- }
- if (fn) fn();
- });
-};
-
-/**
- * Expose the process shim.
- */
-
-Mocha.process = process;
-})();
\ No newline at end of file
diff --git a/ckan/public-bs2/base/test/vendor/sinon.js b/ckan/public-bs2/base/test/vendor/sinon.js
deleted file mode 100644
--- a/ckan/public-bs2/base/test/vendor/sinon.js
+++ /dev/null
@@ -1,4080 +0,0 @@
-/**
- * Sinon.JS 1.4.0, 2012/07/09
- *
- * @author Christian Johansen ([email protected])
- * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
- *
- * (The BSD License)
- *
- * Copyright (c) 2010-2012, Christian Johansen, [email protected]
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- *
- * * Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * * Neither the name of Christian Johansen nor the names of his contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-"use strict";
-var sinon = (function () {
-var buster = (function (setTimeout, B) {
- var isNode = typeof require == "function" && typeof module == "object";
- var div = typeof document != "undefined" && document.createElement("div");
- var F = function () {};
-
- var buster = {
- bind: function bind(obj, methOrProp) {
- var method = typeof methOrProp == "string" ? obj[methOrProp] : methOrProp;
- var args = Array.prototype.slice.call(arguments, 2);
- return function () {
- var allArgs = args.concat(Array.prototype.slice.call(arguments));
- return method.apply(obj, allArgs);
- };
- },
-
- partial: function partial(fn) {
- var args = [].slice.call(arguments, 1);
- return function () {
- return fn.apply(this, args.concat([].slice.call(arguments)));
- };
- },
-
- create: function create(object) {
- F.prototype = object;
- return new F();
- },
-
- extend: function extend(target) {
- if (!target) { return; }
- for (var i = 1, l = arguments.length, prop; i < l; ++i) {
- for (prop in arguments[i]) {
- target[prop] = arguments[i][prop];
- }
- }
- return target;
- },
-
- nextTick: function nextTick(callback) {
- if (typeof process != "undefined" && process.nextTick) {
- return process.nextTick(callback);
- }
- setTimeout(callback, 0);
- },
-
- functionName: function functionName(func) {
- if (!func) return "";
- if (func.displayName) return func.displayName;
- if (func.name) return func.name;
- var matches = func.toString().match(/function\s+([^\(]+)/m);
- return matches && matches[1] || "";
- },
-
- isNode: function isNode(obj) {
- if (!div) return false;
- try {
- obj.appendChild(div);
- obj.removeChild(div);
- } catch (e) {
- return false;
- }
- return true;
- },
-
- isElement: function isElement(obj) {
- return obj && obj.nodeType === 1 && buster.isNode(obj);
- },
-
- isArray: function isArray(arr) {
- return Object.prototype.toString.call(arr) == "[object Array]";
- },
-
- flatten: function flatten(arr) {
- var result = [], arr = arr || [];
- for (var i = 0, l = arr.length; i < l; ++i) {
- result = result.concat(buster.isArray(arr[i]) ? flatten(arr[i]) : arr[i]);
- }
- return result;
- },
-
- each: function each(arr, callback) {
- for (var i = 0, l = arr.length; i < l; ++i) {
- callback(arr[i]);
- }
- },
-
- map: function map(arr, callback) {
- var results = [];
- for (var i = 0, l = arr.length; i < l; ++i) {
- results.push(callback(arr[i]));
- }
- return results;
- },
-
- parallel: function parallel(fns, callback) {
- function cb(err, res) {
- if (typeof callback == "function") {
- callback(err, res);
- callback = null;
- }
- }
- if (fns.length == 0) { return cb(null, []); }
- var remaining = fns.length, results = [];
- function makeDone(num) {
- return function done(err, result) {
- if (err) { return cb(err); }
- results[num] = result;
- if (--remaining == 0) { cb(null, results); }
- };
- }
- for (var i = 0, l = fns.length; i < l; ++i) {
- fns[i](makeDone(i));
- }
- },
-
- series: function series(fns, callback) {
- function cb(err, res) {
- if (typeof callback == "function") {
- callback(err, res);
- }
- }
- var remaining = fns.slice();
- var results = [];
- function callNext() {
- if (remaining.length == 0) return cb(null, results);
- var promise = remaining.shift()(next);
- if (promise && typeof promise.then == "function") {
- promise.then(buster.partial(next, null), next);
- }
- }
- function next(err, result) {
- if (err) return cb(err);
- results.push(result);
- callNext();
- }
- callNext();
- },
-
- countdown: function countdown(num, done) {
- return function () {
- if (--num == 0) done();
- };
- }
- };
-
- if (typeof process === "object") {
- var crypto = require("crypto");
- var path = require("path");
-
- buster.tmpFile = function (fileName) {
- var hashed = crypto.createHash("sha1");
- hashed.update(fileName);
- var tmpfileName = hashed.digest("hex");
-
- if (process.platform == "win32") {
- return path.join(process.env["TEMP"], tmpfileName);
- } else {
- return path.join("/tmp", tmpfileName);
- }
- };
- }
-
- if (Array.prototype.some) {
- buster.some = function (arr, fn, thisp) {
- return arr.some(fn, thisp);
- };
- } else {
- // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
- buster.some = function (arr, fun, thisp) {
- if (arr == null) { throw new TypeError(); }
- arr = Object(arr);
- var len = arr.length >>> 0;
- if (typeof fun !== "function") { throw new TypeError(); }
-
- for (var i = 0; i < len; i++) {
- if (arr.hasOwnProperty(i) && fun.call(thisp, arr[i], i, arr)) {
- return true;
- }
- }
-
- return false;
- };
- }
-
- if (Array.prototype.filter) {
- buster.filter = function (arr, fn, thisp) {
- return arr.filter(fn, thisp);
- };
- } else {
- // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
- buster.filter = function (fn, thisp) {
- if (this == null) { throw new TypeError(); }
-
- var t = Object(this);
- var len = t.length >>> 0;
- if (typeof fn != "function") { throw new TypeError(); }
-
- var res = [];
- for (var i = 0; i < len; i++) {
- if (i in t) {
- var val = t[i]; // in case fun mutates this
- if (fn.call(thisp, val, i, t)) { res.push(val); }
- }
- }
-
- return res;
- };
- }
-
- if (isNode) {
- module.exports = buster;
- buster.eventEmitter = require("./buster-event-emitter");
- Object.defineProperty(buster, "defineVersionGetter", {
- get: function () {
- return require("./define-version-getter");
- }
- });
- }
-
- return buster.extend(B || {}, buster);
-}(setTimeout, buster));
-if (typeof buster === "undefined") {
- var buster = {};
-}
-
-if (typeof module === "object" && typeof require === "function") {
- buster = require("buster-core");
-}
-
-buster.format = buster.format || {};
-buster.format.excludeConstructors = ["Object", /^.$/];
-buster.format.quoteStrings = true;
-
-buster.format.ascii = (function () {
-
- var hasOwn = Object.prototype.hasOwnProperty;
-
- var specialObjects = [];
- if (typeof global != "undefined") {
- specialObjects.push({ obj: global, value: "[object global]" });
- }
- if (typeof document != "undefined") {
- specialObjects.push({ obj: document, value: "[object HTMLDocument]" });
- }
- if (typeof window != "undefined") {
- specialObjects.push({ obj: window, value: "[object Window]" });
- }
-
- function keys(object) {
- var k = Object.keys && Object.keys(object) || [];
-
- if (k.length == 0) {
- for (var prop in object) {
- if (hasOwn.call(object, prop)) {
- k.push(prop);
- }
- }
- }
-
- return k.sort();
- }
-
- function isCircular(object, objects) {
- if (typeof object != "object") {
- return false;
- }
-
- for (var i = 0, l = objects.length; i < l; ++i) {
- if (objects[i] === object) {
- return true;
- }
- }
-
- return false;
- }
-
- function ascii(object, processed, indent) {
- if (typeof object == "string") {
- var quote = typeof this.quoteStrings != "boolean" || this.quoteStrings;
- return processed || quote ? '"' + object + '"' : object;
- }
-
- if (typeof object == "function" && !(object instanceof RegExp)) {
- return ascii.func(object);
- }
-
- processed = processed || [];
-
- if (isCircular(object, processed)) {
- return "[Circular]";
- }
-
- if (Object.prototype.toString.call(object) == "[object Array]") {
- return ascii.array.call(this, object, processed);
- }
-
- if (!object) {
- return "" + object;
- }
-
- if (buster.isElement(object)) {
- return ascii.element(object);
- }
-
- if (typeof object.toString == "function" &&
- object.toString !== Object.prototype.toString) {
- return object.toString();
- }
-
- for (var i = 0, l = specialObjects.length; i < l; i++) {
- if (object === specialObjects[i].obj) {
- return specialObjects[i].value;
- }
- }
-
- return ascii.object.call(this, object, processed, indent);
- }
-
- ascii.func = function (func) {
- return "function " + buster.functionName(func) + "() {}";
- };
-
- ascii.array = function (array, processed) {
- processed = processed || [];
- processed.push(array);
- var pieces = [];
-
- for (var i = 0, l = array.length; i < l; ++i) {
- pieces.push(ascii.call(this, array[i], processed));
- }
-
- return "[" + pieces.join(", ") + "]";
- };
-
- ascii.object = function (object, processed, indent) {
- processed = processed || [];
- processed.push(object);
- indent = indent || 0;
- var pieces = [], properties = keys(object), prop, str, obj;
- var is = "";
- var length = 3;
-
- for (var i = 0, l = indent; i < l; ++i) {
- is += " ";
- }
-
- for (i = 0, l = properties.length; i < l; ++i) {
- prop = properties[i];
- obj = object[prop];
-
- if (isCircular(obj, processed)) {
- str = "[Circular]";
- } else {
- str = ascii.call(this, obj, processed, indent + 2);
- }
-
- str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str;
- length += str.length;
- pieces.push(str);
- }
-
- var cons = ascii.constructorName.call(this, object);
- var prefix = cons ? "[" + cons + "] " : ""
-
- return (length + indent) > 80 ?
- prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + is + "}" :
- prefix + "{ " + pieces.join(", ") + " }";
- };
-
- ascii.element = function (element) {
- var tagName = element.tagName.toLowerCase();
- var attrs = element.attributes, attribute, pairs = [], attrName;
-
- for (var i = 0, l = attrs.length; i < l; ++i) {
- attribute = attrs.item(i);
- attrName = attribute.nodeName.toLowerCase().replace("html:", "");
-
- if (attrName == "contenteditable" && attribute.nodeValue == "inherit") {
- continue;
- }
-
- if (!!attribute.nodeValue) {
- pairs.push(attrName + "=\"" + attribute.nodeValue + "\"");
- }
- }
-
- var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
- var content = element.innerHTML;
-
- if (content.length > 20) {
- content = content.substr(0, 20) + "[...]";
- }
-
- var res = formatted + pairs.join(" ") + ">" + content + "</" + tagName + ">";
-
- return res.replace(/ contentEditable="inherit"/, "");
- };
-
- ascii.constructorName = function (object) {
- var name = buster.functionName(object && object.constructor);
- var excludes = this.excludeConstructors || buster.format.excludeConstructors || [];
-
- for (var i = 0, l = excludes.length; i < l; ++i) {
- if (typeof excludes[i] == "string" && excludes[i] == name) {
- return "";
- } else if (excludes[i].test && excludes[i].test(name)) {
- return "";
- }
- }
-
- return name;
- };
-
- return ascii;
-}());
-
-if (typeof module != "undefined") {
- module.exports = buster.format;
-}
-/*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/
-/*global module, require, __dirname, document*/
-/**
- * Sinon core utilities. For internal use only.
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-var sinon = (function (buster) {
- var div = typeof document != "undefined" && document.createElement("div");
- var hasOwn = Object.prototype.hasOwnProperty;
-
- function isDOMNode(obj) {
- var success = false;
-
- try {
- obj.appendChild(div);
- success = div.parentNode == obj;
- } catch (e) {
- return false;
- } finally {
- try {
- obj.removeChild(div);
- } catch (e) {
- // Remove failed, not much we can do about that
- }
- }
-
- return success;
- }
-
- function isElement(obj) {
- return div && obj && obj.nodeType === 1 && isDOMNode(obj);
- }
-
- function isFunction(obj) {
- return !!(obj && obj.constructor && obj.call && obj.apply);
- }
-
- function mirrorProperties(target, source) {
- for (var prop in source) {
- if (!hasOwn.call(target, prop)) {
- target[prop] = source[prop];
- }
- }
- }
-
- var sinon = {
- wrapMethod: function wrapMethod(object, property, method) {
- if (!object) {
- throw new TypeError("Should wrap property of object");
- }
-
- if (typeof method != "function") {
- throw new TypeError("Method wrapper should be function");
- }
-
- var wrappedMethod = object[property];
-
- if (!isFunction(wrappedMethod)) {
- throw new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " +
- property + " as function");
- }
-
- if (wrappedMethod.restore && wrappedMethod.restore.sinon) {
- throw new TypeError("Attempted to wrap " + property + " which is already wrapped");
- }
-
- if (wrappedMethod.calledBefore) {
- var verb = !!wrappedMethod.returns ? "stubbed" : "spied on";
- throw new TypeError("Attempted to wrap " + property + " which is already " + verb);
- }
-
- // IE 8 does not support hasOwnProperty on the window object.
- var owned = hasOwn.call(object, property);
- object[property] = method;
- method.displayName = property;
-
- method.restore = function () {
- // For prototype properties try to reset by delete first.
- // If this fails (ex: localStorage on mobile safari) then force a reset
- // via direct assignment.
- if (!owned) {
- delete object[property];
- }
- if (object[property] === method) {
- object[property] = wrappedMethod;
- }
- };
-
- method.restore.sinon = true;
- mirrorProperties(method, wrappedMethod);
-
- return method;
- },
-
- extend: function extend(target) {
- for (var i = 1, l = arguments.length; i < l; i += 1) {
- for (var prop in arguments[i]) {
- if (arguments[i].hasOwnProperty(prop)) {
- target[prop] = arguments[i][prop];
- }
-
- // DONT ENUM bug, only care about toString
- if (arguments[i].hasOwnProperty("toString") &&
- arguments[i].toString != target.toString) {
- target.toString = arguments[i].toString;
- }
- }
- }
-
- return target;
- },
-
- create: function create(proto) {
- var F = function () {};
- F.prototype = proto;
- return new F();
- },
-
- deepEqual: function deepEqual(a, b) {
- if (sinon.match && sinon.match.isMatcher(a)) {
- return a.test(b);
- }
- if (typeof a != "object" || typeof b != "object") {
- return a === b;
- }
-
- if (isElement(a) || isElement(b)) {
- return a === b;
- }
-
- if (a === b) {
- return true;
- }
-
- var aString = Object.prototype.toString.call(a);
- if (aString != Object.prototype.toString.call(b)) {
- return false;
- }
-
- if (aString == "[object Array]") {
- if (a.length !== b.length) {
- return false;
- }
-
- for (var i = 0, l = a.length; i < l; i += 1) {
- if (!deepEqual(a[i], b[i])) {
- return false;
- }
- }
-
- return true;
- }
-
- var prop, aLength = 0, bLength = 0;
-
- for (prop in a) {
- aLength += 1;
-
- if (!deepEqual(a[prop], b[prop])) {
- return false;
- }
- }
-
- for (prop in b) {
- bLength += 1;
- }
-
- if (aLength != bLength) {
- return false;
- }
-
- return true;
- },
-
- functionName: function functionName(func) {
- var name = func.displayName || func.name;
-
- // Use function decomposition as a last resort to get function
- // name. Does not rely on function decomposition to work - if it
- // doesn't debugging will be slightly less informative
- // (i.e. toString will say 'spy' rather than 'myFunc').
- if (!name) {
- var matches = func.toString().match(/function ([^\s\(]+)/);
- name = matches && matches[1];
- }
-
- return name;
- },
-
- functionToString: function toString() {
- if (this.getCall && this.callCount) {
- var thisValue, prop, i = this.callCount;
-
- while (i--) {
- thisValue = this.getCall(i).thisValue;
-
- for (prop in thisValue) {
- if (thisValue[prop] === this) {
- return prop;
- }
- }
- }
- }
-
- return this.displayName || "sinon fake";
- },
-
- getConfig: function (custom) {
- var config = {};
- custom = custom || {};
- var defaults = sinon.defaultConfig;
-
- for (var prop in defaults) {
- if (defaults.hasOwnProperty(prop)) {
- config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop];
- }
- }
-
- return config;
- },
-
- format: function (val) {
- return "" + val;
- },
-
- defaultConfig: {
- injectIntoThis: true,
- injectInto: null,
- properties: ["spy", "stub", "mock", "clock", "server", "requests"],
- useFakeTimers: true,
- useFakeServer: true
- },
-
- timesInWords: function timesInWords(count) {
- return count == 1 && "once" ||
- count == 2 && "twice" ||
- count == 3 && "thrice" ||
- (count || 0) + " times";
- },
-
- calledInOrder: function (spies) {
- for (var i = 1, l = spies.length; i < l; i++) {
- if (!spies[i - 1].calledBefore(spies[i])) {
- return false;
- }
- }
-
- return true;
- },
-
- orderByFirstCall: function (spies) {
- return spies.sort(function (a, b) {
- // uuid, won't ever be equal
- var aCall = a.getCall(0);
- var bCall = b.getCall(0);
- var aId = aCall && aCall.callId || -1;
- var bId = bCall && bCall.callId || -1;
-
- return aId < bId ? -1 : 1;
- });
- },
-
- log: function () {},
-
- logError: function (label, err) {
- var msg = label + " threw exception: "
- sinon.log(msg + "[" + err.name + "] " + err.message);
- if (err.stack) { sinon.log(err.stack); }
-
- setTimeout(function () {
- err.message = msg + err.message;
- throw err;
- }, 0);
- },
-
- typeOf: function (value) {
- if (value === null) {
- return "null";
- }
- var string = Object.prototype.toString.call(value);
- return string.substring(8, string.length - 1).toLowerCase();
- }
- };
-
- var isNode = typeof module == "object" && typeof require == "function";
-
- if (isNode) {
- try {
- buster = { format: require("buster-format") };
- } catch (e) {}
- module.exports = sinon;
- module.exports.spy = require("./sinon/spy");
- module.exports.stub = require("./sinon/stub");
- module.exports.mock = require("./sinon/mock");
- module.exports.collection = require("./sinon/collection");
- module.exports.assert = require("./sinon/assert");
- module.exports.sandbox = require("./sinon/sandbox");
- module.exports.test = require("./sinon/test");
- module.exports.testCase = require("./sinon/test_case");
- module.exports.assert = require("./sinon/assert");
- module.exports.match = require("./sinon/match");
- }
-
- if (buster) {
- var formatter = sinon.create(buster.format);
- formatter.quoteStrings = false;
- sinon.format = function () {
- return formatter.ascii.apply(formatter, arguments);
- };
- } else if (isNode) {
- try {
- var util = require("util");
- sinon.format = function (value) {
- return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value;
- };
- } catch (e) {
- /* Node, but no util module - would be very old, but better safe than
- sorry */
- }
- }
-
- return sinon;
-}(typeof buster == "object" && buster));
-
-/* @depend ../sinon.js */
-/*jslint eqeqeq: false, onevar: false, plusplus: false*/
-/*global module, require, sinon*/
-/**
- * Match functions
- *
- * @author Maximilian Antoni ([email protected])
- * @license BSD
- *
- * Copyright (c) 2012 Maximilian Antoni
- */
-
-(function (sinon) {
- var commonJSModule = typeof module == "object" && typeof require == "function";
-
- if (!sinon && commonJSModule) {
- sinon = require("../sinon");
- }
-
- if (!sinon) {
- return;
- }
-
- function assertType(value, type, name) {
- var actual = sinon.typeOf(value);
- if (actual !== type) {
- throw new TypeError("Expected type of " + name + " to be " +
- type + ", but was " + actual);
- }
- }
-
- var matcher = {
- toString: function () {
- return this.message;
- }
- };
-
- function isMatcher(object) {
- return matcher.isPrototypeOf(object);
- }
-
- function matchObject(expectation, actual) {
- if (actual === null || actual === undefined) {
- return false;
- }
- for (var key in expectation) {
- if (expectation.hasOwnProperty(key)) {
- var exp = expectation[key];
- var act = actual[key];
- if (match.isMatcher(exp)) {
- if (!exp.test(act)) {
- return false;
- }
- } else if (sinon.typeOf(exp) === "object") {
- if (!matchObject(exp, act)) {
- return false;
- }
- } else if (exp !== act) {
- return false;
- }
- }
- }
- return true;
- }
-
- matcher.or = function (m2) {
- if (!isMatcher(m2)) {
- throw new TypeError("Matcher expected");
- }
- var m1 = this;
- var or = sinon.create(matcher);
- or.test = function (actual) {
- return m1.test(actual) || m2.test(actual);
- };
- or.message = m1.message + ".or(" + m2.message + ")";
- return or;
- };
-
- matcher.and = function (m2) {
- if (!isMatcher(m2)) {
- throw new TypeError("Matcher expected");
- }
- var m1 = this;
- var and = sinon.create(matcher);
- and.test = function (actual) {
- return m1.test(actual) && m2.test(actual);
- };
- and.message = m1.message + ".and(" + m2.message + ")";
- return and;
- };
-
- var match = function (expectation, message) {
- var m = sinon.create(matcher);
- var type = sinon.typeOf(expectation);
- switch (type) {
- case "object":
- if (typeof expectation.test === "function") {
- m.test = function (actual) {
- return expectation.test(actual) === true;
- };
- m.message = "match(" + sinon.functionName(expectation.test) + ")";
- return m;
- }
- var str = [];
- for (var key in expectation) {
- if (expectation.hasOwnProperty(key)) {
- str.push(key + ": " + expectation[key]);
- }
- }
- m.test = function (actual) {
- return matchObject(expectation, actual);
- };
- m.message = "match(" + str.join(", ") + ")";
- break;
- case "number":
- m.test = function (actual) {
- return expectation == actual;
- };
- break;
- case "string":
- m.test = function (actual) {
- if (typeof actual !== "string") {
- return false;
- }
- return actual.indexOf(expectation) !== -1;
- };
- m.message = "match(\"" + expectation + "\")";
- break;
- case "regexp":
- m.test = function (actual) {
- if (typeof actual !== "string") {
- return false;
- }
- return expectation.test(actual);
- };
- break;
- case "function":
- m.test = expectation;
- if (message) {
- m.message = message;
- } else {
- m.message = "match(" + sinon.functionName(expectation) + ")";
- }
- break;
- default:
- m.test = function (actual) {
- return sinon.deepEqual(expectation, actual);
- };
- }
- if (!m.message) {
- m.message = "match(" + expectation + ")";
- }
- return m;
- };
-
- match.isMatcher = isMatcher;
-
- match.any = match(function () {
- return true;
- }, "any");
-
- match.defined = match(function (actual) {
- return actual !== null && actual !== undefined;
- }, "defined");
-
- match.truthy = match(function (actual) {
- return !!actual;
- }, "truthy");
-
- match.falsy = match(function (actual) {
- return !actual;
- }, "falsy");
-
- match.same = function (expectation) {
- return match(function (actual) {
- return expectation === actual;
- }, "same(" + expectation + ")");
- };
-
- match.typeOf = function (type) {
- assertType(type, "string", "type");
- return match(function (actual) {
- return sinon.typeOf(actual) === type;
- }, "typeOf(\"" + type + "\")");
- };
-
- match.instanceOf = function (type) {
- assertType(type, "function", "type");
- return match(function (actual) {
- return actual instanceof type;
- }, "instanceOf(" + sinon.functionName(type) + ")");
- };
-
- function createPropertyMatcher(propertyTest, messagePrefix) {
- return function (property, value) {
- assertType(property, "string", "property");
- var onlyProperty = arguments.length === 1;
- var message = messagePrefix + "(\"" + property + "\"";
- if (!onlyProperty) {
- message += ", " + value;
- }
- message += ")";
- return match(function (actual) {
- if (actual === undefined || actual === null ||
- !propertyTest(actual, property)) {
- return false;
- }
- return onlyProperty || sinon.deepEqual(value, actual[property]);
- }, message);
- };
- }
-
- match.has = createPropertyMatcher(function (actual, property) {
- if (typeof actual === "object") {
- return property in actual;
- }
- return actual[property] !== undefined;
- }, "has");
-
- match.hasOwn = createPropertyMatcher(function (actual, property) {
- return actual.hasOwnProperty(property);
- }, "hasOwn");
-
- match.bool = match.typeOf("boolean");
- match.number = match.typeOf("number");
- match.string = match.typeOf("string");
- match.object = match.typeOf("object");
- match.func = match.typeOf("function");
- match.array = match.typeOf("array");
- match.regexp = match.typeOf("regexp");
- match.date = match.typeOf("date");
-
- if (commonJSModule) {
- module.exports = match;
- } else {
- sinon.match = match;
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend ../sinon.js
- * @depend match.js
- */
-/*jslint eqeqeq: false, onevar: false, plusplus: false*/
-/*global module, require, sinon*/
-/**
- * Spy functions
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-(function (sinon) {
- var commonJSModule = typeof module == "object" && typeof require == "function";
- var spyCall;
- var callId = 0;
- var push = [].push;
- var slice = Array.prototype.slice;
-
- if (!sinon && commonJSModule) {
- sinon = require("../sinon");
- }
-
- if (!sinon) {
- return;
- }
-
- function spy(object, property) {
- if (!property && typeof object == "function") {
- return spy.create(object);
- }
-
- if (!object && !property) {
- return spy.create(function () {});
- }
-
- var method = object[property];
- return sinon.wrapMethod(object, property, spy.create(method));
- }
-
- sinon.extend(spy, (function () {
-
- function delegateToCalls(api, method, matchAny, actual, notCalled) {
- api[method] = function () {
- if (!this.called) {
- if (notCalled) {
- return notCalled.apply(this, arguments);
- }
- return false;
- }
-
- var currentCall;
- var matches = 0;
-
- for (var i = 0, l = this.callCount; i < l; i += 1) {
- currentCall = this.getCall(i);
-
- if (currentCall[actual || method].apply(currentCall, arguments)) {
- matches += 1;
-
- if (matchAny) {
- return true;
- }
- }
- }
-
- return matches === this.callCount;
- };
- }
-
- function matchingFake(fakes, args, strict) {
- if (!fakes) {
- return;
- }
-
- var alen = args.length;
-
- for (var i = 0, l = fakes.length; i < l; i++) {
- if (fakes[i].matches(args, strict)) {
- return fakes[i];
- }
- }
- }
-
- function incrementCallCount() {
- this.called = true;
- this.callCount += 1;
- this.notCalled = false;
- this.calledOnce = this.callCount == 1;
- this.calledTwice = this.callCount == 2;
- this.calledThrice = this.callCount == 3;
- }
-
- function createCallProperties() {
- this.firstCall = this.getCall(0);
- this.secondCall = this.getCall(1);
- this.thirdCall = this.getCall(2);
- this.lastCall = this.getCall(this.callCount - 1);
- }
-
- var uuid = 0;
-
- // Public API
- var spyApi = {
- reset: function () {
- this.called = false;
- this.notCalled = true;
- this.calledOnce = false;
- this.calledTwice = false;
- this.calledThrice = false;
- this.callCount = 0;
- this.firstCall = null;
- this.secondCall = null;
- this.thirdCall = null;
- this.lastCall = null;
- this.args = [];
- this.returnValues = [];
- this.thisValues = [];
- this.exceptions = [];
- this.callIds = [];
- if (this.fakes) {
- for (var i = 0; i < this.fakes.length; i++) {
- this.fakes[i].reset();
- }
- }
- },
-
- create: function create(func) {
- var name;
-
- if (typeof func != "function") {
- func = function () {};
- } else {
- name = sinon.functionName(func);
- }
-
- function proxy() {
- return proxy.invoke(func, this, slice.call(arguments));
- }
-
- sinon.extend(proxy, spy);
- delete proxy.create;
- sinon.extend(proxy, func);
-
- proxy.reset();
- proxy.prototype = func.prototype;
- proxy.displayName = name || "spy";
- proxy.toString = sinon.functionToString;
- proxy._create = sinon.spy.create;
- proxy.id = "spy#" + uuid++;
-
- return proxy;
- },
-
- invoke: function invoke(func, thisValue, args) {
- var matching = matchingFake(this.fakes, args);
- var exception, returnValue;
-
- incrementCallCount.call(this);
- push.call(this.thisValues, thisValue);
- push.call(this.args, args);
- push.call(this.callIds, callId++);
-
- try {
- if (matching) {
- returnValue = matching.invoke(func, thisValue, args);
- } else {
- returnValue = (this.func || func).apply(thisValue, args);
- }
- } catch (e) {
- push.call(this.returnValues, undefined);
- exception = e;
- throw e;
- } finally {
- push.call(this.exceptions, exception);
- }
-
- push.call(this.returnValues, returnValue);
-
- createCallProperties.call(this);
-
- return returnValue;
- },
-
- getCall: function getCall(i) {
- if (i < 0 || i >= this.callCount) {
- return null;
- }
-
- return spyCall.create(this, this.thisValues[i], this.args[i],
- this.returnValues[i], this.exceptions[i],
- this.callIds[i]);
- },
-
- calledBefore: function calledBefore(spyFn) {
- if (!this.called) {
- return false;
- }
-
- if (!spyFn.called) {
- return true;
- }
-
- return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1];
- },
-
- calledAfter: function calledAfter(spyFn) {
- if (!this.called || !spyFn.called) {
- return false;
- }
-
- return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1];
- },
-
- withArgs: function () {
- var args = slice.call(arguments);
-
- if (this.fakes) {
- var match = matchingFake(this.fakes, args, true);
-
- if (match) {
- return match;
- }
- } else {
- this.fakes = [];
- }
-
- var original = this;
- var fake = this._create();
- fake.matchingAguments = args;
- push.call(this.fakes, fake);
-
- fake.withArgs = function () {
- return original.withArgs.apply(original, arguments);
- };
-
- for (var i = 0; i < this.args.length; i++) {
- if (fake.matches(this.args[i])) {
- incrementCallCount.call(fake);
- push.call(fake.thisValues, this.thisValues[i]);
- push.call(fake.args, this.args[i]);
- push.call(fake.returnValues, this.returnValues[i]);
- push.call(fake.exceptions, this.exceptions[i]);
- push.call(fake.callIds, this.callIds[i]);
- }
- }
- createCallProperties.call(fake);
-
- return fake;
- },
-
- matches: function (args, strict) {
- var margs = this.matchingAguments;
-
- if (margs.length <= args.length &&
- sinon.deepEqual(margs, args.slice(0, margs.length))) {
- return !strict || margs.length == args.length;
- }
- },
-
- printf: function (format) {
- var spy = this;
- var args = slice.call(arguments, 1);
- var formatter;
-
- return (format || "").replace(/%(.)/g, function (match, specifyer) {
- formatter = spyApi.formatters[specifyer];
-
- if (typeof formatter == "function") {
- return formatter.call(null, spy, args);
- } else if (!isNaN(parseInt(specifyer), 10)) {
- return sinon.format(args[specifyer - 1]);
- }
-
- return "%" + specifyer;
- });
- }
- };
-
- delegateToCalls(spyApi, "calledOn", true);
- delegateToCalls(spyApi, "alwaysCalledOn", false, "calledOn");
- delegateToCalls(spyApi, "calledWith", true);
- delegateToCalls(spyApi, "calledWithMatch", true);
- delegateToCalls(spyApi, "alwaysCalledWith", false, "calledWith");
- delegateToCalls(spyApi, "alwaysCalledWithMatch", false, "calledWithMatch");
- delegateToCalls(spyApi, "calledWithExactly", true);
- delegateToCalls(spyApi, "alwaysCalledWithExactly", false, "calledWithExactly");
- delegateToCalls(spyApi, "neverCalledWith", false, "notCalledWith",
- function () { return true; });
- delegateToCalls(spyApi, "neverCalledWithMatch", false, "notCalledWithMatch",
- function () { return true; });
- delegateToCalls(spyApi, "threw", true);
- delegateToCalls(spyApi, "alwaysThrew", false, "threw");
- delegateToCalls(spyApi, "returned", true);
- delegateToCalls(spyApi, "alwaysReturned", false, "returned");
- delegateToCalls(spyApi, "calledWithNew", true);
- delegateToCalls(spyApi, "alwaysCalledWithNew", false, "calledWithNew");
- delegateToCalls(spyApi, "callArg", false, "callArgWith", function () {
- throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
- });
- spyApi.callArgWith = spyApi.callArg;
- delegateToCalls(spyApi, "yield", false, "yield", function () {
- throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
- });
- // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
- spyApi.invokeCallback = spyApi.yield;
- delegateToCalls(spyApi, "yieldTo", false, "yieldTo", function (property) {
- throw new Error(this.toString() + " cannot yield to '" + property +
- "' since it was not yet invoked.");
- });
-
- spyApi.formatters = {
- "c": function (spy) {
- return sinon.timesInWords(spy.callCount);
- },
-
- "n": function (spy) {
- return spy.toString();
- },
-
- "C": function (spy) {
- var calls = [];
-
- for (var i = 0, l = spy.callCount; i < l; ++i) {
- push.call(calls, " " + spy.getCall(i).toString());
- }
-
- return calls.length > 0 ? "\n" + calls.join("\n") : "";
- },
-
- "t": function (spy) {
- var objects = [];
-
- for (var i = 0, l = spy.callCount; i < l; ++i) {
- push.call(objects, sinon.format(spy.thisValues[i]));
- }
-
- return objects.join(", ");
- },
-
- "*": function (spy, args) {
- var formatted = [];
-
- for (var i = 0, l = args.length; i < l; ++i) {
- push.call(formatted, sinon.format(args[i]));
- }
-
- return formatted.join(", ");
- }
- };
-
- return spyApi;
- }()));
-
- spyCall = (function () {
-
- function throwYieldError(proxy, text, args) {
- var msg = sinon.functionName(proxy) + text;
- if (args.length) {
- msg += " Received [" + slice.call(args).join(", ") + "]";
- }
- throw new Error(msg);
- }
-
- return {
- create: function create(spy, thisValue, args, returnValue, exception, id) {
- var proxyCall = sinon.create(spyCall);
- delete proxyCall.create;
- proxyCall.proxy = spy;
- proxyCall.thisValue = thisValue;
- proxyCall.args = args;
- proxyCall.returnValue = returnValue;
- proxyCall.exception = exception;
- proxyCall.callId = typeof id == "number" && id || callId++;
-
- return proxyCall;
- },
-
- calledOn: function calledOn(thisValue) {
- return this.thisValue === thisValue;
- },
-
- calledWith: function calledWith() {
- for (var i = 0, l = arguments.length; i < l; i += 1) {
- if (!sinon.deepEqual(arguments[i], this.args[i])) {
- return false;
- }
- }
-
- return true;
- },
-
- calledWithMatch: function calledWithMatch() {
- for (var i = 0, l = arguments.length; i < l; i += 1) {
- var actual = this.args[i];
- var expectation = arguments[i];
- if (!sinon.match || !sinon.match(expectation).test(actual)) {
- return false;
- }
- }
- return true;
- },
-
- calledWithExactly: function calledWithExactly() {
- return arguments.length == this.args.length &&
- this.calledWith.apply(this, arguments);
- },
-
- notCalledWith: function notCalledWith() {
- return !this.calledWith.apply(this, arguments);
- },
-
- notCalledWithMatch: function notCalledWithMatch() {
- return !this.calledWithMatch.apply(this, arguments);
- },
-
- returned: function returned(value) {
- return sinon.deepEqual(value, this.returnValue);
- },
-
- threw: function threw(error) {
- if (typeof error == "undefined" || !this.exception) {
- return !!this.exception;
- }
-
- if (typeof error == "string") {
- return this.exception.name == error;
- }
-
- return this.exception === error;
- },
-
- calledWithNew: function calledWithNew(thisValue) {
- return this.thisValue instanceof this.proxy;
- },
-
- calledBefore: function (other) {
- return this.callId < other.callId;
- },
-
- calledAfter: function (other) {
- return this.callId > other.callId;
- },
-
- callArg: function (pos) {
- this.args[pos]();
- },
-
- callArgWith: function (pos) {
- var args = slice.call(arguments, 1);
- this.args[pos].apply(null, args);
- },
-
- "yield": function () {
- var args = this.args;
- for (var i = 0, l = args.length; i < l; ++i) {
- if (typeof args[i] === "function") {
- args[i].apply(null, slice.call(arguments));
- return;
- }
- }
- throwYieldError(this.proxy, " cannot yield since no callback was passed.", args);
- },
-
- yieldTo: function (prop) {
- var args = this.args;
- for (var i = 0, l = args.length; i < l; ++i) {
- if (args[i] && typeof args[i][prop] === "function") {
- args[i][prop].apply(null, slice.call(arguments, 1));
- return;
- }
- }
- throwYieldError(this.proxy, " cannot yield to '" + prop +
- "' since no callback was passed.", args);
- },
-
- toString: function () {
- var callStr = this.proxy.toString() + "(";
- var args = [];
-
- for (var i = 0, l = this.args.length; i < l; ++i) {
- push.call(args, sinon.format(this.args[i]));
- }
-
- callStr = callStr + args.join(", ") + ")";
-
- if (typeof this.returnValue != "undefined") {
- callStr += " => " + sinon.format(this.returnValue);
- }
-
- if (this.exception) {
- callStr += " !" + this.exception.name;
-
- if (this.exception.message) {
- callStr += "(" + this.exception.message + ")";
- }
- }
-
- return callStr;
- }
- };
- }());
-
- spy.spyCall = spyCall;
-
- // This steps outside the module sandbox and will be removed
- sinon.spyCall = spyCall;
-
- if (commonJSModule) {
- module.exports = spy;
- } else {
- sinon.spy = spy;
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend ../sinon.js
- * @depend spy.js
- */
-/*jslint eqeqeq: false, onevar: false*/
-/*global module, require, sinon*/
-/**
- * Stub functions
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-(function (sinon) {
- var commonJSModule = typeof module == "object" && typeof require == "function";
-
- if (!sinon && commonJSModule) {
- sinon = require("../sinon");
- }
-
- if (!sinon) {
- return;
- }
-
- function stub(object, property, func) {
- if (!!func && typeof func != "function") {
- throw new TypeError("Custom stub should be function");
- }
-
- var wrapper;
-
- if (func) {
- wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func;
- } else {
- wrapper = stub.create();
- }
-
- if (!object && !property) {
- return sinon.stub.create();
- }
-
- if (!property && !!object && typeof object == "object") {
- for (var prop in object) {
- if (typeof object[prop] === "function") {
- stub(object, prop);
- }
- }
-
- return object;
- }
-
- return sinon.wrapMethod(object, property, wrapper);
- }
-
- function getCallback(stub, args) {
- if (stub.callArgAt < 0) {
- for (var i = 0, l = args.length; i < l; ++i) {
- if (!stub.callArgProp && typeof args[i] == "function") {
- return args[i];
- }
-
- if (stub.callArgProp && args[i] &&
- typeof args[i][stub.callArgProp] == "function") {
- return args[i][stub.callArgProp];
- }
- }
-
- return null;
- }
-
- return args[stub.callArgAt];
- }
-
- var join = Array.prototype.join;
-
- function getCallbackError(stub, func, args) {
- if (stub.callArgAt < 0) {
- var msg;
-
- if (stub.callArgProp) {
- msg = sinon.functionName(stub) +
- " expected to yield to '" + stub.callArgProp +
- "', but no object with such a property was passed."
- } else {
- msg = sinon.functionName(stub) +
- " expected to yield, but no callback was passed."
- }
-
- if (args.length > 0) {
- msg += " Received [" + join.call(args, ", ") + "]";
- }
-
- return msg;
- }
-
- return "argument at index " + stub.callArgAt + " is not a function: " + func;
- }
-
- var nextTick = (function () {
- if (typeof process === "object" && typeof process.nextTick === "function") {
- return process.nextTick;
- } else if (typeof msSetImmediate === "function") {
- return msSetImmediate.bind(window);
- } else if (typeof setImmediate === "function") {
- return setImmediate;
- } else {
- return function (callback) {
- setTimeout(callback, 0);
- };
- }
- })();
-
- function callCallback(stub, args) {
- if (typeof stub.callArgAt == "number") {
- var func = getCallback(stub, args);
-
- if (typeof func != "function") {
- throw new TypeError(getCallbackError(stub, func, args));
- }
-
- if (stub.callbackAsync) {
- nextTick(function() {
- func.apply(stub.callbackContext, stub.callbackArguments);
- });
- } else {
- func.apply(stub.callbackContext, stub.callbackArguments);
- }
- }
- }
-
- var uuid = 0;
-
- sinon.extend(stub, (function () {
- var slice = Array.prototype.slice, proto;
-
- function throwsException(error, message) {
- if (typeof error == "string") {
- this.exception = new Error(message || "");
- this.exception.name = error;
- } else if (!error) {
- this.exception = new Error("Error");
- } else {
- this.exception = error;
- }
-
- return this;
- }
-
- proto = {
- create: function create() {
- var functionStub = function () {
-
- callCallback(functionStub, arguments);
-
- if (functionStub.exception) {
- throw functionStub.exception;
- } else if (typeof functionStub.returnArgAt == 'number') {
- return arguments[functionStub.returnArgAt];
- } else if (functionStub.returnThis) {
- return this;
- }
- return functionStub.returnValue;
- };
-
- functionStub.id = "stub#" + uuid++;
- var orig = functionStub;
- functionStub = sinon.spy.create(functionStub);
- functionStub.func = orig;
-
- sinon.extend(functionStub, stub);
- functionStub._create = sinon.stub.create;
- functionStub.displayName = "stub";
- functionStub.toString = sinon.functionToString;
-
- return functionStub;
- },
-
- returns: function returns(value) {
- this.returnValue = value;
-
- return this;
- },
-
- returnsArg: function returnsArg(pos) {
- if (typeof pos != "number") {
- throw new TypeError("argument index is not number");
- }
-
- this.returnArgAt = pos;
-
- return this;
- },
-
- returnsThis: function returnsThis() {
- this.returnThis = true;
-
- return this;
- },
-
- "throws": throwsException,
- throwsException: throwsException,
-
- callsArg: function callsArg(pos) {
- if (typeof pos != "number") {
- throw new TypeError("argument index is not number");
- }
-
- this.callArgAt = pos;
- this.callbackArguments = [];
-
- return this;
- },
-
- callsArgOn: function callsArgOn(pos, context) {
- if (typeof pos != "number") {
- throw new TypeError("argument index is not number");
- }
- if (typeof context != "object") {
- throw new TypeError("argument context is not an object");
- }
-
- this.callArgAt = pos;
- this.callbackArguments = [];
- this.callbackContext = context;
-
- return this;
- },
-
- callsArgWith: function callsArgWith(pos) {
- if (typeof pos != "number") {
- throw new TypeError("argument index is not number");
- }
-
- this.callArgAt = pos;
- this.callbackArguments = slice.call(arguments, 1);
-
- return this;
- },
-
- callsArgOnWith: function callsArgWith(pos, context) {
- if (typeof pos != "number") {
- throw new TypeError("argument index is not number");
- }
- if (typeof context != "object") {
- throw new TypeError("argument context is not an object");
- }
-
- this.callArgAt = pos;
- this.callbackArguments = slice.call(arguments, 2);
- this.callbackContext = context;
-
- return this;
- },
-
- yields: function () {
- this.callArgAt = -1;
- this.callbackArguments = slice.call(arguments, 0);
-
- return this;
- },
-
- yieldsOn: function (context) {
- if (typeof context != "object") {
- throw new TypeError("argument context is not an object");
- }
-
- this.callArgAt = -1;
- this.callbackArguments = slice.call(arguments, 1);
- this.callbackContext = context;
-
- return this;
- },
-
- yieldsTo: function (prop) {
- this.callArgAt = -1;
- this.callArgProp = prop;
- this.callbackArguments = slice.call(arguments, 1);
-
- return this;
- },
-
- yieldsToOn: function (prop, context) {
- if (typeof context != "object") {
- throw new TypeError("argument context is not an object");
- }
-
- this.callArgAt = -1;
- this.callArgProp = prop;
- this.callbackArguments = slice.call(arguments, 2);
- this.callbackContext = context;
-
- return this;
- }
- };
-
- // create asynchronous versions of callsArg* and yields* methods
- for (var method in proto) {
- if (proto.hasOwnProperty(method) && method.match(/^(callsArg|yields)/)) {
- proto[method + 'Async'] = (function (syncFnName) {
- return function () {
- this.callbackAsync = true;
- return this[syncFnName].apply(this, arguments);
- };
- })(method);
- }
- }
-
- return proto;
-
- }()));
-
- if (commonJSModule) {
- module.exports = stub;
- } else {
- sinon.stub = stub;
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend ../sinon.js
- * @depend stub.js
- */
-/*jslint eqeqeq: false, onevar: false, nomen: false*/
-/*global module, require, sinon*/
-/**
- * Mock functions.
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-(function (sinon) {
- var commonJSModule = typeof module == "object" && typeof require == "function";
- var push = [].push;
-
- if (!sinon && commonJSModule) {
- sinon = require("../sinon");
- }
-
- if (!sinon) {
- return;
- }
-
- function mock(object) {
- if (!object) {
- return sinon.expectation.create("Anonymous mock");
- }
-
- return mock.create(object);
- }
-
- sinon.mock = mock;
-
- sinon.extend(mock, (function () {
- function each(collection, callback) {
- if (!collection) {
- return;
- }
-
- for (var i = 0, l = collection.length; i < l; i += 1) {
- callback(collection[i]);
- }
- }
-
- return {
- create: function create(object) {
- if (!object) {
- throw new TypeError("object is null");
- }
-
- var mockObject = sinon.extend({}, mock);
- mockObject.object = object;
- delete mockObject.create;
-
- return mockObject;
- },
-
- expects: function expects(method) {
- if (!method) {
- throw new TypeError("method is falsy");
- }
-
- if (!this.expectations) {
- this.expectations = {};
- this.proxies = [];
- }
-
- if (!this.expectations[method]) {
- this.expectations[method] = [];
- var mockObject = this;
-
- sinon.wrapMethod(this.object, method, function () {
- return mockObject.invokeMethod(method, this, arguments);
- });
-
- push.call(this.proxies, method);
- }
-
- var expectation = sinon.expectation.create(method);
- push.call(this.expectations[method], expectation);
-
- return expectation;
- },
-
- restore: function restore() {
- var object = this.object;
-
- each(this.proxies, function (proxy) {
- if (typeof object[proxy].restore == "function") {
- object[proxy].restore();
- }
- });
- },
-
- verify: function verify() {
- var expectations = this.expectations || {};
- var messages = [], met = [];
-
- each(this.proxies, function (proxy) {
- each(expectations[proxy], function (expectation) {
- if (!expectation.met()) {
- push.call(messages, expectation.toString());
- } else {
- push.call(met, expectation.toString());
- }
- });
- });
-
- this.restore();
-
- if (messages.length > 0) {
- sinon.expectation.fail(messages.concat(met).join("\n"));
- } else {
- sinon.expectation.pass(messages.concat(met).join("\n"));
- }
-
- return true;
- },
-
- invokeMethod: function invokeMethod(method, thisValue, args) {
- var expectations = this.expectations && this.expectations[method];
- var length = expectations && expectations.length || 0, i;
-
- for (i = 0; i < length; i += 1) {
- if (!expectations[i].met() &&
- expectations[i].allowsCall(thisValue, args)) {
- return expectations[i].apply(thisValue, args);
- }
- }
-
- var messages = [], available, exhausted = 0;
-
- for (i = 0; i < length; i += 1) {
- if (expectations[i].allowsCall(thisValue, args)) {
- available = available || expectations[i];
- } else {
- exhausted += 1;
- }
- push.call(messages, " " + expectations[i].toString());
- }
-
- if (exhausted === 0) {
- return available.apply(thisValue, args);
- }
-
- messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({
- proxy: method,
- args: args
- }));
-
- sinon.expectation.fail(messages.join("\n"));
- }
- };
- }()));
-
- var times = sinon.timesInWords;
-
- sinon.expectation = (function () {
- var slice = Array.prototype.slice;
- var _invoke = sinon.spy.invoke;
-
- function callCountInWords(callCount) {
- if (callCount == 0) {
- return "never called";
- } else {
- return "called " + times(callCount);
- }
- }
-
- function expectedCallCountInWords(expectation) {
- var min = expectation.minCalls;
- var max = expectation.maxCalls;
-
- if (typeof min == "number" && typeof max == "number") {
- var str = times(min);
-
- if (min != max) {
- str = "at least " + str + " and at most " + times(max);
- }
-
- return str;
- }
-
- if (typeof min == "number") {
- return "at least " + times(min);
- }
-
- return "at most " + times(max);
- }
-
- function receivedMinCalls(expectation) {
- var hasMinLimit = typeof expectation.minCalls == "number";
- return !hasMinLimit || expectation.callCount >= expectation.minCalls;
- }
-
- function receivedMaxCalls(expectation) {
- if (typeof expectation.maxCalls != "number") {
- return false;
- }
-
- return expectation.callCount == expectation.maxCalls;
- }
-
- return {
- minCalls: 1,
- maxCalls: 1,
-
- create: function create(methodName) {
- var expectation = sinon.extend(sinon.stub.create(), sinon.expectation);
- delete expectation.create;
- expectation.method = methodName;
-
- return expectation;
- },
-
- invoke: function invoke(func, thisValue, args) {
- this.verifyCallAllowed(thisValue, args);
-
- return _invoke.apply(this, arguments);
- },
-
- atLeast: function atLeast(num) {
- if (typeof num != "number") {
- throw new TypeError("'" + num + "' is not number");
- }
-
- if (!this.limitsSet) {
- this.maxCalls = null;
- this.limitsSet = true;
- }
-
- this.minCalls = num;
-
- return this;
- },
-
- atMost: function atMost(num) {
- if (typeof num != "number") {
- throw new TypeError("'" + num + "' is not number");
- }
-
- if (!this.limitsSet) {
- this.minCalls = null;
- this.limitsSet = true;
- }
-
- this.maxCalls = num;
-
- return this;
- },
-
- never: function never() {
- return this.exactly(0);
- },
-
- once: function once() {
- return this.exactly(1);
- },
-
- twice: function twice() {
- return this.exactly(2);
- },
-
- thrice: function thrice() {
- return this.exactly(3);
- },
-
- exactly: function exactly(num) {
- if (typeof num != "number") {
- throw new TypeError("'" + num + "' is not a number");
- }
-
- this.atLeast(num);
- return this.atMost(num);
- },
-
- met: function met() {
- return !this.failed && receivedMinCalls(this);
- },
-
- verifyCallAllowed: function verifyCallAllowed(thisValue, args) {
- if (receivedMaxCalls(this)) {
- this.failed = true;
- sinon.expectation.fail(this.method + " already called " + times(this.maxCalls));
- }
-
- if ("expectedThis" in this && this.expectedThis !== thisValue) {
- sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " +
- this.expectedThis);
- }
-
- if (!("expectedArguments" in this)) {
- return;
- }
-
- if (!args) {
- sinon.expectation.fail(this.method + " received no arguments, expected " +
- this.expectedArguments.join());
- }
-
- if (args.length < this.expectedArguments.length) {
- sinon.expectation.fail(this.method + " received too few arguments (" + args.join() +
- "), expected " + this.expectedArguments.join());
- }
-
- if (this.expectsExactArgCount &&
- args.length != this.expectedArguments.length) {
- sinon.expectation.fail(this.method + " received too many arguments (" + args.join() +
- "), expected " + this.expectedArguments.join());
- }
-
- for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
- if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
- sinon.expectation.fail(this.method + " received wrong arguments (" + args.join() +
- "), expected " + this.expectedArguments.join());
- }
- }
- },
-
- allowsCall: function allowsCall(thisValue, args) {
- if (this.met() && receivedMaxCalls(this)) {
- return false;
- }
-
- if ("expectedThis" in this && this.expectedThis !== thisValue) {
- return false;
- }
-
- if (!("expectedArguments" in this)) {
- return true;
- }
-
- args = args || [];
-
- if (args.length < this.expectedArguments.length) {
- return false;
- }
-
- if (this.expectsExactArgCount &&
- args.length != this.expectedArguments.length) {
- return false;
- }
-
- for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
- if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
- return false;
- }
- }
-
- return true;
- },
-
- withArgs: function withArgs() {
- this.expectedArguments = slice.call(arguments);
- return this;
- },
-
- withExactArgs: function withExactArgs() {
- this.withArgs.apply(this, arguments);
- this.expectsExactArgCount = true;
- return this;
- },
-
- on: function on(thisValue) {
- this.expectedThis = thisValue;
- return this;
- },
-
- toString: function () {
- var args = (this.expectedArguments || []).slice();
-
- if (!this.expectsExactArgCount) {
- push.call(args, "[...]");
- }
-
- var callStr = sinon.spyCall.toString.call({
- proxy: this.method, args: args
- });
-
- var message = callStr.replace(", [...", "[, ...") + " " +
- expectedCallCountInWords(this);
-
- if (this.met()) {
- return "Expectation met: " + message;
- }
-
- return "Expected " + message + " (" +
- callCountInWords(this.callCount) + ")";
- },
-
- verify: function verify() {
- if (!this.met()) {
- sinon.expectation.fail(this.toString());
- } else {
- sinon.expectation.pass(this.toString());
- }
-
- return true;
- },
-
- pass: function(message) {
- sinon.assert.pass(message);
- },
- fail: function (message) {
- var exception = new Error(message);
- exception.name = "ExpectationError";
-
- throw exception;
- }
- };
- }());
-
- if (commonJSModule) {
- module.exports = mock;
- } else {
- sinon.mock = mock;
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend ../sinon.js
- * @depend stub.js
- * @depend mock.js
- */
-/*jslint eqeqeq: false, onevar: false, forin: true*/
-/*global module, require, sinon*/
-/**
- * Collections of stubs, spies and mocks.
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-(function (sinon) {
- var commonJSModule = typeof module == "object" && typeof require == "function";
- var push = [].push;
-
- if (!sinon && commonJSModule) {
- sinon = require("../sinon");
- }
-
- if (!sinon) {
- return;
- }
-
- function getFakes(fakeCollection) {
- if (!fakeCollection.fakes) {
- fakeCollection.fakes = [];
- }
-
- return fakeCollection.fakes;
- }
-
- function each(fakeCollection, method) {
- var fakes = getFakes(fakeCollection);
-
- for (var i = 0, l = fakes.length; i < l; i += 1) {
- if (typeof fakes[i][method] == "function") {
- fakes[i][method]();
- }
- }
- }
-
- function compact(fakeCollection) {
- var fakes = getFakes(fakeCollection);
- var i = 0;
- while (i < fakes.length) {
- fakes.splice(i, 1);
- }
- }
-
- var collection = {
- verify: function resolve() {
- each(this, "verify");
- },
-
- restore: function restore() {
- each(this, "restore");
- compact(this);
- },
-
- verifyAndRestore: function verifyAndRestore() {
- var exception;
-
- try {
- this.verify();
- } catch (e) {
- exception = e;
- }
-
- this.restore();
-
- if (exception) {
- throw exception;
- }
- },
-
- add: function add(fake) {
- push.call(getFakes(this), fake);
- return fake;
- },
-
- spy: function spy() {
- return this.add(sinon.spy.apply(sinon, arguments));
- },
-
- stub: function stub(object, property, value) {
- if (property) {
- var original = object[property];
-
- if (typeof original != "function") {
- if (!object.hasOwnProperty(property)) {
- throw new TypeError("Cannot stub non-existent own property " + property);
- }
-
- object[property] = value;
-
- return this.add({
- restore: function () {
- object[property] = original;
- }
- });
- }
- }
- if (!property && !!object && typeof object == "object") {
- var stubbedObj = sinon.stub.apply(sinon, arguments);
-
- for (var prop in stubbedObj) {
- if (typeof stubbedObj[prop] === "function") {
- this.add(stubbedObj[prop]);
- }
- }
-
- return stubbedObj;
- }
-
- return this.add(sinon.stub.apply(sinon, arguments));
- },
-
- mock: function mock() {
- return this.add(sinon.mock.apply(sinon, arguments));
- },
-
- inject: function inject(obj) {
- var col = this;
-
- obj.spy = function () {
- return col.spy.apply(col, arguments);
- };
-
- obj.stub = function () {
- return col.stub.apply(col, arguments);
- };
-
- obj.mock = function () {
- return col.mock.apply(col, arguments);
- };
-
- return obj;
- }
- };
-
- if (commonJSModule) {
- module.exports = collection;
- } else {
- sinon.collection = collection;
- }
-}(typeof sinon == "object" && sinon || null));
-
-/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/
-/*global module, require, window*/
-/**
- * Fake timer API
- * setTimeout
- * setInterval
- * clearTimeout
- * clearInterval
- * tick
- * reset
- * Date
- *
- * Inspired by jsUnitMockTimeOut from JsUnit
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-if (typeof sinon == "undefined") {
- var sinon = {};
-}
-
-(function (global) {
- var id = 1;
-
- function addTimer(args, recurring) {
- if (args.length === 0) {
- throw new Error("Function requires at least 1 parameter");
- }
-
- var toId = id++;
- var delay = args[1] || 0;
-
- if (!this.timeouts) {
- this.timeouts = {};
- }
-
- this.timeouts[toId] = {
- id: toId,
- func: args[0],
- callAt: this.now + delay,
- invokeArgs: Array.prototype.slice.call(args, 2)
- };
-
- if (recurring === true) {
- this.timeouts[toId].interval = delay;
- }
-
- return toId;
- }
-
- function parseTime(str) {
- if (!str) {
- return 0;
- }
-
- var strings = str.split(":");
- var l = strings.length, i = l;
- var ms = 0, parsed;
-
- if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
- throw new Error("tick only understands numbers and 'h:m:s'");
- }
-
- while (i--) {
- parsed = parseInt(strings[i], 10);
-
- if (parsed >= 60) {
- throw new Error("Invalid time " + str);
- }
-
- ms += parsed * Math.pow(60, (l - i - 1));
- }
-
- return ms * 1000;
- }
-
- function createObject(object) {
- var newObject;
-
- if (Object.create) {
- newObject = Object.create(object);
- } else {
- var F = function () {};
- F.prototype = object;
- newObject = new F();
- }
-
- newObject.Date.clock = newObject;
- return newObject;
- }
-
- sinon.clock = {
- now: 0,
-
- create: function create(now) {
- var clock = createObject(this);
-
- if (typeof now == "number") {
- clock.now = now;
- }
-
- if (!!now && typeof now == "object") {
- throw new TypeError("now should be milliseconds since UNIX epoch");
- }
-
- return clock;
- },
-
- setTimeout: function setTimeout(callback, timeout) {
- return addTimer.call(this, arguments, false);
- },
-
- clearTimeout: function clearTimeout(timerId) {
- if (!this.timeouts) {
- this.timeouts = [];
- }
-
- if (timerId in this.timeouts) {
- delete this.timeouts[timerId];
- }
- },
-
- setInterval: function setInterval(callback, timeout) {
- return addTimer.call(this, arguments, true);
- },
-
- clearInterval: function clearInterval(timerId) {
- this.clearTimeout(timerId);
- },
-
- tick: function tick(ms) {
- ms = typeof ms == "number" ? ms : parseTime(ms);
- var tickFrom = this.now, tickTo = this.now + ms, previous = this.now;
- var timer = this.firstTimerInRange(tickFrom, tickTo);
-
- var firstException;
- while (timer && tickFrom <= tickTo) {
- if (this.timeouts[timer.id]) {
- tickFrom = this.now = timer.callAt;
- try {
- this.callTimer(timer);
- } catch (e) {
- firstException = firstException || e;
- }
- }
-
- timer = this.firstTimerInRange(previous, tickTo);
- previous = tickFrom;
- }
-
- this.now = tickTo;
-
- if (firstException) {
- throw firstException;
- }
- },
-
- firstTimerInRange: function (from, to) {
- var timer, smallest, originalTimer;
-
- for (var id in this.timeouts) {
- if (this.timeouts.hasOwnProperty(id)) {
- if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) {
- continue;
- }
-
- if (!smallest || this.timeouts[id].callAt < smallest) {
- originalTimer = this.timeouts[id];
- smallest = this.timeouts[id].callAt;
-
- timer = {
- func: this.timeouts[id].func,
- callAt: this.timeouts[id].callAt,
- interval: this.timeouts[id].interval,
- id: this.timeouts[id].id,
- invokeArgs: this.timeouts[id].invokeArgs
- };
- }
- }
- }
-
- return timer || null;
- },
-
- callTimer: function (timer) {
- if (typeof timer.interval == "number") {
- this.timeouts[timer.id].callAt += timer.interval;
- } else {
- delete this.timeouts[timer.id];
- }
-
- try {
- if (typeof timer.func == "function") {
- timer.func.apply(null, timer.invokeArgs);
- } else {
- eval(timer.func);
- }
- } catch (e) {
- var exception = e;
- }
-
- if (!this.timeouts[timer.id]) {
- if (exception) {
- throw exception;
- }
- return;
- }
-
- if (exception) {
- throw exception;
- }
- },
-
- reset: function reset() {
- this.timeouts = {};
- },
-
- Date: (function () {
- var NativeDate = Date;
-
- function ClockDate(year, month, date, hour, minute, second, ms) {
- // Defensive and verbose to avoid potential harm in passing
- // explicit undefined when user does not pass argument
- switch (arguments.length) {
- case 0:
- return new NativeDate(ClockDate.clock.now);
- case 1:
- return new NativeDate(year);
- case 2:
- return new NativeDate(year, month);
- case 3:
- return new NativeDate(year, month, date);
- case 4:
- return new NativeDate(year, month, date, hour);
- case 5:
- return new NativeDate(year, month, date, hour, minute);
- case 6:
- return new NativeDate(year, month, date, hour, minute, second);
- default:
- return new NativeDate(year, month, date, hour, minute, second, ms);
- }
- }
-
- return mirrorDateProperties(ClockDate, NativeDate);
- }())
- };
-
- function mirrorDateProperties(target, source) {
- if (source.now) {
- target.now = function now() {
- return target.clock.now;
- };
- } else {
- delete target.now;
- }
-
- if (source.toSource) {
- target.toSource = function toSource() {
- return source.toSource();
- };
- } else {
- delete target.toSource;
- }
-
- target.toString = function toString() {
- return source.toString();
- };
-
- target.prototype = source.prototype;
- target.parse = source.parse;
- target.UTC = source.UTC;
- target.prototype.toUTCString = source.prototype.toUTCString;
- return target;
- }
-
- var methods = ["Date", "setTimeout", "setInterval",
- "clearTimeout", "clearInterval"];
-
- function restore() {
- var method;
-
- for (var i = 0, l = this.methods.length; i < l; i++) {
- method = this.methods[i];
- if (global[method].hadOwnProperty) {
- global[method] = this["_" + method];
- } else {
- delete global[method];
- }
- }
-
- // Prevent multiple executions which will completely remove these props
- this.methods = [];
- }
-
- function stubGlobal(method, clock) {
- clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method);
- clock["_" + method] = global[method];
-
- if (method == "Date") {
- var date = mirrorDateProperties(clock[method], global[method]);
- global[method] = date;
- } else {
- global[method] = function () {
- return clock[method].apply(clock, arguments);
- };
-
- for (var prop in clock[method]) {
- if (clock[method].hasOwnProperty(prop)) {
- global[method][prop] = clock[method][prop];
- }
- }
- }
-
- global[method].clock = clock;
- }
-
- sinon.useFakeTimers = function useFakeTimers(now) {
- var clock = sinon.clock.create(now);
- clock.restore = restore;
- clock.methods = Array.prototype.slice.call(arguments,
- typeof now == "number" ? 1 : 0);
-
- if (clock.methods.length === 0) {
- clock.methods = methods;
- }
-
- for (var i = 0, l = clock.methods.length; i < l; i++) {
- stubGlobal(clock.methods[i], clock);
- }
-
- return clock;
- };
-}(typeof global != "undefined" && typeof global !== "function" ? global : this));
-
-sinon.timers = {
- setTimeout: setTimeout,
- clearTimeout: clearTimeout,
- setInterval: setInterval,
- clearInterval: clearInterval,
- Date: Date
-};
-
-if (typeof module == "object" && typeof require == "function") {
- module.exports = sinon;
-}
-
-/*jslint eqeqeq: false, onevar: false*/
-/*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
-/**
- * Minimal Event interface implementation
- *
- * Original implementation by Sven Fuchs: https://gist.github.com/995028
- * Modifications and tests by Christian Johansen.
- *
- * @author Sven Fuchs ([email protected])
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2011 Sven Fuchs, Christian Johansen
- */
-
-if (typeof sinon == "undefined") {
- this.sinon = {};
-}
-
-(function () {
- var push = [].push;
-
- sinon.Event = function Event(type, bubbles, cancelable) {
- this.initEvent(type, bubbles, cancelable);
- };
-
- sinon.Event.prototype = {
- initEvent: function(type, bubbles, cancelable) {
- this.type = type;
- this.bubbles = bubbles;
- this.cancelable = cancelable;
- },
-
- stopPropagation: function () {},
-
- preventDefault: function () {
- this.defaultPrevented = true;
- }
- };
-
- sinon.EventTarget = {
- addEventListener: function addEventListener(event, listener, useCapture) {
- this.eventListeners = this.eventListeners || {};
- this.eventListeners[event] = this.eventListeners[event] || [];
- push.call(this.eventListeners[event], listener);
- },
-
- removeEventListener: function removeEventListener(event, listener, useCapture) {
- var listeners = this.eventListeners && this.eventListeners[event] || [];
-
- for (var i = 0, l = listeners.length; i < l; ++i) {
- if (listeners[i] == listener) {
- return listeners.splice(i, 1);
- }
- }
- },
-
- dispatchEvent: function dispatchEvent(event) {
- var type = event.type;
- var listeners = this.eventListeners && this.eventListeners[type] || [];
-
- for (var i = 0; i < listeners.length; i++) {
- if (typeof listeners[i] == "function") {
- listeners[i].call(this, event);
- } else {
- listeners[i].handleEvent(event);
- }
- }
-
- return !!event.defaultPrevented;
- }
- };
-}());
-
-/**
- * @depend event.js
- */
-/*jslint eqeqeq: false, onevar: false*/
-/*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
-/**
- * Fake XMLHttpRequest object
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-if (typeof sinon == "undefined") {
- this.sinon = {};
-}
-sinon.xhr = { XMLHttpRequest: this.XMLHttpRequest };
-
-// wrapper for global
-(function(global) {
- var xhr = sinon.xhr;
- xhr.GlobalXMLHttpRequest = global.XMLHttpRequest;
- xhr.GlobalActiveXObject = global.ActiveXObject;
- xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined";
- xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined";
- xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX
- ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false;
-
- /*jsl:ignore*/
- var unsafeHeaders = {
- "Accept-Charset": true,
- "Accept-Encoding": true,
- "Connection": true,
- "Content-Length": true,
- "Cookie": true,
- "Cookie2": true,
- "Content-Transfer-Encoding": true,
- "Date": true,
- "Expect": true,
- "Host": true,
- "Keep-Alive": true,
- "Referer": true,
- "TE": true,
- "Trailer": true,
- "Transfer-Encoding": true,
- "Upgrade": true,
- "User-Agent": true,
- "Via": true
- };
- /*jsl:end*/
-
- function FakeXMLHttpRequest() {
- this.readyState = FakeXMLHttpRequest.UNSENT;
- this.requestHeaders = {};
- this.requestBody = null;
- this.status = 0;
- this.statusText = "";
-
- if (typeof FakeXMLHttpRequest.onCreate == "function") {
- FakeXMLHttpRequest.onCreate(this);
- }
- }
-
- function verifyState(xhr) {
- if (xhr.readyState !== FakeXMLHttpRequest.OPENED) {
- throw new Error("INVALID_STATE_ERR");
- }
-
- if (xhr.sendFlag) {
- throw new Error("INVALID_STATE_ERR");
- }
- }
-
- // filtering to enable a white-list version of Sinon FakeXhr,
- // where whitelisted requests are passed through to real XHR
- function each(collection, callback) {
- if (!collection) return;
- for (var i = 0, l = collection.length; i < l; i += 1) {
- callback(collection[i]);
- }
- }
- function some(collection, callback) {
- for (var index = 0; index < collection.length; index++) {
- if(callback(collection[index]) === true) return true;
- };
- return false;
- }
- // largest arity in XHR is 5 - XHR#open
- var apply = function(obj,method,args) {
- switch(args.length) {
- case 0: return obj[method]();
- case 1: return obj[method](args[0]);
- case 2: return obj[method](args[0],args[1]);
- case 3: return obj[method](args[0],args[1],args[2]);
- case 4: return obj[method](args[0],args[1],args[2],args[3]);
- case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]);
- };
- };
-
- FakeXMLHttpRequest.filters = [];
- FakeXMLHttpRequest.addFilter = function(fn) {
- this.filters.push(fn)
- };
- var IE6Re = /MSIE 6/;
- FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) {
- var xhr = new sinon.xhr.workingXHR();
- each(["open","setRequestHeader","send","abort","getResponseHeader",
- "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"],
- function(method) {
- fakeXhr[method] = function() {
- return apply(xhr,method,arguments);
- };
- });
-
- var copyAttrs = function(args) {
- each(args, function(attr) {
- try {
- fakeXhr[attr] = xhr[attr]
- } catch(e) {
- if(!IE6Re.test(navigator.userAgent)) throw e;
- }
- });
- };
-
- var stateChange = function() {
- fakeXhr.readyState = xhr.readyState;
- if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) {
- copyAttrs(["status","statusText"]);
- }
- if(xhr.readyState >= FakeXMLHttpRequest.LOADING) {
- copyAttrs(["responseText"]);
- }
- if(xhr.readyState === FakeXMLHttpRequest.DONE) {
- copyAttrs(["responseXML"]);
- }
- if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr);
- };
- if(xhr.addEventListener) {
- for(var event in fakeXhr.eventListeners) {
- if(fakeXhr.eventListeners.hasOwnProperty(event)) {
- each(fakeXhr.eventListeners[event],function(handler) {
- xhr.addEventListener(event, handler);
- });
- }
- }
- xhr.addEventListener("readystatechange",stateChange);
- } else {
- xhr.onreadystatechange = stateChange;
- }
- apply(xhr,"open",xhrArgs);
- };
- FakeXMLHttpRequest.useFilters = false;
-
- function verifyRequestSent(xhr) {
- if (xhr.readyState == FakeXMLHttpRequest.DONE) {
- throw new Error("Request done");
- }
- }
-
- function verifyHeadersReceived(xhr) {
- if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) {
- throw new Error("No headers received");
- }
- }
-
- function verifyResponseBodyType(body) {
- if (typeof body != "string") {
- var error = new Error("Attempted to respond to fake XMLHttpRequest with " +
- body + ", which is not a string.");
- error.name = "InvalidBodyException";
- throw error;
- }
- }
-
- sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, {
- async: true,
-
- open: function open(method, url, async, username, password) {
- this.method = method;
- this.url = url;
- this.async = typeof async == "boolean" ? async : true;
- this.username = username;
- this.password = password;
- this.responseText = null;
- this.responseXML = null;
- this.requestHeaders = {};
- this.sendFlag = false;
- if(sinon.FakeXMLHttpRequest.useFilters === true) {
- var xhrArgs = arguments;
- var defake = some(FakeXMLHttpRequest.filters,function(filter) {
- return filter.apply(this,xhrArgs)
- });
- if (defake) {
- return sinon.FakeXMLHttpRequest.defake(this,arguments);
- }
- }
- this.readyStateChange(FakeXMLHttpRequest.OPENED);
- },
-
- readyStateChange: function readyStateChange(state) {
- this.readyState = state;
-
- if (typeof this.onreadystatechange == "function") {
- try {
- this.onreadystatechange();
- } catch (e) {
- sinon.logError("Fake XHR onreadystatechange handler", e);
- }
- }
-
- this.dispatchEvent(new sinon.Event("readystatechange"));
- },
-
- setRequestHeader: function setRequestHeader(header, value) {
- verifyState(this);
-
- if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) {
- throw new Error("Refused to set unsafe header \"" + header + "\"");
- }
-
- if (this.requestHeaders[header]) {
- this.requestHeaders[header] += "," + value;
- } else {
- this.requestHeaders[header] = value;
- }
- },
-
- // Helps testing
- setResponseHeaders: function setResponseHeaders(headers) {
- this.responseHeaders = {};
-
- for (var header in headers) {
- if (headers.hasOwnProperty(header)) {
- this.responseHeaders[header] = headers[header];
- }
- }
-
- if (this.async) {
- this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED);
- }
- },
-
- // Currently treats ALL data as a DOMString (i.e. no Document)
- send: function send(data) {
- verifyState(this);
-
- if (!/^(get|head)$/i.test(this.method)) {
- if (this.requestHeaders["Content-Type"]) {
- var value = this.requestHeaders["Content-Type"].split(";");
- this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8";
- } else {
- this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8";
- }
-
- this.requestBody = data;
- }
-
- this.errorFlag = false;
- this.sendFlag = this.async;
- this.readyStateChange(FakeXMLHttpRequest.OPENED);
-
- if (typeof this.onSend == "function") {
- this.onSend(this);
- }
- },
-
- abort: function abort() {
- this.aborted = true;
- this.responseText = null;
- this.errorFlag = true;
- this.requestHeaders = {};
-
- if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) {
- this.readyStateChange(sinon.FakeXMLHttpRequest.DONE);
- this.sendFlag = false;
- }
-
- this.readyState = sinon.FakeXMLHttpRequest.UNSENT;
- },
-
- getResponseHeader: function getResponseHeader(header) {
- if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
- return null;
- }
-
- if (/^Set-Cookie2?$/i.test(header)) {
- return null;
- }
-
- header = header.toLowerCase();
-
- for (var h in this.responseHeaders) {
- if (h.toLowerCase() == header) {
- return this.responseHeaders[h];
- }
- }
-
- return null;
- },
-
- getAllResponseHeaders: function getAllResponseHeaders() {
- if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
- return "";
- }
-
- var headers = "";
-
- for (var header in this.responseHeaders) {
- if (this.responseHeaders.hasOwnProperty(header) &&
- !/^Set-Cookie2?$/i.test(header)) {
- headers += header + ": " + this.responseHeaders[header] + "\r\n";
- }
- }
-
- return headers;
- },
-
- setResponseBody: function setResponseBody(body) {
- verifyRequestSent(this);
- verifyHeadersReceived(this);
- verifyResponseBodyType(body);
-
- var chunkSize = this.chunkSize || 10;
- var index = 0;
- this.responseText = "";
-
- do {
- if (this.async) {
- this.readyStateChange(FakeXMLHttpRequest.LOADING);
- }
-
- this.responseText += body.substring(index, index + chunkSize);
- index += chunkSize;
- } while (index < body.length);
-
- var type = this.getResponseHeader("Content-Type");
-
- if (this.responseText &&
- (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
- try {
- this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText);
- } catch (e) {
- // Unable to parse XML - no biggie
- }
- }
-
- if (this.async) {
- this.readyStateChange(FakeXMLHttpRequest.DONE);
- } else {
- this.readyState = FakeXMLHttpRequest.DONE;
- }
- },
-
- respond: function respond(status, headers, body) {
- this.setResponseHeaders(headers || {});
- this.status = typeof status == "number" ? status : 200;
- this.statusText = FakeXMLHttpRequest.statusCodes[this.status];
- this.setResponseBody(body || "");
- }
- });
-
- sinon.extend(FakeXMLHttpRequest, {
- UNSENT: 0,
- OPENED: 1,
- HEADERS_RECEIVED: 2,
- LOADING: 3,
- DONE: 4
- });
-
- // Borrowed from JSpec
- FakeXMLHttpRequest.parseXML = function parseXML(text) {
- var xmlDoc;
-
- if (typeof DOMParser != "undefined") {
- var parser = new DOMParser();
- xmlDoc = parser.parseFromString(text, "text/xml");
- } else {
- xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
- xmlDoc.async = "false";
- xmlDoc.loadXML(text);
- }
-
- return xmlDoc;
- };
-
- FakeXMLHttpRequest.statusCodes = {
- 100: "Continue",
- 101: "Switching Protocols",
- 200: "OK",
- 201: "Created",
- 202: "Accepted",
- 203: "Non-Authoritative Information",
- 204: "No Content",
- 205: "Reset Content",
- 206: "Partial Content",
- 300: "Multiple Choice",
- 301: "Moved Permanently",
- 302: "Found",
- 303: "See Other",
- 304: "Not Modified",
- 305: "Use Proxy",
- 307: "Temporary Redirect",
- 400: "Bad Request",
- 401: "Unauthorized",
- 402: "Payment Required",
- 403: "Forbidden",
- 404: "Not Found",
- 405: "Method Not Allowed",
- 406: "Not Acceptable",
- 407: "Proxy Authentication Required",
- 408: "Request Timeout",
- 409: "Conflict",
- 410: "Gone",
- 411: "Length Required",
- 412: "Precondition Failed",
- 413: "Request Entity Too Large",
- 414: "Request-URI Too Long",
- 415: "Unsupported Media Type",
- 416: "Requested Range Not Satisfiable",
- 417: "Expectation Failed",
- 422: "Unprocessable Entity",
- 500: "Internal Server Error",
- 501: "Not Implemented",
- 502: "Bad Gateway",
- 503: "Service Unavailable",
- 504: "Gateway Timeout",
- 505: "HTTP Version Not Supported"
- };
-
- sinon.useFakeXMLHttpRequest = function () {
- sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) {
- if (xhr.supportsXHR) {
- global.XMLHttpRequest = xhr.GlobalXMLHttpRequest;
- }
-
- if (xhr.supportsActiveX) {
- global.ActiveXObject = xhr.GlobalActiveXObject;
- }
-
- delete sinon.FakeXMLHttpRequest.restore;
-
- if (keepOnCreate !== true) {
- delete sinon.FakeXMLHttpRequest.onCreate;
- }
- };
- if (xhr.supportsXHR) {
- global.XMLHttpRequest = sinon.FakeXMLHttpRequest;
- }
-
- if (xhr.supportsActiveX) {
- global.ActiveXObject = function ActiveXObject(objId) {
- if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) {
-
- return new sinon.FakeXMLHttpRequest();
- }
-
- return new xhr.GlobalActiveXObject(objId);
- };
- }
-
- return sinon.FakeXMLHttpRequest;
- };
-
- sinon.FakeXMLHttpRequest = FakeXMLHttpRequest;
-})(this);
-
-if (typeof module == "object" && typeof require == "function") {
- module.exports = sinon;
-}
-
-/**
- * @depend fake_xml_http_request.js
- */
-/*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/
-/*global module, require, window*/
-/**
- * The Sinon "server" mimics a web server that receives requests from
- * sinon.FakeXMLHttpRequest and provides an API to respond to those requests,
- * both synchronously and asynchronously. To respond synchronuously, canned
- * answers have to be provided upfront.
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-if (typeof sinon == "undefined") {
- var sinon = {};
-}
-
-sinon.fakeServer = (function () {
- var push = [].push;
- function F() {}
-
- function create(proto) {
- F.prototype = proto;
- return new F();
- }
-
- function responseArray(handler) {
- var response = handler;
-
- if (Object.prototype.toString.call(handler) != "[object Array]") {
- response = [200, {}, handler];
- }
-
- if (typeof response[2] != "string") {
- throw new TypeError("Fake server response body should be string, but was " +
- typeof response[2]);
- }
-
- return response;
- }
-
- var wloc = typeof window !== "undefined" ? window.location : {};
- var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host);
-
- function matchOne(response, reqMethod, reqUrl) {
- var rmeth = response.method;
- var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase();
- var url = response.url;
- var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl));
-
- return matchMethod && matchUrl;
- }
-
- function match(response, request) {
- var requestMethod = this.getHTTPMethod(request);
- var requestUrl = request.url;
-
- if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) {
- requestUrl = requestUrl.replace(rCurrLoc, "");
- }
-
- if (matchOne(response, this.getHTTPMethod(request), requestUrl)) {
- if (typeof response.response == "function") {
- var ru = response.url;
- var args = [request].concat(!ru ? [] : requestUrl.match(ru).slice(1));
- return response.response.apply(response, args);
- }
-
- return true;
- }
-
- return false;
- }
-
- return {
- create: function () {
- var server = create(this);
- this.xhr = sinon.useFakeXMLHttpRequest();
- server.requests = [];
-
- this.xhr.onCreate = function (xhrObj) {
- server.addRequest(xhrObj);
- };
-
- return server;
- },
-
- addRequest: function addRequest(xhrObj) {
- var server = this;
- push.call(this.requests, xhrObj);
-
- xhrObj.onSend = function () {
- server.handleRequest(this);
- };
-
- if (this.autoRespond && !this.responding) {
- setTimeout(function () {
- server.responding = false;
- server.respond();
- }, this.autoRespondAfter || 10);
-
- this.responding = true;
- }
- },
-
- getHTTPMethod: function getHTTPMethod(request) {
- if (this.fakeHTTPMethods && /post/i.test(request.method)) {
- var matches = (request.requestBody || "").match(/_method=([^\b;]+)/);
- return !!matches ? matches[1] : request.method;
- }
-
- return request.method;
- },
-
- handleRequest: function handleRequest(xhr) {
- if (xhr.async) {
- if (!this.queue) {
- this.queue = [];
- }
-
- push.call(this.queue, xhr);
- } else {
- this.processRequest(xhr);
- }
- },
-
- respondWith: function respondWith(method, url, body) {
- if (arguments.length == 1 && typeof method != "function") {
- this.response = responseArray(method);
- return;
- }
-
- if (!this.responses) { this.responses = []; }
-
- if (arguments.length == 1) {
- body = method;
- url = method = null;
- }
-
- if (arguments.length == 2) {
- body = url;
- url = method;
- method = null;
- }
-
- push.call(this.responses, {
- method: method,
- url: url,
- response: typeof body == "function" ? body : responseArray(body)
- });
- },
-
- respond: function respond() {
- if (arguments.length > 0) this.respondWith.apply(this, arguments);
- var queue = this.queue || [];
- var request;
-
- while(request = queue.shift()) {
- this.processRequest(request);
- }
- },
-
- processRequest: function processRequest(request) {
- try {
- if (request.aborted) {
- return;
- }
-
- var response = this.response || [404, {}, ""];
-
- if (this.responses) {
- for (var i = 0, l = this.responses.length; i < l; i++) {
- if (match.call(this, this.responses[i], request)) {
- response = this.responses[i].response;
- break;
- }
- }
- }
-
- if (request.readyState != 4) {
- request.respond(response[0], response[1], response[2]);
- }
- } catch (e) {
- sinon.logError("Fake server request processing", e);
- }
- },
-
- restore: function restore() {
- return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments);
- }
- };
-}());
-
-if (typeof module == "object" && typeof require == "function") {
- module.exports = sinon;
-}
-
-/**
- * @depend fake_server.js
- * @depend fake_timers.js
- */
-/*jslint browser: true, eqeqeq: false, onevar: false*/
-/*global sinon*/
-/**
- * Add-on for sinon.fakeServer that automatically handles a fake timer along with
- * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery
- * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead,
- * it polls the object for completion with setInterval. Dispite the direct
- * motivation, there is nothing jQuery-specific in this file, so it can be used
- * in any environment where the ajax implementation depends on setInterval or
- * setTimeout.
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-(function () {
- function Server() {}
- Server.prototype = sinon.fakeServer;
-
- sinon.fakeServerWithClock = new Server();
-
- sinon.fakeServerWithClock.addRequest = function addRequest(xhr) {
- if (xhr.async) {
- if (typeof setTimeout.clock == "object") {
- this.clock = setTimeout.clock;
- } else {
- this.clock = sinon.useFakeTimers();
- this.resetClock = true;
- }
-
- if (!this.longestTimeout) {
- var clockSetTimeout = this.clock.setTimeout;
- var clockSetInterval = this.clock.setInterval;
- var server = this;
-
- this.clock.setTimeout = function (fn, timeout) {
- server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
-
- return clockSetTimeout.apply(this, arguments);
- };
-
- this.clock.setInterval = function (fn, timeout) {
- server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
-
- return clockSetInterval.apply(this, arguments);
- };
- }
- }
-
- return sinon.fakeServer.addRequest.call(this, xhr);
- };
-
- sinon.fakeServerWithClock.respond = function respond() {
- var returnVal = sinon.fakeServer.respond.apply(this, arguments);
-
- if (this.clock) {
- this.clock.tick(this.longestTimeout || 0);
- this.longestTimeout = 0;
-
- if (this.resetClock) {
- this.clock.restore();
- this.resetClock = false;
- }
- }
-
- return returnVal;
- };
-
- sinon.fakeServerWithClock.restore = function restore() {
- if (this.clock) {
- this.clock.restore();
- }
-
- return sinon.fakeServer.restore.apply(this, arguments);
- };
-}());
-
-/**
- * @depend ../sinon.js
- * @depend collection.js
- * @depend util/fake_timers.js
- * @depend util/fake_server_with_clock.js
- */
-/*jslint eqeqeq: false, onevar: false, plusplus: false*/
-/*global require, module*/
-/**
- * Manages fake collections as well as fake utilities such as Sinon's
- * timers and fake XHR implementation in one convenient object.
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-if (typeof module == "object" && typeof require == "function") {
- var sinon = require("../sinon");
- sinon.extend(sinon, require("./util/fake_timers"));
-}
-
-(function () {
- var push = [].push;
-
- function exposeValue(sandbox, config, key, value) {
- if (!value) {
- return;
- }
-
- if (config.injectInto) {
- config.injectInto[key] = value;
- } else {
- push.call(sandbox.args, value);
- }
- }
-
- function prepareSandboxFromConfig(config) {
- var sandbox = sinon.create(sinon.sandbox);
-
- if (config.useFakeServer) {
- if (typeof config.useFakeServer == "object") {
- sandbox.serverPrototype = config.useFakeServer;
- }
-
- sandbox.useFakeServer();
- }
-
- if (config.useFakeTimers) {
- if (typeof config.useFakeTimers == "object") {
- sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers);
- } else {
- sandbox.useFakeTimers();
- }
- }
-
- return sandbox;
- }
-
- sinon.sandbox = sinon.extend(sinon.create(sinon.collection), {
- useFakeTimers: function useFakeTimers() {
- this.clock = sinon.useFakeTimers.apply(sinon, arguments);
-
- return this.add(this.clock);
- },
-
- serverPrototype: sinon.fakeServer,
-
- useFakeServer: function useFakeServer() {
- var proto = this.serverPrototype || sinon.fakeServer;
-
- if (!proto || !proto.create) {
- return null;
- }
-
- this.server = proto.create();
- return this.add(this.server);
- },
-
- inject: function (obj) {
- sinon.collection.inject.call(this, obj);
-
- if (this.clock) {
- obj.clock = this.clock;
- }
-
- if (this.server) {
- obj.server = this.server;
- obj.requests = this.server.requests;
- }
-
- return obj;
- },
-
- create: function (config) {
- if (!config) {
- return sinon.create(sinon.sandbox);
- }
-
- var sandbox = prepareSandboxFromConfig(config);
- sandbox.args = sandbox.args || [];
- var prop, value, exposed = sandbox.inject({});
-
- if (config.properties) {
- for (var i = 0, l = config.properties.length; i < l; i++) {
- prop = config.properties[i];
- value = exposed[prop] || prop == "sandbox" && sandbox;
- exposeValue(sandbox, config, prop, value);
- }
- } else {
- exposeValue(sandbox, config, "sandbox", value);
- }
-
- return sandbox;
- }
- });
-
- sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer;
-
- if (typeof module == "object" && typeof require == "function") {
- module.exports = sinon.sandbox;
- }
-}());
-
-/**
- * @depend ../sinon.js
- * @depend stub.js
- * @depend mock.js
- * @depend sandbox.js
- */
-/*jslint eqeqeq: false, onevar: false, forin: true, plusplus: false*/
-/*global module, require, sinon*/
-/**
- * Test function, sandboxes fakes
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-(function (sinon) {
- var commonJSModule = typeof module == "object" && typeof require == "function";
-
- if (!sinon && commonJSModule) {
- sinon = require("../sinon");
- }
-
- if (!sinon) {
- return;
- }
-
- function test(callback) {
- var type = typeof callback;
-
- if (type != "function") {
- throw new TypeError("sinon.test needs to wrap a test function, got " + type);
- }
-
- return function () {
- var config = sinon.getConfig(sinon.config);
- config.injectInto = config.injectIntoThis && this || config.injectInto;
- var sandbox = sinon.sandbox.create(config);
- var exception, result;
- var args = Array.prototype.slice.call(arguments).concat(sandbox.args);
-
- try {
- result = callback.apply(this, args);
- } finally {
- sandbox.verifyAndRestore();
- }
-
- return result;
- };
- }
-
- test.config = {
- injectIntoThis: true,
- injectInto: null,
- properties: ["spy", "stub", "mock", "clock", "server", "requests"],
- useFakeTimers: true,
- useFakeServer: true
- };
-
- if (commonJSModule) {
- module.exports = test;
- } else {
- sinon.test = test;
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend ../sinon.js
- * @depend test.js
- */
-/*jslint eqeqeq: false, onevar: false, eqeqeq: false*/
-/*global module, require, sinon*/
-/**
- * Test case, sandboxes all test functions
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-(function (sinon) {
- var commonJSModule = typeof module == "object" && typeof require == "function";
-
- if (!sinon && commonJSModule) {
- sinon = require("../sinon");
- }
-
- if (!sinon || !Object.prototype.hasOwnProperty) {
- return;
- }
-
- function createTest(property, setUp, tearDown) {
- return function () {
- if (setUp) {
- setUp.apply(this, arguments);
- }
-
- var exception, result;
-
- try {
- result = property.apply(this, arguments);
- } catch (e) {
- exception = e;
- }
-
- if (tearDown) {
- tearDown.apply(this, arguments);
- }
-
- if (exception) {
- throw exception;
- }
-
- return result;
- };
- }
-
- function testCase(tests, prefix) {
- /*jsl:ignore*/
- if (!tests || typeof tests != "object") {
- throw new TypeError("sinon.testCase needs an object with test functions");
- }
- /*jsl:end*/
-
- prefix = prefix || "test";
- var rPrefix = new RegExp("^" + prefix);
- var methods = {}, testName, property, method;
- var setUp = tests.setUp;
- var tearDown = tests.tearDown;
-
- for (testName in tests) {
- if (tests.hasOwnProperty(testName)) {
- property = tests[testName];
-
- if (/^(setUp|tearDown)$/.test(testName)) {
- continue;
- }
-
- if (typeof property == "function" && rPrefix.test(testName)) {
- method = property;
-
- if (setUp || tearDown) {
- method = createTest(property, setUp, tearDown);
- }
-
- methods[testName] = sinon.test(method);
- } else {
- methods[testName] = tests[testName];
- }
- }
- }
-
- return methods;
- }
-
- if (commonJSModule) {
- module.exports = testCase;
- } else {
- sinon.testCase = testCase;
- }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend ../sinon.js
- * @depend stub.js
- */
-/*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/
-/*global module, require, sinon*/
-/**
- * Assertions matching the test spy retrieval interface.
- *
- * @author Christian Johansen ([email protected])
- * @license BSD
- *
- * Copyright (c) 2010-2011 Christian Johansen
- */
-
-(function (sinon, global) {
- var commonJSModule = typeof module == "object" && typeof require == "function";
- var slice = Array.prototype.slice;
- var assert;
-
- if (!sinon && commonJSModule) {
- sinon = require("../sinon");
- }
-
- if (!sinon) {
- return;
- }
-
- function verifyIsStub() {
- var method;
-
- for (var i = 0, l = arguments.length; i < l; ++i) {
- method = arguments[i];
-
- if (!method) {
- assert.fail("fake is not a spy");
- }
-
- if (typeof method != "function") {
- assert.fail(method + " is not a function");
- }
-
- if (typeof method.getCall != "function") {
- assert.fail(method + " is not stubbed");
- }
- }
- }
-
- function failAssertion(object, msg) {
- object = object || global;
- var failMethod = object.fail || assert.fail;
- failMethod.call(object, msg);
- }
-
- function mirrorPropAsAssertion(name, method, message) {
- if (arguments.length == 2) {
- message = method;
- method = name;
- }
-
- assert[name] = function (fake) {
- verifyIsStub(fake);
-
- var args = slice.call(arguments, 1);
- var failed = false;
-
- if (typeof method == "function") {
- failed = !method(fake);
- } else {
- failed = typeof fake[method] == "function" ?
- !fake[method].apply(fake, args) : !fake[method];
- }
-
- if (failed) {
- failAssertion(this, fake.printf.apply(fake, [message].concat(args)));
- } else {
- assert.pass(name);
- }
- };
- }
-
- function exposedName(prefix, prop) {
- return !prefix || /^fail/.test(prop) ? prop :
- prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1);
- };
-
- assert = {
- failException: "AssertError",
-
- fail: function fail(message) {
- var error = new Error(message);
- error.name = this.failException || assert.failException;
-
- throw error;
- },
-
- pass: function pass(assertion) {},
-
- callOrder: function assertCallOrder() {
- verifyIsStub.apply(null, arguments);
- var expected = "", actual = "";
-
- if (!sinon.calledInOrder(arguments)) {
- try {
- expected = [].join.call(arguments, ", ");
- actual = sinon.orderByFirstCall(slice.call(arguments)).join(", ");
- } catch (e) {
- // If this fails, we'll just fall back to the blank string
- }
-
- failAssertion(this, "expected " + expected + " to be " +
- "called in order but were called as " + actual);
- } else {
- assert.pass("callOrder");
- }
- },
-
- callCount: function assertCallCount(method, count) {
- verifyIsStub(method);
-
- if (method.callCount != count) {
- var msg = "expected %n to be called " + sinon.timesInWords(count) +
- " but was called %c%C";
- failAssertion(this, method.printf(msg));
- } else {
- assert.pass("callCount");
- }
- },
-
- expose: function expose(target, options) {
- if (!target) {
- throw new TypeError("target is null or undefined");
- }
-
- var o = options || {};
- var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix;
- var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail;
-
- for (var method in this) {
- if (method != "export" && (includeFail || !/^(fail)/.test(method))) {
- target[exposedName(prefix, method)] = this[method];
- }
- }
-
- return target;
- }
- };
-
- mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called");
- mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; },
- "expected %n to not have been called but was called %c%C");
- mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C");
- mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C");
- mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C");
- mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t");
- mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t");
- mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new");
- mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new");
- mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C");
- mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C");
- mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
- mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C");
- mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
- mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
- mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C");
- mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C");
- mirrorPropAsAssertion("threw", "%n did not throw exception%C");
- mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C");
-
- if (commonJSModule) {
- module.exports = assert;
- } else {
- sinon.assert = assert;
- }
-}(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : global));
-
-return sinon;}.call(typeof window != 'undefined' && window || {}));
diff --git a/ckan/public-bs2/base/vendor/bootstrap/less/tests/buttons.html b/ckan/public-bs2/base/vendor/bootstrap/less/tests/buttons.html
deleted file mode 100755
--- a/ckan/public-bs2/base/vendor/bootstrap/less/tests/buttons.html
+++ /dev/null
@@ -1,139 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Buttons · Bootstrap</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="">
- <meta name="author" content="">
-
- <!-- Le styles -->
- <link href="../../docs/assets/css/bootstrap.css" rel="stylesheet">
- <style>
- body {
- padding-top: 30px;
- padding-bottom: 30px;
- }
- </style>
- <link href="../../docs/assets/css/bootstrap-responsive.css" rel="stylesheet">
-
- <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
- <!--[if lt IE 9]>
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
- <![endif]-->
-
- <!-- Le fav and touch icons -->
- <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../docs/assets/ico/apple-touch-icon-144-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../docs/assets/ico/apple-touch-icon-114-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../docs/assets/ico/apple-touch-icon-72-precomposed.png">
- <link rel="apple-touch-icon-precomposed" href="../../docs/assets/ico/apple-touch-icon-57-precomposed.png">
- <link rel="shortcut icon" href="../../docs/assets/ico/favicon.png">
- </head>
-
- <body>
-
- <div class="container">
-
- <h2>Dropups</h2>
- <div class="btn-toolbar">
- <div class="btn-group dropup">
- <button class="btn">Dropup</button>
- <button class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li><a href="#">Separated link</a></li>
- </ul>
- </div><!-- /btn-group -->
- <div class="btn-group dropup">
- <button class="btn btn-primary">Dropup</button>
- <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li><a href="#">Separated link</a></li>
- </ul>
- </div><!-- /btn-group -->
- <div class="btn-group dropup">
- <button class="btn btn-danger">Dropup</button>
- <button class="btn btn-danger dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li><a href="#">Separated link</a></li>
- </ul>
- </div><!-- /btn-group -->
- <div class="btn-group dropup">
- <button class="btn btn-warning">Dropup</button>
- <button class="btn btn-warning dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li><a href="#">Separated link</a></li>
- </ul>
- </div><!-- /btn-group -->
- <div class="btn-group dropup">
- <button class="btn btn-success">Dropup</button>
- <button class="btn btn-success dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li><a href="#">Separated link</a></li>
- </ul>
- </div><!-- /btn-group -->
- <div class="btn-group dropup">
- <button class="btn btn-info">Dropup</button>
- <button class="btn btn-info dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li><a href="#">Separated link</a></li>
- </ul>
- </div><!-- /btn-group -->
- <div class="btn-group dropup">
- <button class="btn btn-inverse">Dropup</button>
- <button class="btn btn-inverse dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li><a href="#">Separated link</a></li>
- </ul>
- </div><!-- /btn-group -->
- </div><!-- /btn-toolbar -->
-
-
- </div> <!-- /container -->
-
- <!-- Le javascript
- ================================================== -->
- <!-- Placed at the end of the document so the pages load faster -->
- <script src="../../docs/assets/js/jquery.js"></script>
- <script src="../../docs/assets/js/bootstrap-transition.js"></script>
- <script src="../../docs/assets/js/bootstrap-alert.js"></script>
- <script src="../../docs/assets/js/bootstrap-modal.js"></script>
- <script src="../../docs/assets/js/bootstrap-dropdown.js"></script>
- <script src="../../docs/assets/js/bootstrap-scrollspy.js"></script>
- <script src="../../docs/assets/js/bootstrap-tab.js"></script>
- <script src="../../docs/assets/js/bootstrap-tooltip.js"></script>
- <script src="../../docs/assets/js/bootstrap-popover.js"></script>
- <script src="../../docs/assets/js/bootstrap-button.js"></script>
- <script src="../../docs/assets/js/bootstrap-collapse.js"></script>
- <script src="../../docs/assets/js/bootstrap-carousel.js"></script>
- <script src="../../docs/assets/js/bootstrap-typeahead.js"></script>
-
- </body>
-</html>
diff --git a/ckan/public-bs2/base/vendor/bootstrap/less/tests/css-tests.css b/ckan/public-bs2/base/vendor/bootstrap/less/tests/css-tests.css
deleted file mode 100755
--- a/ckan/public-bs2/base/vendor/bootstrap/less/tests/css-tests.css
+++ /dev/null
@@ -1,150 +0,0 @@
-/*!
- * Bootstrap CSS Tests
- */
-
-
-/* Remove background image */
-body {
- background-image: none;
-}
-
-/* Space out subhead */
-.subhead {
- margin-bottom: 36px;
-}
-/*h4 {
- margin-bottom: 5px;
-}
-*/
-
-.type-test {
- margin-bottom: 20px;
- padding: 0 20px 20px;
- background: url(../../docs/assets/img/grid-baseline-20px.png);
-}
-.type-test h1,
-.type-test h2,
-.type-test h3,
-.type-test h4,
-.type-test h5,
-.type-test h6 {
- background-color: rgba(255,0,0,.2);
-}
-
-
-/* colgroup tests */
-.col1 {
- background-color: rgba(255,0,0,.1);
-}
-.col2 {
- background-color: rgba(0,255,0,.1);
-}
-.col3 {
- background-color: rgba(0,0,255,.1);
-}
-
-
-/* Fluid row inputs */
-#rowInputs .row > [class*=span],
-#fluidRowInputs .row-fluid > [class*=span] {
- background-color: rgba(255,0,0,.1);
-}
-
-
-/* Fluid grid */
-.fluid-grid {
- margin-bottom: 45px;
-}
-.fluid-grid .row {
- height: 40px;
- padding-top: 10px;
- margin-top: 10px;
- color: #ddd;
- text-align: center;
-}
-.fluid-grid .span1 {
- background-color: #999;
-}
-
-
-/* Gradients */
-
-[class^="gradient-"] {
- width: 100%;
- height: 400px;
- margin: 20px 0;
- -webkit-border-radius: 5px;
- -moz-border-radius: 5px;
- border-radius: 5px;
-}
-
-.gradient-horizontal {
- background-color: #333333;
- background-image: -moz-linear-gradient(left, #555555, #333333);
- background-image: -webkit-gradient(linear, 0 0, 100% 0, from(#555555), to(#333333));
- background-image: -webkit-linear-gradient(left, #555555, #333333);
- background-image: -o-linear-gradient(left, #555555, #333333);
- background-image: linear-gradient(to right, #555555, #333333);
- background-repeat: repeat-x;
- filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff555555', endColorstr='#ff333333', GradientType=1);
-}
-
-.gradient-vertical {
- background-color: #474747;
- background-image: -moz-linear-gradient(top, #555555, #333333);
- background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#555555), to(#333333));
- background-image: -webkit-linear-gradient(top, #555555, #333333);
- background-image: -o-linear-gradient(top, #555555, #333333);
- background-image: linear-gradient(to bottom, #555555, #333333);
- background-repeat: repeat-x;
- filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff555555', endColorstr='#ff333333', GradientType=0);
-}
-
-.gradient-directional {
- background-color: #333333;
- background-image: -moz-linear-gradient(45deg, #555555, #333333);
- background-image: -webkit-linear-gradient(45deg, #555555, #333333);
- background-image: -o-linear-gradient(45deg, #555555, #333333);
- background-image: linear-gradient(45deg, #555555, #333333);
- background-repeat: repeat-x;
-}
-
-.gradient-vertical-three {
- background-color: #8940a5;
- background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#00b3ee), color-stop(50%, #7a43b6), to(#c3325f));
- background-image: -webkit-linear-gradient(#00b3ee, #7a43b6 50%, #c3325f);
- background-image: -moz-linear-gradient(top, #00b3ee, #7a43b6 50%, #c3325f);
- background-image: -o-linear-gradient(#00b3ee, #7a43b6 50%, #c3325f);
- background-image: linear-gradient(#00b3ee, #7a43b6 50%, #c3325f);
- background-repeat: no-repeat;
- filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff00b3ee', endColorstr='#ffc3325f', GradientType=0);
-}
-
-.gradient-radial {
- background-color: #333333;
- background-image: -webkit-gradient(radial, center center, 0, center center, 460, from(#555555), to(#333333));
- background-image: -webkit-radial-gradient(circle, #555555, #333333);
- background-image: -moz-radial-gradient(circle, #555555, #333333);
- background-image: -o-radial-gradient(circle, #555555, #333333);
- background-repeat: no-repeat;
-}
-
-.gradient-striped {
- background-color: #555555;
- background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
- background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
- background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
- background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
- background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-}
-
-.gradient-horizontal-three {
- background-color: #00b3ee;
- background-image: -webkit-gradient(left, linear, 0 0, 0 100%, from(#00b3ee), color-stop(50%, #7a43b6), to(#c3325f));
- background-image: -webkit-linear-gradient(left, #00b3ee, #7a43b6 50%, #c3325f);
- background-image: -moz-linear-gradient(left, #00b3ee, #7a43b6 50%, #c3325f);
- background-image: -o-linear-gradient(left, #00b3ee, #7a43b6 50%, #c3325f);
- background-image: linear-gradient(to right, #00b3ee, #7a43b6 50%, #c3325f);
- background-repeat: no-repeat;
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00b3ee', endColorstr='#c3325f', GradientType=0);
-}
diff --git a/ckan/public-bs2/base/vendor/bootstrap/less/tests/css-tests.html b/ckan/public-bs2/base/vendor/bootstrap/less/tests/css-tests.html
deleted file mode 100755
--- a/ckan/public-bs2/base/vendor/bootstrap/less/tests/css-tests.html
+++ /dev/null
@@ -1,1399 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>CSS Tests · Twitter Bootstrap</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="">
- <meta name="author" content="">
-
- <!-- Le styles -->
- <link href="../../docs/assets/css/bootstrap.css" rel="stylesheet">
- <link href="../../docs/assets/css/bootstrap-responsive.css" rel="stylesheet">
- <link href="../../docs/assets/css/docs.css" rel="stylesheet">
- <link href="../../docs/assets/js/google-code-prettify/prettify.css" rel="stylesheet">
-
- <!-- CSS just for the tests page -->
- <link href="css-tests.css" rel="stylesheet">
-
- <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
- <!--[if lt IE 9]>
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
- <![endif]-->
-
- <!-- Le fav and touch icons -->
- <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../docs/assets/ico/apple-touch-icon-144-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../docs/assets/ico/apple-touch-icon-114-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../docs/assets/ico/apple-touch-icon-72-precomposed.png">
- <link rel="apple-touch-icon-precomposed" href="../../docs/assets/ico/apple-touch-icon-57-precomposed.png">
- <link rel="shortcut icon" href="../../docs/assets/ico/favicon.png">
- </head>
-
- <body>
-
-
- <!-- Navbar
- ================================================== -->
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="navbar-inner">
- <div class="container">
- <a class="brand" href="../../docs/index.html">Bootstrap</a>
- </div>
- </div>
- </div>
-
-
-<!-- Masthead
-================================================== -->
-<header class="jumbotron subhead" id="overview">
- <div class="container">
- <h1>CSS Tests</h1>
- <p class="lead">One stop shop for quick debugging and edge-case tests of CSS.</p>
- </div>
-</header>
-
-
-<div class="bs-docs-canvas">
-
- <div class="container">
-
-
-
-<!-- Typography
-================================================== -->
-
-<div class="page-header">
- <h1>Typography</h1>
-</div>
-
-<div class="row">
- <div class="span6">
- <div class="type-test">
- <h1>h1. Heading 1</h1>
- <h2>h2. Heading 2</h2>
- <h3>h3. Heading 3</h3>
- <h4>h4. Heading 4</h4>
- <h5>h5. Heading 5</h5>
- <h6>h6. Heading 6</h6>
- <p>Sed posuere consectetur est at lobortis. Maecenas sed diam eget risus varius blandit sit amet non magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
- </div>
- </div>
- <div class="span6">
- <div class="type-test">
- <h1>h1. Heading 1</h1>
- <p>Sed posuere consectetur est at lobortis. Maecenas sed diam eget risus varius blandit sit amet non magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
- <h2>h2. Heading 2</h2>
- <p>Sed posuere consectetur est at lobortis. Maecenas sed diam eget risus varius blandit sit amet non magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
- <h3>h3. Heading 3</h3>
- <p>Sed posuere consectetur est at lobortis. Maecenas sed diam eget risus varius blandit sit amet non magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
- <h4>h4. Heading 4</h4>
- <p>Sed posuere consectetur est at lobortis. Maecenas sed diam eget risus varius blandit sit amet non magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
- <h5>h5. Heading 5</h5>
- <p>Sed posuere consectetur est at lobortis. Maecenas sed diam eget risus varius blandit sit amet non magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
- <h6>h6. Heading 6</h6>
- <p>Sed posuere consectetur est at lobortis. Maecenas sed diam eget risus varius blandit sit amet non magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
- </div>
- </div>
-</div>
-
-
-
-<!-- Responsive images
-================================================== -->
-
-<div class="page-header">
- <h1>Responsive images</h1>
-</div>
-
-<div class="row">
- <div class="span4">
- <img data-src="holder.js/600x600" height="200">
- </div>
- <div class="span4">
- <img data-src="holder.js/600x600">
- </div>
- <div class="span4">
- <img data-src="holder.js/600x600">
- </div>
-</div>
-
-<br>
-
-<div class="row">
- <div class="span4">
- <img data-src="holder.js/600x900" style="width: 200px;">
- </div>
- <div class="span4">
- <img data-src="holder.js/200x300">
- </div>
- <div class="span4">
- <img data-src="holder.js/600x600">
- </div>
-</div>
-
-<br><br>
-
-
-
-
-<!-- Fluid grid
-================================================== -->
-
-<div class="page-header">
- <h1>Fluid grids</h1>
-</div>
-
-<div class="fluid-grid">
- <div class="row">
- <div class="span12">12
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="span11">11
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- <div class="span1">1
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="span10">10
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- <div class="span2">2
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="span9">9
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- <div class="span3">3
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="span8">8
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- <div class="span4">4
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="span7">7
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- <div class="span5">5
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="span6">6
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- <div class="span6">6
- <div class="row-fluid">
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- <div class="span1">1</div>
- </div>
- </div>
- </div>
-</div> <!-- fluid grids -->
-
-
-
-<!-- Tables
-================================================== -->
-
-<div class="page-header">
- <h1>Tables</h1>
-</div>
-
-<div class="row">
- <div class="span6">
- <h4>Bordered without thead</h4>
- <table class="table table-bordered">
- <tbody>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- </tbody>
- </table>
- <h4>Bordered without thead, with caption</h4>
- <table class="table table-bordered">
- <caption>Table caption</caption>
- <tbody>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- </tbody>
- </table>
- <h4>Bordered without thead, with colgroup</h4>
- <table class="table table-bordered">
- <colgroup>
- <col class="col1">
- <col class="col2">
- <col class="col3">
- </colgroup>
- <tbody>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- </tbody>
- <tfoot>
- <tr>
- <td>3</td>
- <td>6</td>
- <td>9</td>
- </tr>
- </tfoot>
- </table>
- <h4>Bordered with thead, with colgroup</h4>
- <table class="table table-bordered">
- <colgroup>
- <col class="col1">
- <col class="col2">
- <col class="col3">
- </colgroup>
- <thead>
- <tr>
- <th>A</th>
- <th>B</th>
- <th>C</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- </tbody>
- <tfoot>
- <tr>
- <td>3</td>
- <td>6</td>
- <td>9</td>
- </tr>
- </tfoot>
- </table>
- </div><!--/span-->
- <div class="span6">
- <h4>Bordered with thead and caption</h4>
- <table class="table table-bordered">
- <caption>Table caption</caption>
- <thead>
- <tr>
- <th>1</th>
- <th>2</th>
- <th>3</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td>2</td>
- <td>3</td>
- </tr>
- </tbody>
- <tfoot>
- <tr>
- <td>3</td>
- <td>6</td>
- <td>9</td>
- </tr>
- </tfoot>
- </table>
- <h4>Bordered with rowspan and colspan</h4>
- <table class="table table-bordered">
- <thead>
- <tr>
- <th>1</th>
- <th>2</th>
- <th>3</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td colspan="2">1 and 2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td rowspan="2">2</td>
- <td>3</td>
- </tr>
- <tr>
- <td rowspan="2">1</td>
- <td>3</td>
- </tr>
- <tr>
- <td colspan="2">2 and 3</td>
- </tr>
- </tbody>
- </table>
- </div><!--/span-->
-</div><!--/row-->
-
-
-<h4>Grid sizing</h4>
-<div class="row">
- <div class="span12">
- <table class="table table-bordered">
- <thead>
- <tr>
- <th class="span3">1</th>
- <th class="span4">2</th>
- <th>3</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td colspan="2">1 and 2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td rowspan="2">2</td>
- <td>3</td>
- </tr>
- <tr>
- <td rowspan="2">1</td>
- <td>3</td>
- </tr>
- <tr>
- <td colspan="2">2 and 3</td>
- </tr>
- </tbody>
- </table>
- </div>
-</div><!--/row-->
-
-<h4>Nesting and striping</h4>
-<table class="table table-bordered table-striped">
- <thead>
- <tr>
- <th>Test</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>
- <table class="table table-bordered table-striped">
- <thead>
- <tr>
- <th>Test</th>
- <th>Test</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>
- test
- </td>
- <td>
- test
- </td>
- </tr>
- <tr>
- <td>
- test
- </td>
- <td>
- test
- </td>
- </tr>
- <tr>
- <td>
- test
- </td>
- <td>
- test
- </td>
- </tr>
- </tbody>
- </table>
- </td>
- </tr>
- </tbody>
-</table>
-
-<h4>Fluid grid sizing</h4>
-<div class="row-fluid">
- <div class="span12">
- <table class="table table-bordered">
- <thead>
- <tr>
- <th class="span3">1</th>
- <th class="span4">2</th>
- <th>3</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td colspan="2">1 and 2</td>
- <td>3</td>
- </tr>
- <tr>
- <td>1</td>
- <td rowspan="2">2</td>
- <td>3</td>
- </tr>
- <tr>
- <td rowspan="2">1</td>
- <td>3</td>
- </tr>
- <tr>
- <td colspan="2">2 and 3</td>
- </tr>
- </tbody>
- </table>
- </div>
-</div><!--/row-->
-
-
-
-<!-- Forms
-================================================== -->
-
-<div class="page-header">
- <h1>Forms</h1>
-</div>
-
-<h4>Buttons and button groups</h4>
-<form class="form-inline">
- <button class="btn btn-success">Save</button>
- <button class="btn btn-info">Add new</button>
- <div class="btn-group">
- <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
- <i class="fa fa-user"></i> User
- <span class="caret"></span>
- </a>
- <ul class="dropdown-menu">
- <li><a href="#">Profile</a></li>
- <li class="divider"></li>
- <li><a href="#">Sign Out</a></li>
- </ul>
- </div>
-</form>
-
-<h4>Horizontal form errors</h4>
-<form class="form-horizontal">
- <div class="control-group error">
- <label class="control-label" for="inputError">Radio with error</label>
- <div class="controls">
- <label class="radio">
- <input type="radio" id="inputError"> Oh hai
- </label>
- <span class="help-inline">Please correct the error</span>
- </div>
- </div>
-</form>
-
-<div class="row">
- <div class="span4">
- <h4>Prepend and append on inputs</h4>
- <form>
- <div class="controls">
- <div class="input-prepend">
- <span class="add-on">@</span>
- <input class="span2" id="prependedInput" size="16" type="text">
- </div>
- </div>
- <div class="controls">
- <div class="input-append">
- <input class="span2" id="prependedInput" size="16" type="text">
- <span class="add-on">@</span>
- </div>
- </div>
- <div class="controls">
- <div class="input-prepend input-append">
- <span class="add-on">$</span>
- <input class="span2" id="prependedInput" size="16" type="text">
- <span class="add-on">.00</span>
- </div>
- </div>
- </form>
- </div><!--/span-->
- <div class="span4">
- <h4>Prepend and append with uneditable</h4>
- <form>
- <div class="input-prepend">
- <span class="add-on">$</span>
- <span class="span2 uneditable-input">Some value here</span>
- </div>
- <div class="input-append">
- <span class="span2 uneditable-input">Some value here</span>
- <span class="add-on">.00</span>
- </div>
- <div class="input-prepend input-append">
- <span class="add-on">$</span>
- <span class="span2 uneditable-input">Some value here</span>
- <span class="add-on">.00</span>
- </div>
- </form>
- </div><!--/span-->
- <div class="span4">
- <h4>Prepend with type="submit"</h4>
- <form class="form-search">
- <div class="input-append">
- <input type="text" class="span2 search-query" value="" name="q">
- <input type="submit" value="Search" class="btn">
- </div>
- </form>
- <div class="input-append">
- <input type="text" class="span2" value="" name="">
- <input type="submit" value="Button" class="btn">
- </div>
- <div class="input-append">
- <input type="text" size="16" id="appendedInputButtons" class="span2">
- <input type="submit" value="Search" class="btn">
- <button type="button" class="btn">Options</button>
- </div>
- </div><!--/span-->
-</div><!--/row-->
-
-<h4>Fluid prepended and appended inputs</h4>
-<div class="row-fluid">
- <div class="span6">
- <form>
- <div class="controls">
- <div class="input-prepend">
- <span class="add-on">@</span><input class="span2" id="prependedInput" size="16" type="text">
- </div>
- </div>
- <div class="controls">
- <div class="input-append">
- <input class="span2" id="prependedInput" size="16" type="text"><span class="add-on">@</span>
- </div>
- </div>
- <div class="controls">
- <div class="input-prepend input-append">
- <span class="add-on">$</span><input class="span2" id="prependedInput" size="16" type="text"><span class="add-on">.00</span>
- </div>
- </div>
- </form>
- </div>
-</div>
-
-<h4>Fixed row with inputs</h4>
-<p>Inputs should not extend past the light red background, set on their parent, a <code>.span*</code> column.</p>
-
-<div class="rowInputs">
- <div class="row">
- <div class="span12">
- <input type="text" class="span1" placeholder="span1">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row">
- <div class="span12">
- <input type="text" class="span2" placeholder="span2">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row">
- <div class="span12">
- <input type="text" class="span3" placeholder="span3">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row">
- <div class="span12">
- <input type="text" class="span4" placeholder="span4">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row">
- <div class="span12">
- <input type="text" class="span5" placeholder="span5">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row">
- <div class="span12">
- <input type="text" class="span6" placeholder="span6">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row">
- <div class="span12">
- <input type="text" class="span7" placeholder="span7">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row">
- <div class="span12">
- <input type="text" class="span8" placeholder="span8">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row">
- <div class="span12">
- <input type="text" class="span9" placeholder="span9">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row">
- <div class="span12">
- <input type="text" class="span10" placeholder="span10">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row">
- <div class="span12">
- <input type="text" class="span11" placeholder="span11">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row">
- <div class="span12">
- <input type="text" class="span12" placeholder="span12">
- </div><!--/span-->
- </div><!--/row-->
-</div>
-<br>
-
-<h4>Fluid row with inputs</h4>
-<p>Inputs should not extend past the light red background, set on their parent, a <code>.span*</code> column.</p>
-<div id="fluidRowInputs">
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span1" placeholder="span1">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span2" placeholder="span2">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span3" placeholder="span3">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span4" placeholder="span4">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span5" placeholder="span5">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span6" placeholder="span6">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span7" placeholder="span7">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span8" placeholder="span8">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span9" placeholder="span9">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span10" placeholder="span10">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span11" placeholder="span11">
- </div><!--/span-->
- </div><!--/row-->
- <div class="row-fluid">
- <div class="span12">
- <input type="text" class="span12" placeholder="span12">
- </div><!--/span-->
- </div><!--/row-->
-</div>
-
-<br>
-
-<h4>Inline form in fluid row</h4>
-
-<div class="row-fluid">
- <div class="span12">
- <form class="form-inline">
- <input type="text" class="span3" placeholder="Email">
- <input type="password" class="span3" placeholder="Password">
- <label class="checkbox">
- <input type="checkbox"> Remember me
- </label>
- <button type="submit" class="btn">Sign in</button>
- </form>
- </div>
-</div>
-
-
-<br>
-
-
-<h4>Fluid textarea at .span12</h4>
-<div class="row-fluid">
- <div class="span12">
- <textarea class="span12"></textarea>
- </div>
-</div>
-
-
-<br>
-
-
-<h4>Selects</h4>
-<form>
- <select class="span4">
- <option>Option</option>
- </select>
-</form>
-
-
-<br>
-
-
-
-
-<!-- Dropdowns
-================================================== -->
-
-<div class="page-header">
- <h1>Dropdowns</h1>
-</div>
-
-<h4>Dropdown link with hash URL</h4>
-<ul class="nav nav-pills">
- <li class="active"><a href="#">Link</a></li>
- <li><a href="#">Example link</a></li>
- <li class="dropdown">
- <a class="dropdown-toggle" data-toggle="dropdown" href="#">
- Dropdown <span class="caret"></span>
- </a>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li><a href="#">Separated link</a></li>
- </ul>
- </li>
-</ul>
-
-<h4>Dropdown link with custom URL and data-target</h4>
-<ul class="nav nav-pills">
- <li class="active"><a href="#">Link</a></li>
- <li><a href="#">Example link</a></li>
- <li class="dropdown">
- <a class="dropdown-toggle" data-toggle="dropdown" data-target="#" href="path/to/page.html">
- Dropdown <span class="caret"></span>
- </a>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li><a href="#">Separated link</a></li>
- </ul>
- </li>
-</ul>
-
-<h4>Dropdown on a button</h4>
-<div style="position: relative;">
- <button class="btn" type="button" data-toggle="dropdown">Dropdown <span class="caret"></span></button>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li><a href="#">Separated link</a></li>
- </ul>
-</div>
-
-<br>
-
-
-<!-- Thumbnails
-================================================== -->
-
-<div class="page-header">
- <h1>Thumbnails</h1>
-</div>
-
-<h4>Default thumbnails (no grid sizing)</h4>
-<ul class="thumbnails">
- <li class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </li>
- <li class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </li>
- <li class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </li>
- <li class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </li>
-</ul>
-
-<!-- NOT CURRENTLY SUPPORTED
-<h4>Offset thumbnails</h4>
-<ul class="thumbnails">
- <li class="span3 offset3">
- <a href="#" class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </a>
- </li>
- <li class="span3">
- <a href="#" class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </a>
- </li>
- <li class="span3">
- <a href="#" class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </a>
- </li>
-</ul>
--->
-
-<h4>Standard grid sizing</h4>
-<ul class="thumbnails">
- <li class="span3">
- <a href="#" class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </a>
- </li>
- <li class="span3 offset3">
- <a href="#" class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </a>
- </li>
- <li class="span3">
- <a href="#" class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </a>
- </li>
-</ul>
-
-<h4>Fluid thumbnails</h4>
-<div class="row-fluid">
- <div class="span8">
- <ul class="thumbnails">
- <li class="span4">
- <a href="#" class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </a>
- </li>
- <li class="span4">
- <a href="#" class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </a>
- </li>
- <li class="span4">
- <a href="#" class="thumbnail">
- <img data-src="holder.js/260x180" alt="">
- </a>
- </li>
- </ul>
- </div>
-</div>
-
-
-
-<!-- Tabs
-================================================== -->
-
-<div class="page-header">
- <h1>Tabs</h1>
-</div>
-
-<div class="tabbable tabs-left" style="margin-bottom: 18px;">
- <ul class="nav nav-tabs">
- <li class="active"><a href="#tab1" data-toggle="tab">Section 1</a></li>
- <li><a href="#tab2" data-toggle="tab">Section 2</a></li>
- <li><a href="#tab3" data-toggle="tab">Section 3</a></li>
- </ul>
- <div class="tab-content" style="padding-bottom: 9px; border-bottom: 1px solid #ddd;">
- <div class="tab-pane active" id="tab1">
- <p>I'm in Section 1.</p>
-
- <div class="tabbable" style="background: #f5f5f5; padding: 20px;">
- <ul class="nav nav-tabs">
- <li class="active"><a href="#tab1-1" data-toggle="tab">1.1</a></li>
- <li><a href="#tab1-2" data-toggle="tab">1.2</a></li>
- <li><a href="#tab1-3" data-toggle="tab">1.3</a></li>
- </ul>
- <div class="tab-content" style="padding-bottom: 9px; border-bottom: 1px solid #ddd;">
- <div class="tab-pane active" id="tab1-1">
- <p>I'm in Section 1.1.</p>
- </div>
- <div class="tab-pane" id="tab1-2">
- <p>I'm in Section 1.2.</p>
- </div>
- <div class="tab-pane" id="tab1-3">
- <p>I'm in Section 1.3.</p>
- </div>
- </div>
- </div>
- </div>
- <div class="tab-pane" id="tab2">
- <p>Howdy, I'm in Section 2.</p>
- </div>
- <div class="tab-pane" id="tab3">
- <p>What up girl, this is Section 3.</p>
- </div>
- </div>
-</div> <!-- /tabbable -->
-
-<br>
-
-
-<!-- Labels
-================================================== -->
-
-<div class="page-header">
- <h1>Labels</h1>
-</div>
-
-<div class="row">
- <div class="span4">
- <h4>Inline label</h4>
- <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Maecenas sed diam <span class="label label-warning">Label name</span> eget risus varius blandit sit amet non magna. Fusce <code>.class-name</code> dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
- </div><!--/span-->
- <div class="span4">
- <form class="form-horizontal">
- <label>Example label</label>
- <input type="text" placeholder="Input"> <span class="help-inline"><span class="label">Hey!</span> Read this.</span>
- </form>
- </div><!--/span-->
- <div class="span4">
- <button class="btn">Action <span class="badge">2</span></button>
- <button class="btn">Action <span class="label">2</span></button>
- </div><!--/span-->
-</div><!--/row-->
-
-<br>
-
-
-<!-- Button groups
-================================================== -->
-
-<div class="page-header">
- <h1>Buttons</h1>
-</div>
-
-<table class="table table-bordered">
- <tbody>
- <tr>
- <td>
- Maecenas faucibus mollis interdum. Nulla vitae elit libero, a pharetra augue. Donec ullamcorper nulla non metus auctor fringilla. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.
- </td>
- <td>
- <div class="btn-group">
- <button class="btn">1</button>
- <button class="btn">2</button>
- <button class="btn">3</button>
- <button class="btn">4</button>
- </div>
- </td>
- </tr>
- </tbody>
-</table>
-
-<h4>Mini buttons: text and icon</h4>
-<div class="btn-group">
- <button class="btn btn-mini">Button text</button>
- <button class="btn btn-mini"><i class="fa fa-cog"></i></button>
-</div>
-
-<br>
-
-
-
-<!-- Responsive utility classes
-================================================== -->
-
-<div class="page-header">
- <h1>Responsive utility classes</h1>
-</div>
-
-<h4>Visible on...</h4>
-<ul class="responsive-utilities-test visible-on">
- <li>Phone<span class="visible-phone">✔ Phone</span></li>
- <li>Tablet<span class="visible-tablet">✔ Tablet</span></li>
- <li>Desktop<span class="visible-desktop">✔ Desktop</span></li>
-</ul>
-<ul class="responsive-utilities-test visible-on">
- <li>Phone + Tablet<span class="visible-phone visible-tablet">✔ Phone + Tablet</span></li>
- <li>Tablet + Desktop<span class="visible-tablet visible-desktop">✔ Tablet + Desktop</span></li>
- <li>All<span class="visible-phone visible-tablet visible-desktop">✔ All</span></li>
-</ul>
-
-<h4>Hidden on...</h4>
-<ul class="responsive-utilities-test hidden-on">
- <li>Phone<span class="hidden-phone">✔ Phone</span></li>
- <li>Tablet<span class="hidden-tablet">✔ Tablet</span></li>
- <li>Desktop<span class="hidden-desktop">✔ Desktop</span></li>
-</ul>
-<ul class="responsive-utilities-test hidden-on">
- <li>Phone + Tablet<span class="hidden-phone hidden-tablet">✔ Phone + Tablet</span></li>
- <li>Tablet + Desktop<span class="hidden-tablet hidden-desktop">✔ Tablet + Desktop</span></li>
- <li>All<span class="hidden-phone hidden-tablet hidden-desktop">✔ All</span></li>
-</ul>
-
-
-
-<!-- Gradients
-================================================== -->
-
-<div class="page-header">
- <h1>Gradients</h1>
-</div>
-
-<h4>Horizontal</h4>
-<div class="gradient-horizontal"></div>
-
-<h4>Vertical</h4>
-<div class="gradient-vertical"></div>
-
-<h4>Directional</h4>
-<div class="gradient-directional"></div>
-
-<h4>Three colors</h4>
-<div class="gradient-vertical-three"></div>
-
-<h4>Radial</h4>
-<div class="gradient-radial"></div>
-
-<h4>Striped</h4>
-<div class="gradient-striped"></div>
-
-<h4>Horizontal three colors</h4>
-<div class="gradient-horizontal-three"></div>
-
-
-
-<div class="page-header">
- <h1>Alerts</h1>
-</div>
-
-<h4>Alert default</h4>
-<div class="alert">
- <button type="button" class="close" data-dismiss="alert">×</button>
- <strong>Alert!</strong> Best check yourself, you're not looking too good.
-</div>
-<div class="alert alert-block">
- <button type="button" class="close" data-dismiss="alert">×</button>
- <p><strong>Alert!</strong> Best check yourself, you're not looking too good.</p>
-</div>
-
-<h4>Success</h4>
-<div class="alert alert-success">
- <button type="button" class="close" data-dismiss="alert">×</button>
- <strong>Success!</strong> Best check yourself, you're not looking too good.
-</div>
-<div class="alert alert-block alert-success">
- <button type="button" class="close" data-dismiss="alert">×</button>
- <p><strong>Success!</strong> Best check yourself, you're not looking too good.</p>
-</div>
-
-<h4>Info</h4>
-<div class="alert alert-info">
- <button type="button" class="close" data-dismiss="alert">×</button>
- <strong>Info!</strong> Best check yourself, you're not looking too good.
-</div>
-<div class="alert alert-block alert-info">
- <button type="button" class="close" data-dismiss="alert">×</button>
- <p><strong>Info!</strong> Best check yourself, you're not looking too good.</p>
-</div>
-
-<h4>Warning</h4>
-<div class="alert ">
- <button type="button" class="close" data-dismiss="alert">×</button>
- <strong>Warning!</strong> Best check yourself, you're not looking too good.
-</div>
-<div class="alert alert-block alert-warning">
- <button type="button" class="close" data-dismiss="alert">×</button>
- <p><strong>Warning!</strong> Best check yourself, you're not looking too good.</p>
-</div>
-
-<h4>Error</h4>
-<div class="alert alert-error">
- <button type="button" class="close" data-dismiss="alert">×</button>
- <strong>Error!</strong> Best check yourself, you're not looking too good.
-</div>
-<div class="alert alert-block alert-error">
- <button type="button" class="close" data-dismiss="alert">×</button>
- <p><strong>Error!</strong> Best check yourself, you're not looking too good.</p>
-</div>
-
-
- </div><!-- /container -->
-
-
-
- <!-- Footer
- ================================================== -->
- <footer class="footer">
- <div class="container">
- <p class="pull-right"><a href="#">Back to top</a></p>
- <p>Designed and built with all the love in the world <a href="http://twitter.com/twitter" target="_blank">@twitter</a> by <a href="http://twitter.com/mdo" target="_blank">@mdo</a> and <a href="http://twitter.com/fat" target="_blank">@fat</a>.</p>
- <p>Code licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0" target="_blank">Apache License v2.0</a>. Documentation licensed under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>.</p>
- <p>Icons from <a href="http://glyphicons.com">Glyphicons Free</a>, licensed under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>.</p>
- <ul class="footer-links">
- <li><a href="http://blog.getbootstrap.com">Read the blog</a></li>
- <li><a href="https://github.com/twitter/bootstrap/issues?state=open">Submit issues</a></li>
- <li><a href="https://github.com/twitter/bootstrap/wiki">Roadmap and changelog</a></li>
- </ul>
- </div>
- </footer>
-
-</div>
-
-
- <!-- Le javascript
- ================================================== -->
- <!-- Placed at the end of the document so the pages load faster -->
- <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
- <script src="../../docs/assets/js/jquery.js"></script>
- <script src="../../docs/assets/js/google-code-prettify/prettify.js"></script>
- <script src="../../docs/assets/js/bootstrap-transition.js"></script>
- <script src="../../docs/assets/js/bootstrap-alert.js"></script>
- <script src="../../docs/assets/js/bootstrap-modal.js"></script>
- <script src="../../docs/assets/js/bootstrap-dropdown.js"></script>
- <script src="../../docs/assets/js/bootstrap-scrollspy.js"></script>
- <script src="../../docs/assets/js/bootstrap-tab.js"></script>
- <script src="../../docs/assets/js/bootstrap-tooltip.js"></script>
- <script src="../../docs/assets/js/bootstrap-popover.js"></script>
- <script src="../../docs/assets/js/bootstrap-button.js"></script>
- <script src="../../docs/assets/js/bootstrap-collapse.js"></script>
- <script src="../../docs/assets/js/bootstrap-carousel.js"></script>
- <script src="../../docs/assets/js/bootstrap-typeahead.js"></script>
- <script src="../../docs/assets/js/application.js"></script>
-
-
- </body>
-</html>
diff --git a/ckan/public-bs2/base/vendor/bootstrap/less/tests/forms-responsive.html b/ckan/public-bs2/base/vendor/bootstrap/less/tests/forms-responsive.html
deleted file mode 100755
--- a/ckan/public-bs2/base/vendor/bootstrap/less/tests/forms-responsive.html
+++ /dev/null
@@ -1,71 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Bootstrap, from Twitter</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="">
- <meta name="author" content="">
-
- <!-- Le styles -->
- <link href="../../docs/assets/css/bootstrap.css" rel="stylesheet">
- <link href="../../docs/assets/css/bootstrap-responsive.css" rel="stylesheet">
- <style>
- body {
- padding-top: 30px;
- padding-bottom: 30px;
- }
- </style>
-
- <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
- <!--[if lt IE 9]>
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
- <![endif]-->
-
- <!-- Le fav and touch icons -->
- <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../docs/assets/ico/apple-touch-icon-144-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../docs/assets/ico/apple-touch-icon-114-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../docs/assets/ico/apple-touch-icon-72-precomposed.png">
- <link rel="apple-touch-icon-precomposed" href="../../docs/assets/ico/apple-touch-icon-57-precomposed.png">
- <link rel="shortcut icon" href="../../docs/assets/ico/favicon.png">
- </head>
-
- <body>
-
- <form class="container">
-
- <div class="page-header">
- <h1>Fixed grid</h1>
- </div>
-
- <h3>Vertical alignment</h3>
- <input type="text" class="span2" placeholder="span2">
- <select class="span2"><option>span2</option></select>
- <span class="uneditable-input span2">span1</span>
-
- <h3>Width across elements</h3>
- <div>
- <input type="text" class="span2" placeholder="span2">
- </div>
- <div>
- <select class="span2"><option>span2</option></select>
- </div>
- <div>
- <span class="uneditable-input span2">span2</span>
- </div>
-
-
- <div class="page-header">
- <h1>Fluid grid</h1>
- </div>
-
- <div class="row-fluid">
- <input type="text" class="span2" placeholder="span2">
- <select class="span2"><option>span2</option></select>
- <span class="uneditable-input span2">span1</span>
- </div>
-
- </form> <!-- /container -->
-
- </body>
-</html>
diff --git a/ckan/public-bs2/base/vendor/bootstrap/less/tests/forms.html b/ckan/public-bs2/base/vendor/bootstrap/less/tests/forms.html
deleted file mode 100755
--- a/ckan/public-bs2/base/vendor/bootstrap/less/tests/forms.html
+++ /dev/null
@@ -1,179 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Bootstrap, from Twitter</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="">
- <meta name="author" content="">
-
- <!-- Le styles -->
- <link href="../../docs/assets/css/bootstrap.css" rel="stylesheet">
- <link href="../../docs/assets/css/bootstrap-responsive.css" rel="stylesheet">
- <style>
- body {
- padding-top: 30px;
- padding-bottom: 30px;
- }
- </style>
-
- <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
- <!--[if lt IE 9]>
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
- <![endif]-->
-
- <!-- Le fav and touch icons -->
- <link rel="shortcut icon" href="../../docs/assets/ico/favicon.ico">
- <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../docs/assets/ico/apple-touch-icon-144-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../docs/assets/ico/apple-touch-icon-114-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../docs/assets/ico/apple-touch-icon-72-precomposed.png">
- <link rel="apple-touch-icon-precomposed" href="../../docs/assets/ico/apple-touch-icon-57-precomposed.png">
- </head>
-
- <body>
-
- <form class="container">
-
- <div class="page-header">
- <h1>Form controls</h1>
- </div>
-
- <div class="row">
- <div class="span4">
-
- <label>Select</label>
- <select>
- <option>Select</option>
- <option>Option 2</option>
- <option>Option 3</option>
- </select>
-
- <hr>
-
- <label>textarea</label>
- <textarea>Textarea</textarea>
-
- <hr>
-
- <label>text</label>
- <input type="text" value="Text input">
-
- <hr>
-
- <label>password</label>
- <input type="password" value="Password input">
-
- <hr>
-
- <label>checkbox</label>
- <input type="checkbox" value="">
-
- <hr>
-
- <label>radio</label>
- <input type="radio" value="">
-
- <hr>
-
- <label>button</label>
- <input type="button" value="Button">
-
- <hr>
-
- <label>submit</label>
- <input type="submit" value="Submit">
-
- <hr>
-
- <label>reset</label>
- <input type="reset" value="Reset">
-
- </div><!-- /span4 -->
- <div class="span4">
-
- <label>file</label>
- <input type="file" value="">
-
- <hr>
-
- <label>hidden</label>
- <input type="hidden" value="hidden">
-
- <hr>
-
- <label>image</label>
- <input type="image" value="">
-
- <hr>
-
- <label>datetime</label>
- <input type="datetime" value="">
-
- <hr>
-
- <label>datetime-local</label>
- <input type="datetime-local" value="">
-
- <hr>
-
- <label>date</label>
- <input type="date" value="">
-
- <hr>
-
- <label>month</label>
- <input type="month" value="">
-
- <hr>
-
- <label>time</label>
- <input type="time" value="">
-
- <hr>
-
- <label>week</label>
- <input type="week" value="">
-
- </div><!-- /span4 -->
- <div class="span4">
-
- <label>number</label>
- <input type="number" value="">
-
- <hr>
-
- <label>range</label>
- <input type="range" value="">
-
- <hr>
-
- <label>email</label>
- <input type="email" value="">
-
- <hr>
-
- <label>url</label>
- <input type="url" value="">
-
- <hr>
-
- <label>search</label>
- <input type="search" value="">
-
- <hr>
-
- <label>tel</label>
- <input type="tel" value="">
-
- <hr>
-
- <label>color</label>
- <input type="color" value="">
-
- </div><!-- /span4 -->
- </div><!-- /row -->
-
- </form> <!-- /container -->
-
- </body>
-</html>
diff --git a/ckan/public-bs2/base/vendor/bootstrap/less/tests/navbar-fixed-top.html b/ckan/public-bs2/base/vendor/bootstrap/less/tests/navbar-fixed-top.html
deleted file mode 100755
--- a/ckan/public-bs2/base/vendor/bootstrap/less/tests/navbar-fixed-top.html
+++ /dev/null
@@ -1,104 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Bootstrap, from Twitter</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="">
- <meta name="author" content="">
-
- <!-- Le styles -->
- <link href="../../docs/assets/css/bootstrap.css" rel="stylesheet">
- <style>
- body {
- padding-top: 60px;
- padding-bottom: 30px;
- }
- </style>
- <link href="../../docs/assets/css/bootstrap-responsive.css" rel="stylesheet">
-
- <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
- <!--[if lt IE 9]>
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
- <![endif]-->
-
- <!-- Le fav and touch icons -->
- <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../docs/assets/ico/apple-touch-icon-144-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../docs/assets/ico/apple-touch-icon-114-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../docs/assets/ico/apple-touch-icon-72-precomposed.png">
- <link rel="apple-touch-icon-precomposed" href="../../docs/assets/ico/apple-touch-icon-57-precomposed.png">
- <link rel="shortcut icon" href="../../docs/assets/ico/favicon.png">
- </head>
-
- <body>
-
- <!-- Fixed navbar -->
- <div class="navbar navbar-fixed-top">
- <div class="navbar-inner">
- <div class="container">
- <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
- <span class="fa-bar"></span>
- <span class="fa-bar"></span>
- <span class="fa-bar"></span>
- </a>
- <a class="brand" href="#">Project name</a>
- <div class="nav-collapse collapse">
- <ul class="nav">
- <li class="active"><a href="#">Home</a></li>
- <li><a href="#about">About</a></li>
- <li><a href="#contact">Contact</a></li>
- <li class="dropdown">
- <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li class="nav-header">Nav header</li>
- <li><a href="#">Separated link</a></li>
- <li><a href="#">One more separated link</a></li>
- </ul>
- </li>
- </ul>
- <ul class="nav pull-right">
- <li><a href="./navbar.html">Default</a></li>
- <li><a href="./navbar-static-top.html">Static top</a></li>
- <li class="active"><a href="./navbar-fixed-top.html">Fixed top</a></li>
- </ul>
- </div><!--/.nav-collapse -->
- </div>
- </div>
- </div>
-
- <div class="container">
-
- <!-- Main hero unit for a primary marketing message or call to action -->
- <div class="hero-unit">
- <h1>Navbar example</h1>
- <p>This example is a quick exercise to illustrate how the default, static navbar and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.</p>
- <p>
- <a class="btn btn-large btn-primary" href="../components.html#navbar">View navbar docs »</a>
- </p>
- </div>
-
- </div> <!-- /container -->
-
- <!-- Le javascript
- ================================================== -->
- <!-- Placed at the end of the document so the pages load faster -->
- <script src="../../docs/assets/js/jquery.js"></script>
- <script src="../../docs/assets/js/bootstrap-transition.js"></script>
- <script src="../../docs/assets/js/bootstrap-alert.js"></script>
- <script src="../../docs/assets/js/bootstrap-modal.js"></script>
- <script src="../../docs/assets/js/bootstrap-dropdown.js"></script>
- <script src="../../docs/assets/js/bootstrap-scrollspy.js"></script>
- <script src="../../docs/assets/js/bootstrap-tab.js"></script>
- <script src="../../docs/assets/js/bootstrap-tooltip.js"></script>
- <script src="../../docs/assets/js/bootstrap-popover.js"></script>
- <script src="../../docs/assets/js/bootstrap-button.js"></script>
- <script src="../../docs/assets/js/bootstrap-collapse.js"></script>
- <script src="../../docs/assets/js/bootstrap-carousel.js"></script>
- <script src="../../docs/assets/js/bootstrap-typeahead.js"></script>
-
- </body>
-</html>
diff --git a/ckan/public-bs2/base/vendor/bootstrap/less/tests/navbar-static-top.html b/ckan/public-bs2/base/vendor/bootstrap/less/tests/navbar-static-top.html
deleted file mode 100755
--- a/ckan/public-bs2/base/vendor/bootstrap/less/tests/navbar-static-top.html
+++ /dev/null
@@ -1,107 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Bootstrap, from Twitter</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="">
- <meta name="author" content="">
-
- <!-- Le styles -->
- <link href="../../docs/assets/css/bootstrap.css" rel="stylesheet">
- <style>
- body {
- padding-bottom: 30px;
- }
- .hero-unit {
- margin-top: 20px;
- }
- </style>
- <link href="../../docs/assets/css/bootstrap-responsive.css" rel="stylesheet">
-
- <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
- <!--[if lt IE 9]>
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
- <![endif]-->
-
- <!-- Le fav and touch icons -->
- <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../docs/assets/ico/apple-touch-icon-144-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../docs/assets/ico/apple-touch-icon-114-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../docs/assets/ico/apple-touch-icon-72-precomposed.png">
- <link rel="apple-touch-icon-precomposed" href="../../docs/assets/ico/apple-touch-icon-57-precomposed.png">
- <link rel="shortcut icon" href="../../docs/assets/ico/favicon.png">
- </head>
-
- <body>
-
- <!-- Static navbar -->
- <div class="navbar navbar-static-top">
- <div class="navbar-inner">
- <div class="container">
- <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
- <span class="fa-bar"></span>
- <span class="fa-bar"></span>
- <span class="fa-bar"></span>
- </a>
- <a class="brand" href="#">Project name</a>
- <div class="nav-collapse collapse">
- <ul class="nav">
- <li class="active"><a href="#">Home</a></li>
- <li><a href="#about">About</a></li>
- <li><a href="#contact">Contact</a></li>
- <li class="dropdown">
- <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li class="nav-header">Nav header</li>
- <li><a href="#">Separated link</a></li>
- <li><a href="#">One more separated link</a></li>
- </ul>
- </li>
- </ul>
- <ul class="nav pull-right">
- <li><a href="./navbar.html">Default</a></li>
- <li class="active"><a href="./navbar-static-top.html">Static top</a></li>
- <li><a href="./navbar-fixed-top.html">Fixed top</a></li>
- </ul>
- </div><!--/.nav-collapse -->
- </div>
- </div>
- </div>
-
-
- <div class="container">
-
- <!-- Main hero unit for a primary marketing message or call to action -->
- <div class="hero-unit">
- <h1>Navbar example</h1>
- <p>This example is a quick exercise to illustrate how the default, static navbar and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.</p>
- <p>
- <a class="btn btn-large btn-primary" href="../components.html#navbar">View navbar docs »</a>
- </p>
- </div>
-
- </div> <!-- /container -->
-
- <!-- Le javascript
- ================================================== -->
- <!-- Placed at the end of the document so the pages load faster -->
- <script src="../../docs/assets/js/jquery.js"></script>
- <script src="../../docs/assets/js/bootstrap-transition.js"></script>
- <script src="../../docs/assets/js/bootstrap-alert.js"></script>
- <script src="../../docs/assets/js/bootstrap-modal.js"></script>
- <script src="../../docs/assets/js/bootstrap-dropdown.js"></script>
- <script src="../../docs/assets/js/bootstrap-scrollspy.js"></script>
- <script src="../../docs/assets/js/bootstrap-tab.js"></script>
- <script src="../../docs/assets/js/bootstrap-tooltip.js"></script>
- <script src="../../docs/assets/js/bootstrap-popover.js"></script>
- <script src="../../docs/assets/js/bootstrap-button.js"></script>
- <script src="../../docs/assets/js/bootstrap-collapse.js"></script>
- <script src="../../docs/assets/js/bootstrap-carousel.js"></script>
- <script src="../../docs/assets/js/bootstrap-typeahead.js"></script>
-
- </body>
-</html>
diff --git a/ckan/public-bs2/base/vendor/bootstrap/less/tests/navbar.html b/ckan/public-bs2/base/vendor/bootstrap/less/tests/navbar.html
deleted file mode 100755
--- a/ckan/public-bs2/base/vendor/bootstrap/less/tests/navbar.html
+++ /dev/null
@@ -1,107 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Bootstrap, from Twitter</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="">
- <meta name="author" content="">
-
- <!-- Le styles -->
- <link href="../../docs/assets/css/bootstrap.css" rel="stylesheet">
- <style>
- body {
- padding-top: 0;
- padding-bottom: 30px;
- }
- .navbar {
- margin-top: 20px;
- }
- </style>
- <link href="../../docs/assets/css/bootstrap-responsive.css" rel="stylesheet">
-
- <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
- <!--[if lt IE 9]>
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
- <![endif]-->
-
- <!-- Le fav and touch icons -->
- <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../docs/assets/ico/apple-touch-icon-144-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../docs/assets/ico/apple-touch-icon-114-precomposed.png">
- <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../docs/assets/ico/apple-touch-icon-72-precomposed.png">
- <link rel="apple-touch-icon-precomposed" href="../../docs/assets/ico/apple-touch-icon-57-precomposed.png">
- <link rel="shortcut icon" href="../../docs/assets/ico/favicon.png">
- </head>
-
- <body>
-
- <div class="container">
-
- <!-- Static navbar -->
- <div class="navbar">
- <div class="navbar-inner">
- <div class="container">
- <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
- <span class="fa-bar"></span>
- <span class="fa-bar"></span>
- <span class="fa-bar"></span>
- </a>
- <a class="brand" href="#">Project name</a>
- <div class="nav-collapse collapse">
- <ul class="nav">
- <li class="active"><a href="#">Home</a></li>
- <li><a href="#about">About</a></li>
- <li><a href="#contact">Contact</a></li>
- <li class="dropdown">
- <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
- <ul class="dropdown-menu">
- <li><a href="#">Action</a></li>
- <li><a href="#">Another action</a></li>
- <li><a href="#">Something else here</a></li>
- <li class="divider"></li>
- <li class="nav-header">Nav header</li>
- <li><a href="#">Separated link</a></li>
- <li><a href="#">One more separated link</a></li>
- </ul>
- </li>
- </ul>
- <ul class="nav pull-right">
- <li class="active"><a href="./navbar.html">Default</a></li>
- <li><a href="./navbar-static-top.html">Static top</a></li>
- <li><a href="./navbar-fixed-top.html">Fixed top</a></li>
- </ul>
- </div><!--/.nav-collapse -->
- </div>
- </div>
- </div>
-
- <!-- Main hero unit for a primary marketing message or call to action -->
- <div class="hero-unit">
- <h1>Navbar example</h1>
- <p>This example is a quick exercise to illustrate how the default, static navbar and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.</p>
- <p>
- <a class="btn btn-large btn-primary" href="../components.html#navbar">View navbar docs »</a>
- </p>
- </div>
-
- </div> <!-- /container -->
-
- <!-- Le javascript
- ================================================== -->
- <!-- Placed at the end of the document so the pages load faster -->
- <script src="../../docs/assets/js/jquery.js"></script>
- <script src="../../docs/assets/js/bootstrap-transition.js"></script>
- <script src="../../docs/assets/js/bootstrap-alert.js"></script>
- <script src="../../docs/assets/js/bootstrap-modal.js"></script>
- <script src="../../docs/assets/js/bootstrap-dropdown.js"></script>
- <script src="../../docs/assets/js/bootstrap-scrollspy.js"></script>
- <script src="../../docs/assets/js/bootstrap-tab.js"></script>
- <script src="../../docs/assets/js/bootstrap-tooltip.js"></script>
- <script src="../../docs/assets/js/bootstrap-popover.js"></script>
- <script src="../../docs/assets/js/bootstrap-button.js"></script>
- <script src="../../docs/assets/js/bootstrap-collapse.js"></script>
- <script src="../../docs/assets/js/bootstrap-carousel.js"></script>
- <script src="../../docs/assets/js/bootstrap-typeahead.js"></script>
-
- </body>
-</html>
diff --git a/ckan/templates-bs2/tests/broken_helper_as_attribute.html b/ckan/templates-bs2/tests/broken_helper_as_attribute.html
deleted file mode 100644
--- a/ckan/templates-bs2/tests/broken_helper_as_attribute.html
+++ /dev/null
@@ -1,5 +0,0 @@
-{% extends 'page.html' %}
-
-{% block page %}
- {{ h.not_here() }}
-{% endblock %}
diff --git a/ckan/templates-bs2/tests/broken_helper_as_item.html b/ckan/templates-bs2/tests/broken_helper_as_item.html
deleted file mode 100644
--- a/ckan/templates-bs2/tests/broken_helper_as_item.html
+++ /dev/null
@@ -1,5 +0,0 @@
-{% extends 'page.html' %}
-
-{% block page %}
- {{ h['not_here']() }}
-{% endblock %}
diff --git a/ckan/templates-bs2/tests/flash_messages.html b/ckan/templates-bs2/tests/flash_messages.html
deleted file mode 100644
--- a/ckan/templates-bs2/tests/flash_messages.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <title>Hello</title>
- </head>
- <body>
- Flash messages:
- {% for message in h.flash.pop_messages() | list %}
- <div>
- {{ message.category }}: {{ h.literal(message) }}
- </div>
- {% endfor %}
- </body>
-</html>
diff --git a/ckan/templates-bs2/tests/helper_as_attribute.html b/ckan/templates-bs2/tests/helper_as_attribute.html
deleted file mode 100644
--- a/ckan/templates-bs2/tests/helper_as_attribute.html
+++ /dev/null
@@ -1,5 +0,0 @@
-{% extends 'page.html' %}
-
-{% block page %}
- My lang is: {{ h.lang() }}
-{% endblock %}
diff --git a/ckan/templates-bs2/tests/helper_as_item.html b/ckan/templates-bs2/tests/helper_as_item.html
deleted file mode 100644
--- a/ckan/templates-bs2/tests/helper_as_item.html
+++ /dev/null
@@ -1,5 +0,0 @@
-{% extends 'page.html' %}
-
-{% block page %}
- My lang is: {{ h['lang']() }}
-{% endblock %}
diff --git a/ckan/templates-bs2/tests/mock_json_resource_preview_template.html b/ckan/templates-bs2/tests/mock_json_resource_preview_template.html
deleted file mode 100644
--- a/ckan/templates-bs2/tests/mock_json_resource_preview_template.html
+++ /dev/null
@@ -1,17 +0,0 @@
-{% extends 'dataviewer/base.html' %}
-
-{% block page %}
- <div>
- <pre data-module="mock-json-preview">
- <div class="loading">
- {{ _('Loading...') }}
- </div>
- </pre>
- </div>
-{% endblock %}
-
-{% block scripts %}
- {{ super() }}
-
- <script src="mock-json-preview.js"></script>
-{% endblock %}
diff --git a/ckan/templates-bs2/tests/mock_resource_preview_template.html b/ckan/templates-bs2/tests/mock_resource_preview_template.html
deleted file mode 100644
--- a/ckan/templates-bs2/tests/mock_resource_preview_template.html
+++ /dev/null
@@ -1,17 +0,0 @@
-{% extends 'dataviewer/base.html' %}
-
-{% block page %}
- <div>
- <pre data-module="mock-preview">
- <div class="loading">
- {{ _('Loading...') }}
- </div>
- </pre>
- </div>
-{% endblock %}
-
-{% block scripts %}
- {{ super() }}
-
- <script src="mock-preview.js"></script>
-{% endblock %}
| Remove Bootstrap 2 templates from master
They have been around (and will be) for the whole 2.8 release cycle, which should give users plenty of time to upgrade.
| 2019-05-10T13:21:13 |
|
ckan/ckan | 4,790 | ckan__ckan-4790 | [
"4823"
] | fb2cc3c264ffa6f3e2886e973501dc7edf94afc9 | diff --git a/ckan/views/dataset.py b/ckan/views/dataset.py
--- a/ckan/views/dataset.py
+++ b/ckan/views/dataset.py
@@ -84,13 +84,15 @@ def drill_down_url(alternative_url=None, **by):
def remove_field(package_type, key, value=None, replace=None):
+ if not package_type or package_type == u'dataset':
+ url = h.url_for(u'dataset.search')
+ else:
+ url = h.url_for(u'{0}_search'.format(package_type))
return h.remove_url_param(
key,
value=value,
replace=replace,
- controller=u'dataset',
- action=u'search',
- alternative_url=package_type
+ alternative_url=url
)
| After removing the tag the redirect web url is wrong and it causes an error
Hi, thanks for the wonderful CKAN. It makes me set up a open data portal very fast.
When I search the data by tags, it works very quickly.

But I am trying to remove the tags like the picture below

the redirect web url became` http://10.102.30.154:5000/en/dataset/dataset?tags=%E6%B5%8B%E8%AF%95`. The url has an extra `dataset`, which causes an error in the UI.


| 2019-05-22T14:14:55 |
||
ckan/ckan | 4,824 | ckan__ckan-4824 | [
"4722"
] | c8ac563191c0635b4590a686a8b6ecf6d62f9cef | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -505,7 +505,7 @@ def _local_url(url_to_amend, **kw):
default_locale = True
root = ''
- if kw.get('qualified', False):
+ if kw.get('qualified', False) or kw.get('_external', False):
# if qualified is given we want the full url ie http://...
protocol, host = get_site_protocol_and_host()
root = _routes_default_url_for('/',
| diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py
--- a/ckan/tests/lib/test_helpers.py
+++ b/ckan/tests/lib/test_helpers.py
@@ -226,18 +226,39 @@ def test_url_for_flask_route_new_syntax_external(self):
generated_url = h.url_for('api.get_api', ver=3, _external=True)
eq_(generated_url, url)
+ @helpers.change_config('ckan.site_url', 'http://example.com')
+ @helpers.change_config('ckan.root_path', '/{{LANG}}/data')
+ def test_url_for_flask_route_new_syntax_external_with_root_path(self):
+ url = 'http://example.com/data/api/3'
+ generated_url = h.url_for('api.get_api', ver=3, _external=True)
+ eq_(generated_url, url)
+
@helpers.change_config('ckan.site_url', 'http://example.com')
def test_url_for_flask_route_old_syntax_external(self):
url = 'http://example.com/api/3'
generated_url = h.url_for(controller='api', action='get_api', ver=3, _external=True)
eq_(generated_url, url)
+ @helpers.change_config('ckan.site_url', 'http://example.com')
+ @helpers.change_config('ckan.root_path', '/{{LANG}}/data')
+ def test_url_for_flask_route_old_syntax_external_with_root_path(self):
+ url = 'http://example.com/data/api/3'
+ generated_url = h.url_for(controller='api', action='get_api', ver=3, _external=True)
+ eq_(generated_url, url)
+
@helpers.change_config('ckan.site_url', 'http://example.com')
def test_url_for_flask_route_old_syntax_qualified(self):
url = 'http://example.com/api/3'
generated_url = h.url_for(controller='api', action='get_api', ver=3, qualified=True)
eq_(generated_url, url)
+ @helpers.change_config('ckan.site_url', 'http://example.com')
+ @helpers.change_config('ckan.root_path', '/{{LANG}}/data')
+ def test_url_for_flask_route_old_syntax_qualified_with_root_path(self):
+ url = 'http://example.com/data/api/3'
+ generated_url = h.url_for(controller='api', action='get_api', ver=3, qualified=True)
+ eq_(generated_url, url)
+
@helpers.change_config('ckan.site_url', 'http://example.com')
def test_url_for_flask_route_new_syntax_site_url(self):
url = '/api/3'
| API response help link is nonsense when root_path is set
### CKAN Version if known (or site URL)
2.8.2/master(2.9.0a0)
### Please describe the expected behaviour
help URL in API returns has root_path inside URL
http://domain.tld/data/api/3/help_show?name=package_list
### Please describe the actual behaviour
help URL has root_path prepended
/datahttp://domain.tld/api/3/help_show?name=package_list
### What steps can be taken to reproduce the issue?
Install either 2.8.2 or master
configure with root_path = /{{LANG}}/data
$ paster serve /etc/ckan/default/development.ini &
$ curl http://localhost:5000/api/action/package_list
| Hi @cdn, can you please provide more detailed step to reproduce the issue?
> Hi @cdn, can you please provide more detailed step to reproduce the issue?
Where would you like more detail? | 2019-05-30T09:54:05 |
ckan/ckan | 4,826 | ckan__ckan-4826 | [
"4766"
] | fd0ffb60969cc15edd2568750b28898cd9feda06 | diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py
--- a/ckanext/datastore/backend/postgres.py
+++ b/ckanext/datastore/backend/postgres.py
@@ -1042,7 +1042,7 @@ def upsert_data(context, data_dict):
row = []
for field in fields:
value = record.get(field['id'])
- if value and field['type'].lower() == 'nested':
+ if value is not None and field['type'].lower() == 'nested':
# a tuple with an empty second value
value = (json.dumps(value), '')
row.append(value)
| diff --git a/ckanext/datastore/tests/test_create.py b/ckanext/datastore/tests/test_create.py
--- a/ckanext/datastore/tests/test_create.py
+++ b/ckanext/datastore/tests/test_create.py
@@ -21,6 +21,32 @@
class TestDatastoreCreateNewTests(DatastoreFunctionalTestBase):
+ def test_create_works_with_empty_array_in_json_field(self):
+ package = factories.Dataset()
+ data = {
+ 'resource': {
+ 'package_id': package['id']
+ },
+ 'fields': [{'id': 'movie', 'type': 'text'},
+ {'id': 'directors', 'type': 'json'}],
+ 'records': [{'movie': 'sideways', 'directors': []}]
+ }
+ result = helpers.call_action('datastore_create', **data)
+ assert result['resource_id'] is not None
+
+ def test_create_works_with_empty_object_in_json_field(self):
+ package = factories.Dataset()
+ data = {
+ 'resource': {
+ 'package_id': package['id']
+ },
+ 'fields': [{'id': 'movie', 'type': 'text'},
+ {'id': 'director', 'type': 'json'}],
+ 'records': [{'movie': 'sideways', 'director': {}}]
+ }
+ result = helpers.call_action('datastore_create', **data)
+ assert result['resource_id'] is not None
+
def test_create_creates_index_on_primary_key(self):
package = factories.Dataset()
data = {
| Error when posting empty array with type json using datastore_create
### CKAN Version if known (or site URL)
2.8.0
### Please describe the expected behaviour
Posting data (see below) using datastore_create with specified field type `json` and value `[]` should return status code 200 along with the details of the resource created.
### Please describe the actual behaviour
Status code 409 is returned with the following error:
`{
"help": "http://localhost:5000/api/3/action/help_show?name=datastore_create",
"success": false,
"error": {
"message": "The data was invalid (for example: a numeric value is out of range or was inserted into a text field).",
"__type": "Validation Error"
}
}`
Checking the log file gives the following information:
`db | 2019-05-08 09:50:19.098 UTC [43] ERROR: malformed record literal: "{}" at character 103
db | 2019-05-08 09:50:19.098 UTC [43] DETAIL: Missing left parenthesis.
db | 2019-05-08 09:50:19.098 UTC [43] STATEMENT: INSERT INTO "d9bd906e-39d7-4191-8514-622e33f0afa5" ("conditionId", "symptoms")
db | VALUES (1, '{}');
ckan | 2019-05-08 09:50:19,100 INFO [ckan.views.api] Validation error (Action API): "{'message': u'The data was invalid (for example: a numeric value is out of range or was inserted into a text field).', u'__type': u'Validation Error'}"`
### What steps can be taken to reproduce the issue?
1. Create a dataset called 'my-dataset'.
2. Post the following data in a request to datastore_create:
`{
"resource": {
"package_id": "my-dataset",
"name": "conditions"
},
"fields": [
{
"id": "conditionId",
"type": "int"
},
{
"id": "symptoms",
"type": "json"
}
],
"primary_key": "conditionId",
"records": [
{
"conditionId": 1,
"symptoms": []
}
]
}`
### Comments
I found the following issue where a similar behaviour appeared, but for datastore_upsert:
https://github.com/ckan/ckan/pull/1776
Looking at the code in ckanext/datastore/backend/postgres.py, I believe that the bug was only fixed for upsert/update and not for insert, but I could be wrong.
| @Icontech would you mind submitting a PR to copy the upsert fix to the create code in ckanext/datastore/backend/postgres.py?
@wardi Sure, let me take a look at it. I'm not a member of the CKAN project though, so should I fork the project and then branch from the 2.8.0 release? My first time doing a PR so sorry for any stupid questions. :)
Nevermind, I found the contributing guidelines on the wiki, so I think I have all the info that I need to get started fixing the bug. | 2019-06-03T10:01:02 |
ckan/ckan | 4,828 | ckan__ckan-4828 | [
"4827"
] | e2e33e4335f4196186146e573a93c482af294072 | diff --git a/ckan/logic/auth/get.py b/ckan/logic/auth/get.py
--- a/ckan/logic/auth/get.py
+++ b/ckan/logic/auth/get.py
@@ -163,7 +163,15 @@ def resource_show(context, data_dict):
def resource_view_show(context, data_dict):
- return authz.is_authorized('resource_show', context, data_dict)
+
+ model = context['model']
+
+ resource_view = model.ResourceView.get(data_dict['id'])
+ if not resource_view:
+ raise logic.NotFound(_('Resource view not found, cannot check auth.'))
+ resource = model.Resource.get(resource_view.resource_id)
+
+ return authz.is_authorized('resource_show', context, {'id': resource.id})
def resource_view_list(context, data_dict):
| diff --git a/ckanext/datastore/tests/test_chained_auth_functions.py b/ckanext/datastore/tests/test_chained_auth_functions.py
--- a/ckanext/datastore/tests/test_chained_auth_functions.py
+++ b/ckanext/datastore/tests/test_chained_auth_functions.py
@@ -96,4 +96,3 @@ def test_user_create_chained_auth(self):
ctd.CreateTestData.create()
# check if chained auth fallbacks to built-in user_create
check_access(u'user_create', {u'user': u'annafan'}, {})
-
| More robust auth functions for resource_view_show
Right now it relies on resource objects being present in the context. You should be able to call the auth function with the same parameters as the action (ie just the resource view `id`). This is not an issue in core but it can be problematic when extending auth from extensions.
| 2019-06-03T10:41:28 |
|
ckan/ckan | 4,831 | ckan__ckan-4831 | [
"4830"
] | fd0ffb60969cc15edd2568750b28898cd9feda06 | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -477,7 +477,9 @@ def filter(self, log_record):
log_record.headers = request.headers
return True
- mailhost = tuple(config.get('smtp.server', 'localhost').split(":"))
+ smtp_server = config.get('smtp.server', 'localhost')
+ mailhost = tuple(smtp_server.split(':')) \
+ if ':' in smtp_server else smtp_server
credentials = None
if config.get('smtp.user'):
credentials = (config.get('smtp.user'), config.get('smtp.password'))
| ValueError when you configure exception emails
When I configure CKAN to send me exception emails, I get this exception:
```
$ paster db upgrade -c /etc/ckan/default/development.ini
2019-05-31 21:27:32,979 DEBUG [ckan.lib.fanstatic_resources] Base path /usr/lib/ckan/default/src/ckan/ckan/public/base
2019-05-31 21:27:33,449 DEBUG [ckanext.harvest.model] Harvest tables defined in memory
2019-05-31 21:27:33,462 DEBUG [ckanext.harvest.model] Harvest tables already exist
2019-05-31 21:27:34,126 DEBUG [ckanext.harvest.model] Harvest tables already exist
Traceback (most recent call last):
File "/usr/lib/ckan/default/bin/paster", line 11, in <module>
load_entry_point('PasteScript', 'console_scripts', 'paster')()
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run
invoke(command, command_name, options, args[1:])
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke
exit_code = runner.run(args)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run
result = self.command()
File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 354, in command
self._load_config(cmd!='upgrade')
File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 331, in _load_config
self.site_user = load_config(self.options.config, load_site_user)
File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 244, in load_config
app = make_app(conf.global_conf, **conf.local_conf)
File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/__init__.py", line 60, in make_app
flask_app = make_flask_stack(conf, **app_conf)
File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/flask_app.py", line 188, in make_flask_stack
_register_error_handler(app)
File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/flask_app.py", line 463, in _register_error_handler
_setup_error_mail_handler(app)
File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/flask_app.py", line 481, in _setup_error_mail_handler
subject='Application Error'
File "/usr/lib/python2.7/logging/handlers.py", line 892, in __init__
self.mailhost, self.mailport = mailhost
ValueError: need more than 1 value to unpack
```
Reproduce this using config:
```
#debug = false
email_to = [email protected]
```
The problem is SMTPHandler is expecting a hostname AND port, but the default value doesn't have a port:
```
smtp.server = localhost
```
This was introduced on master: https://github.com/ckan/ckan/pull/4623
### CKAN Version if known (or site URL)
Doesn't affect any CKAN releases. Affects master branch since January 2019.
| 2019-06-05T13:50:18 |
||
ckan/ckan | 4,841 | ckan__ckan-4841 | [
"4837"
] | 61b785fa9ff818cdf8473a5e252e3ffd02b5ce85 | diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py
--- a/ckanext/datastore/backend/postgres.py
+++ b/ckanext/datastore/backend/postgres.py
@@ -315,7 +315,7 @@ def _cache_types(connection):
# redo cache types with json now available.
return _cache_types(connection)
- register_composite('nested', connection.connection, True)
+ register_composite('nested', connection.connection.connection, True)
def _pg_version_is_at_least(connection, version):
| psycopg2 version depends on old libssl
### CKAN Version if known (or site URL)
2.8.2
### Please describe the expected behaviour
CKAN works with up-to-date libssl
### Please describe the actual behaviour
psycopg segfaults if running environment has libssl 1.1 or newer:
```
#0 0x00007f662989ac1b in ssl3_cleanup_key_block ()
from target:/usr/lib/ckan/default/lib/python2.7/site-packages/psycopg2/.libs/./libssl-fad88670.so.1.0.2l
#1 0x00007f6629898516 in ssl3_clear ()
from target:/usr/lib/ckan/default/lib/python2.7/site-packages/psycopg2/.libs/./libssl-fad88670.so.1.0.2l
#2 0x00007f66298a40a9 in tls1_clear ()
from target:/usr/lib/ckan/default/lib/python2.7/site-packages/psycopg2/.libs/./libssl-fad88670.so.1.0.2l
#3 0x00007f663ecb79d2 in SSL_new () from target:/usr/lib/x86_64-linux-gnu/libssl.so.1.1
#4 0x00007f6629b2f389 in ?? () from target:/usr/lib/ckan/default/lib/python2.7/site-packages/psycopg2/.libs/libpq-909a53d8.so.5.10
#5 0x00007f6629b30925 in ?? () from target:/usr/lib/ckan/default/lib/python2.7/site-packages/psycopg2/.libs/libpq-909a53d8.so.5.10
#6 0x00007f6629b1a600 in PQconnectPoll ()
from target:/usr/lib/ckan/default/lib/python2.7/site-packages/psycopg2/.libs/libpq-909a53d8.so.5.10
#7 0x00007f6629b1b099 in ?? () from target:/usr/lib/ckan/default/lib/python2.7/site-packages/psycopg2/.libs/libpq-909a53d8.so.5.10
#8 0x00007f6629b1de9f in PQconnectdb ()
from target:/usr/lib/ckan/default/lib/python2.7/site-packages/psycopg2/.libs/libpq-909a53d8.so.5.10
#9 0x00007f6629d6e4d1 in _conn_sync_connect (self=0x7f662a1baa10) at psycopg/connection_int.c:716
#10 conn_connect (self=self@entry=0x7f662a1baa10, async=<optimized out>) at psycopg/connection_int.c:812
...
```
Notice the two libssl versions. A related psycopg2 issue: psycopg/psycopg2#543
### What steps can be taken to reproduce the issue?
Install libssl 1.1 on server, restart apache2 and try to open the front page.
The issue can be resolved by updating to `psycopg2==2.8.2`
| 2019-06-14T05:38:02 |
||
ckan/ckan | 4,843 | ckan__ckan-4843 | [
"4842"
] | 7fd6ca6439e3a7db60787283148652f895b02920 | diff --git a/ckan/config/routing.py b/ckan/config/routing.py
--- a/ckan/config/routing.py
+++ b/ckan/config/routing.py
@@ -134,11 +134,6 @@ def make_map():
# users
map.redirect('/users/{url:.*}', '/user/{url}')
- with SubMapper(map, controller='util') as m:
- m.connect('/i18n/strings_{lang}.js', action='i18n_js_strings')
- m.connect('/util/redirect', action='redirect')
- m.connect('/testing/primer', action='primer')
-
# robots.txt
map.connect('/(robots.txt)', controller='template', action='view')
diff --git a/ckan/controllers/util.py b/ckan/controllers/util.py
deleted file mode 100644
--- a/ckan/controllers/util.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# encoding: utf-8
-
-import re
-
-import ckan.lib.base as base
-import ckan.lib.i18n as i18n
-import ckan.lib.helpers as h
-from ckan.common import _
-
-
-class UtilController(base.BaseController):
- ''' Controller for functionality that has no real home'''
-
- def redirect(self):
- ''' redirect to the url parameter. '''
- url = base.request.params.get('url')
- if not url:
- base.abort(400, _('Missing Value') + ': url')
-
- if h.url_is_local(url):
- return h.redirect_to(url)
- else:
- base.abort(403, _('Redirecting to external site is not allowed.'))
-
- def primer(self):
- ''' Render all html components out onto a single page.
- This is useful for development/styling of ckan. '''
- return base.render('development/primer.html')
-
- def i18_js_strings(self, lang):
- ''' This is used to produce the translations for javascript. '''
- i18n.set_lang(lang)
- html = base.render('js_strings.html', cache_force=True)
- html = re.sub(r'<[^\>]*>', '', html)
- header = "text/javascript; charset=utf-8"
- base.response.headers['Content-type'] = header
- return html
diff --git a/ckan/views/util.py b/ckan/views/util.py
new file mode 100644
--- /dev/null
+++ b/ckan/views/util.py
@@ -0,0 +1,38 @@
+# encoding: utf-8
+
+import re
+
+from flask import Blueprint
+
+import ckan.lib.base as base
+import ckan.lib.helpers as h
+from ckan.common import _, request
+
+
+util = Blueprint(u'util', __name__)
+
+
+def internal_redirect():
+ u''' Redirect to the url parameter.
+ Only internal URLs are allowed'''
+
+ url = request.form.get(u'url') or request.args.get(u'url')
+ if not url:
+ base.abort(400, _(u'Missing Value') + u': url')
+
+ if h.url_is_local(url):
+ return h.redirect_to(url)
+ else:
+ base.abort(403, _(u'Redirecting to external site is not allowed.'))
+
+
+def primer():
+ u''' Render all HTML components out onto a single page.
+ This is useful for development/styling of CKAN. '''
+
+ return base.render(u'development/primer.html')
+
+
+util.add_url_rule(
+ u'/util/redirect', view_func=internal_redirect, methods=(u'GET', u'POST',))
+util.add_url_rule(u'/testing/primer', view_func=primer)
| diff --git a/ckan/tests/controllers/test_util.py b/ckan/tests/controllers/test_util.py
--- a/ckan/tests/controllers/test_util.py
+++ b/ckan/tests/controllers/test_util.py
@@ -11,7 +11,7 @@ class TestUtil(helpers.FunctionalTestBase):
def test_redirect_ok(self):
app = self._get_test_app()
response = app.get(
- url=url_for(controller='util', action='redirect'),
+ url=url_for('util.internal_redirect'),
params={'url': '/dataset'},
status=302,
)
@@ -21,7 +21,7 @@ def test_redirect_ok(self):
def test_redirect_external(self):
app = self._get_test_app()
response = app.get(
- url=url_for(controller='util', action='redirect'),
+ url=url_for('util.internal_redirect'),
params={'url': 'http://nastysite.com'},
status=403,
)
@@ -29,7 +29,7 @@ def test_redirect_external(self):
def test_redirect_no_params(self):
app = self._get_test_app()
response = app.get(
- url=url_for(controller='util', action='redirect'),
+ url=url_for('util.internal_redirect'),
params={},
status=400,
)
@@ -37,7 +37,7 @@ def test_redirect_no_params(self):
def test_redirect_no_params_2(self):
app = self._get_test_app()
response = app.get(
- url=url_for(controller='util', action='redirect'),
+ url=url_for('util.internal_redirect'),
params={'url': ''},
status=400,
)
| Migrate util controller
This was a left over from the core blueprints migration.
| 2019-06-14T14:34:45 |
|
ckan/ckan | 4,847 | ckan__ckan-4847 | [
"4844"
] | 7fd6ca6439e3a7db60787283148652f895b02920 | diff --git a/ckan/lib/webassets_tools.py b/ckan/lib/webassets_tools.py
--- a/ckan/lib/webassets_tools.py
+++ b/ckan/lib/webassets_tools.py
@@ -58,7 +58,7 @@ def webassets_init():
env.debug = config.get(u'debug', False)
env.url = u'/webassets/'
- env.append_path(base_path, u'/base/')
+ add_public_path(base_path, u'/base/')
logger.debug(u'Base path {0}'.format(base_path))
create_library(u'vendor', os.path.join(
@@ -159,3 +159,7 @@ def get_webassets_path():
u'must be specified'
)
return webassets_path
+
+
+def add_public_path(path, url):
+ env.append_path(path, url)
diff --git a/ckan/plugins/toolkit.py b/ckan/plugins/toolkit.py
--- a/ckan/plugins/toolkit.py
+++ b/ckan/plugins/toolkit.py
@@ -325,8 +325,19 @@ def _add_public_directory(cls, config, relative_path):
The path is relative to the file calling this function.
+ Webassets addition: append directory to webassets load paths
+ in order to correctly rewrite relative css paths and resolve
+ public urls.
+
'''
- cls._add_served_directory(config, relative_path, 'extra_public_paths')
+ import ckan.lib.helpers as h
+ from ckan.lib.webassets_tools import add_public_path
+ path = cls._add_served_directory(
+ config,
+ relative_path,
+ 'extra_public_paths'
+ )
+ add_public_path(path, h.url_for_static('/'))
@classmethod
def _add_served_directory(cls, config, relative_path, config_var):
@@ -349,6 +360,7 @@ def _add_served_directory(cls, config, relative_path, config_var):
config[config_var] += ',' + absolute_path
else:
config[config_var] = absolute_path
+ return absolute_path
@classmethod
def _add_resource(cls, path, name):
| 404s for minor recline assets
### CKAN Version if known (or site URL)
latest master
### Bug
When I preview a CSV on the resource page e.g. `/dataset/test/resource/0d534c55-879c-41c3-9e8f-26386b574158`
then it basically works, but there are some 404 errors fetching a few assets:
* /webassets/img/ajaxload-circle.gif
* /webassets/fonts/glyphicons-halflings-regular.woff
* /webassets/fonts/glyphicons-halflings-regular.ttf
There is a mismatch because there is an asset here: /img/ajaxload-circle.gif
I guess this is a side-effect from: https://github.com/ckan/ckan/pull/4614
| @smotornyuk I don't suppose you have a moment to look at this? | 2019-06-16T11:02:26 |
|
ckan/ckan | 4,873 | ckan__ckan-4873 | [
"4872"
] | f6adcaa5bf4ae7e8ef662b089e356f1f7b9df69d | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -409,7 +409,9 @@ def _url_for_pylons(*args, **kw):
# We need to provide protocol and host to get full URLs, get them from
# ckan.site_url
- if kw.get('qualified', False) or kw.get('_external', False):
+ if kw.pop('_external', None):
+ kw['qualified'] = True
+ if kw.get('qualified'):
kw['protocol'], kw['host'] = get_site_protocol_and_host()
# The Pylons API routes require a slask on the version number for some
| diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py
--- a/ckan/tests/lib/test_helpers.py
+++ b/ckan/tests/lib/test_helpers.py
@@ -314,6 +314,22 @@ def test_url_for_pylons_request_using_flask_url_for(self):
p.unload('test_routing_plugin')
+ @helpers.change_config('ckan.site_url', 'http://example.com')
+ def test_url_for_pylons_request_external(self):
+
+ if not p.plugin_loaded('test_routing_plugin'):
+ p.load('test_routing_plugin')
+
+ url = 'http://example.com/from_pylons_extension_before_map'
+ generated_url = h.url_for(
+ controller='ckan.tests.config.test_middleware:MockPylonsController',
+ action='view',
+ _external=True,
+ )
+ eq_(generated_url, url)
+
+ p.unload('test_routing_plugin')
+
class TestHelpersRenderMarkdown(object):
| _external parameter kept on Pylons generated URLs
The `url_for` wrapper for Pylons requests correctly handles Flask's `_external` parameter to generate fully qualified URLs, but fails to remove it, resulting in an extraneous param added to the URL, eg: `http://example.com/dataset/test?_external=True`
| 2019-06-26T13:03:37 |
|
ckan/ckan | 4,875 | ckan__ckan-4875 | [
"4874"
] | f6adcaa5bf4ae7e8ef662b089e356f1f7b9df69d | diff --git a/ckanext/reclineview/plugin.py b/ckanext/reclineview/plugin.py
--- a/ckanext/reclineview/plugin.py
+++ b/ckanext/reclineview/plugin.py
@@ -21,6 +21,14 @@ def get_mapview_config():
if k.startswith(namespace)])
+def get_dataproxy_url():
+ '''
+ Returns the value of the ckan.recline.dataproxy_url config option
+ '''
+ return config.get(
+ 'ckan.recline.dataproxy_url', '//jsonpdataproxy.appspot.com')
+
+
def in_list(list_possible_values):
'''
Validator that checks that the input value is one of the given
@@ -83,7 +91,8 @@ def view_template(self, context, data_dict):
def get_helpers(self):
return {
- 'get_map_config': get_mapview_config
+ 'get_map_config': get_mapview_config,
+ 'get_dataproxy_url': get_dataproxy_url,
}
| Allow to customize the DataProxy URL
This will allow users that really want to use it to host their own instance
| 2019-06-26T14:07:28 |
||
ckan/ckan | 4,879 | ckan__ckan-4879 | [
"4515"
] | f6adcaa5bf4ae7e8ef662b089e356f1f7b9df69d | diff --git a/ckanext/datapusher/logic/action.py b/ckanext/datapusher/logic/action.py
--- a/ckanext/datapusher/logic/action.py
+++ b/ckanext/datapusher/logic/action.py
@@ -62,7 +62,14 @@ def datapusher_submit(context, data_dict):
datapusher_url = config.get('ckan.datapusher.url')
site_url = h.url_for('/', qualified=True)
- callback_url = h.url_for('/api/3/action/datapusher_hook', qualified=True)
+
+ callback_url_base = config.get('ckan.datapusher.callback_url_base')
+ if callback_url_base:
+ callback_url = urlparse.urljoin(
+ callback_url_base.rstrip('/'), '/api/3/action/datapusher_hook')
+ else:
+ callback_url = h.url_for(
+ '/api/3/action/datapusher_hook', qualified=True)
user = p.toolkit.get_action('user_show')(context, {'id': context['user']})
| diff --git a/ckanext/datapusher/tests/test.py b/ckanext/datapusher/tests/test.py
--- a/ckanext/datapusher/tests/test.py
+++ b/ckanext/datapusher/tests/test.py
@@ -11,6 +11,7 @@
import ckanext.datastore.backend.postgres as db
import responses
import nose
+from nose.tools import assert_equals
import sqlalchemy.orm as orm
from ckan.common import config
from ckanext.datastore.tests.helpers import rebuild_all_dbs, set_url_type
@@ -232,3 +233,33 @@ def test_datapusher_hook_no_resource_id_in_metadata(self):
self.app.post('/api/action/datapusher_hook', params=postparams,
status=409)
+
+ @responses.activate
+ @helpers.change_config(
+ 'ckan.datapusher.callback_url_base', 'https://ckan.example.com')
+ @helpers.change_config(
+ 'ckan.datapusher.url', 'http://datapusher.ckan.org')
+ def test_custom_callback_url_base(self):
+
+ package = model.Package.get('annakarenina')
+ resource = package.resources[0]
+
+ responses.add(
+ responses.POST,
+ 'http://datapusher.ckan.org/job',
+ content_type='application/json',
+ body=json.dumps({'job_id': 'foo', 'job_key': 'barloco'})
+ )
+ responses.add_passthru(config['solr_url'])
+
+ tests.call_action_api(
+ self.app, 'datapusher_submit', apikey=self.sysadmin_user.apikey,
+ resource_id=resource.id,
+ ignore_hash=True
+ )
+
+ data = json.loads(responses.calls[-1].request.body)
+ assert_equals(
+ data['result_url'],
+ 'https://ckan.example.com/api/3/action/datapusher_hook'
+ )
| Process completed but unable to post to result_url
### CKAN Version if known (or site URL)
version 2.8.1
### Please describe the expected behaviour
I install ckan with docker, and everything works fine but when I add a resource in datastore it does not work I get this error Process completed but unable to post to result_url
### Please describe the actual behaviour
### What steps can be taken to reproduce the issue?
| This error means that the DataPusher finished its job (ie the data is on the DataStore) but it could not ping back to CKAN via HTTP to update the status. This generally happens because the CKAN host (as defined in `ckan.site_url` is not accessible, in this case from the DataPusher container.
One workaround is to add an entry to your /etc/hosts file (something like `127.0.0.1 ckan-dev` and use that in your `ckan.site_url` setting. | 2019-06-27T12:18:14 |
ckan/ckan | 4,885 | ckan__ckan-4885 | [
"4675"
] | 8d0d0a136a92cb057d207e2528d12169f9faa09b | diff --git a/ckan/lib/cli.py b/ckan/lib/cli.py
--- a/ckan/lib/cli.py
+++ b/ckan/lib/cli.py
@@ -548,7 +548,7 @@ def clear(self):
def rebuild_fast(self):
### Get out config but without starting pylons environment ####
- conf = self._get_config()
+ conf = _get_config()
### Get ids using own engine, otherwise multiprocess will balk
db_url = conf['sqlalchemy.url']
| rebuild_fast is broken
### CKAN Version if known (or site URL)
2.8.2
### Please describe the expected behaviour
`rebuild_fast` should work.
### Please describe the actual behaviour
```
root@dfa227c64a65:/usr/lib/ckan/venv/src/ckan# ckan-paster search-index rebuild_fast --config /etc/ckan/production.ini
Traceback (most recent call last):
File "/usr/local/bin/ckan-paster", line 11, in <module>
sys.exit(run())
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run
invoke(command, command_name, options, args[1:])
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke
exit_code = runner.run(args)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run
result = self.command()
File "/usr/lib/ckan/venv/src/ckan/ckan/lib/cli.py", line 574, in command
self.rebuild_fast()
File "/usr/lib/ckan/venv/src/ckan/ckan/lib/cli.py", line 630, in rebuild_fast
conf = self._get_config()
AttributeError: 'SearchIndexCommand' object has no attribute '_get_config'
root@dfa227c64a65:/usr/lib/ckan/venv/src/ckan# ckan-paster search-index rebuild --config /etc/ckan/production.ini
2019-03-07 11:29:55,367 DEBUG [ckanext.spatial.plugin] Setting up the spatial model
2019-03-07 11:29:55,433 DEBUG [ckanext.spatial.model.package_extent] Spatial tables defined in memory
2019-03-07 11:29:55,448 DEBUG [ckanext.spatial.model.package_extent] Spatial tables already exist
2019-03-07 11:29:55,760 DEBUG [ckanext.spatial.plugin] Setting up the spatial model
2019-03-07 11:29:55,773 DEBUG [ckanext.spatial.model.package_extent] Spatial tables already exist
```
### What steps can be taken to reproduce the issue?
See above.
| Found this because it's also broke in 2.7.5
```
Traceback (most recent call last):
File "/usr/lib/ckan/default/bin/paster", line 10, in <module>
sys.exit(run())
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run
invoke(command, command_name, options, args[1:])
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke
exit_code = runner.run(args)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run
result = self.command()
File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 549, in command
self.rebuild_fast()
File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 605, in rebuild_fast
conf = self._get_config()
AttributeError: 'SearchIndexCommand' object has no attribute '_get_config'
``` | 2019-07-01T10:48:52 |
|
ckan/ckan | 4,886 | ckan__ckan-4886 | [
"4795"
] | 9a80e29b5f412cf6049ec911fbbcf489dbb40562 | diff --git a/ckan/plugins/core.py b/ckan/plugins/core.py
--- a/ckan/plugins/core.py
+++ b/ckan/plugins/core.py
@@ -112,10 +112,10 @@ def plugins_update():
# the file containing them is imported, for example if two or more
# extensions are defined in the same file. Therefore we do a sanity
# check and disable any that should not be active.
- for env in PluginGlobals.env_registry.values():
- for service in env.services.copy():
- if service.__class__ not in _PLUGINS_CLASS:
- service.deactivate()
+ for env in PluginGlobals.env.values():
+ for service, id_ in env.singleton_services.items():
+ if service not in _PLUGINS_CLASS:
+ PluginGlobals.plugin_instances[id_].deactivate()
# Reset CKAN to reflect the currently enabled extensions.
import ckan.config.environment as environment
| diff --git a/ckan/tests/legacy/test_plugins.py b/ckan/tests/legacy/test_plugins.py
--- a/ckan/tests/legacy/test_plugins.py
+++ b/ckan/tests/legacy/test_plugins.py
@@ -101,7 +101,7 @@ def test_plugins_load(self):
# synchronous_search automatically gets loaded
current_plugins = set([plugins.get_plugin(p) for p in ['mapper_plugin', 'routes_plugin', 'synchronous_search'] + find_system_plugins()])
- assert PluginGlobals.env().services == current_plugins
+ assert set(plugins.core._PLUGINS_SERVICE.values()) == current_plugins
# cleanup
config['ckan.plugins'] = config_plugins
plugins.load_all()
@@ -175,10 +175,15 @@ def test_mapper_plugin_fired_on_delete(self):
def test_routes_plugin_fired(self):
with plugins.use_plugin('routes_plugin'):
- routes_plugin = PluginGlobals.env_registry['pca'].plugin_registry['RoutesPlugin'].__instance__
- assert routes_plugin.calls_made == ['before_map', 'after_map'], \
- routes_plugin.calls_made
+ pca = PluginGlobals.env['pca']
+ routes_plugin_idx = pca.singleton_services[
+ pca.plugin_registry['RoutesPlugin']
+ ]
+
+ routes_plugin = PluginGlobals.plugin_instances[routes_plugin_idx]
+ assert routes_plugin.calls_made == ['before_map', 'after_map'], \
+ routes_plugin.calls_made
def test_action_plugin_override(self):
status_show_original = logic.get_action('status_show')(None, {})
| Replace pyutilib.component.core with a modern alternative
We use pyutilib.component.core to define the interface classes and methods used by our plugins system, eg things like `SingletonPlugin`, `implements` or `PluginImplementations`. It is not a lot of code but obviously pretty critical as the extensions depend completely on it.
pyutilib.component.core is ancient, and it has since moved back to a single PyUtilib package as discussed in [here](https://github.com/PyUtilib/pyutilib/issues/30).
#### Approach
A quick look at the relevant module on pyutilib shows that the same classes and methods are still available so hopefully it's just a matter of changing the requirements and the imports to point to the new package.
In the future we might want to look at an alternative but to get the Python 2 dependency out of the way this looks like the easiest option.
#### Story points
3
| 2019-07-01T17:14:35 |
|
ckan/ckan | 4,912 | ckan__ckan-4912 | [
"4796"
] | 7972908a4327260a74a88eb7d346ffd12f673aff | diff --git a/ckan/lib/repoze_plugins/__init__.py b/ckan/lib/repoze_plugins/__init__.py
new file mode 100644
diff --git a/ckan/lib/auth_tkt.py b/ckan/lib/repoze_plugins/auth_tkt.py
similarity index 79%
rename from ckan/lib/auth_tkt.py
rename to ckan/lib/repoze_plugins/auth_tkt.py
--- a/ckan/lib/auth_tkt.py
+++ b/ckan/lib/repoze_plugins/auth_tkt.py
@@ -19,7 +19,7 @@ def __init__(self, httponly, *args, **kwargs):
self.httponly = httponly
def _get_cookies(self, *args, **kwargs):
- '''
+ u'''
Override method in superclass to ensure HttpOnly is set appropriately.
'''
super_cookies = super(CkanAuthTktCookiePlugin, self). \
@@ -46,29 +46,29 @@ def make_plugin(secret=None,
# ckan specifics:
# Get secret from beaker setting if necessary
- if secret is None or secret == 'somesecret':
- secret = config['beaker.session.secret']
+ if secret is None or secret == u'somesecret':
+ secret = config[u'beaker.session.secret']
# Session timeout and reissue time for auth cookie
- if timeout is None and config.get('who.timeout'):
- timeout = config.get('who.timeout')
- if reissue_time is None and config.get('who.reissue_time'):
- reissue_time = config.get('who.reissue_time')
+ if timeout is None and config.get(u'who.timeout'):
+ timeout = config.get(u'who.timeout')
+ if reissue_time is None and config.get(u'who.reissue_time'):
+ reissue_time = config.get(u'who.reissue_time')
if timeout is not None and reissue_time is None:
reissue_time = int(math.ceil(int(timeout) * 0.1))
# Set httponly based on config value. Default is True
- httponly = config.get('who.httponly', True)
+ httponly = config.get(u'who.httponly', True)
# Set secure based on config value. Default is False
- secure = config.get('who.secure', False)
+ secure = config.get(u'who.secure', False)
# back to repoze boilerplate
if (secret is None and secretfile is None):
- raise ValueError("One of 'secret' or 'secretfile' must not be None.")
+ raise ValueError(u"One of 'secret' or 'secretfile' must not be None.")
if (secret is not None and secretfile is not None):
- raise ValueError("Specify only one of 'secret' or 'secretfile'.")
+ raise ValueError(u"Specify only one of 'secret' or 'secretfile'.")
if secretfile:
secretfile = os.path.abspath(os.path.expanduser(secretfile))
if not os.path.exists(secretfile):
- raise ValueError("No such 'secretfile': %s" % secretfile)
+ raise ValueError(u"No such 'secretfile': %s" % secretfile)
secret = open(secretfile).read().strip()
if timeout:
timeout = int(timeout)
diff --git a/ckan/lib/repoze_plugins/friendly_form.py b/ckan/lib/repoze_plugins/friendly_form.py
new file mode 100644
--- /dev/null
+++ b/ckan/lib/repoze_plugins/friendly_form.py
@@ -0,0 +1,318 @@
+# -*- coding: utf-8 -*-
+
+#
+# This is a modified version of repoze.who-friendlyform, written by
+# Gustavo Narea <[email protected]>
+#
+# Modifications include:
+# * Python 3 support
+# * Replace usage of paster methods with webob ones
+#
+
+##############################################################################
+#
+# Copyright (c) 2009-2010, Gustavo Narea <[email protected]> and
+# contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the BSD-like license at
+# http://www.repoze.org/LICENSE.txt. A copy of the license should accompany
+# this distribution. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL
+# EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO,
+# THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND
+# FITNESS FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+
+u'''Collection of :mod:`repoze.who` friendly forms'''
+
+from six.moves.urllib.parse import urlparse, urlunparse, urlencode, parse_qs
+
+from webob import Request, UnicodeMultiDict
+from webob.exc import HTTPFound, HTTPUnauthorized
+from zope.interface import implements
+
+from repoze.who.interfaces import IChallenger, IIdentifier
+
+__all__ = [u'FriendlyFormPlugin']
+
+
+def construct_url(environ):
+ return Request(environ).url
+
+
+class FriendlyFormPlugin(object):
+ u'''
+ :class:`RedirectingFormPlugin
+ <repoze.who.plugins.form.RedirectingFormPlugin>`-like form plugin with
+ more features.
+
+ It is like ``RedirectingFormPlugin``, but provides us with the following
+ features:
+
+ * Users are not challenged on logout, unless the referrer URL is a
+ private one (but that's up to the application).
+ * Developers may define post-login and/or post-logout pages.
+ * In the login URL, the amount of failed logins is available in the
+ environ. It's also increased by one on every login try. This counter
+ will allow developers not using a post-login page to handle logins that
+ fail/succeed.
+
+ You should keep in mind that if you're using a post-login or a post-logout
+ page, that page will receive the referrer URL as a query string variable
+ whose name is 'came_from'.
+
+ Forms can be submitted with any encoding (non-ASCII credentials are
+ supported) and ISO-8859-1 (aka 'Latin-1') is the default one.
+
+ '''
+ implements(IChallenger, IIdentifier)
+
+ classifications = {
+ IIdentifier: [u'browser'],
+ IChallenger: [u'browser'],
+ }
+
+ def __init__(self, login_form_url, login_handler_path, post_login_url,
+ logout_handler_path, post_logout_url, rememberer_name,
+ login_counter_name=None, charset=u'iso-8859-1'):
+ u'''
+
+ :param login_form_url: The URL/path where the login form is located.
+ :type login_form_url: str
+ :param login_handler_path: The URL/path where the login form is
+ submitted to (where it is processed by this plugin).
+ :type login_handler_path: str
+ :param post_login_url: The URL/path where the user should be redirected
+ to after login (even if wrong credentials were provided).
+ :type post_login_url: str
+ :param logout_handler_path: The URL/path where the user is logged out.
+ :type logout_handler_path: str
+ :param post_logout_url: The URL/path where the user should be
+ redirected to after logout.
+ :type post_logout_url: str
+ :param rememberer_name: The name of the repoze.who identifier which
+ acts as rememberer.
+ :type rememberer_name: str
+ :param login_counter_name: The name of the query string variable which
+ will represent the login counter.
+ :type login_counter_name: str
+ :param charset: The character encoding to be assumed when the user
+ agent does not submit the form with an explicit charset.
+ :type charset: :class:`str`
+
+ The login counter variable's name will be set to ``__logins`` if
+ ``login_counter_name`` equals None.
+
+ .. versionchanged:: 1.0.1
+ Added the ``charset`` argument.
+
+ '''
+ self.login_form_url = login_form_url
+ self.login_handler_path = login_handler_path
+ self.post_login_url = post_login_url
+ self.logout_handler_path = logout_handler_path
+ self.post_logout_url = post_logout_url
+ self.rememberer_name = rememberer_name
+ self.login_counter_name = login_counter_name
+ if not login_counter_name:
+ self.login_counter_name = u'__logins'
+ self.charset = charset
+
+ # IIdentifier
+ def identify(self, environ):
+ u'''
+ Override the parent's identifier to introduce a login counter
+ (possibly along with a post-login page) and load the login counter into
+ the ``environ``.
+
+ '''
+ request = Request(environ, charset=self.charset)
+
+ path_info = environ[u'PATH_INFO']
+ script_name = environ.get(u'SCRIPT_NAME') or u'/'
+ query = request.GET
+
+ if path_info == self.login_handler_path:
+ # We are on the URL where repoze.who processes authentication. #
+ # Let's append the login counter to the query string of the
+ # 'came_from' URL. It will be used by the challenge below if
+ # authorization is denied for this request.
+ form = dict(request.POST)
+ form.update(query)
+ try:
+ login = form[u'login']
+ password = form[u'password']
+ except KeyError:
+ credentials = None
+ else:
+ if request.charset == u'us-ascii':
+ credentials = {
+ u'login': str(login),
+ u'password': str(password),
+ }
+ else:
+ credentials = {u'login': login, u'password': password}
+
+ try:
+ credentials[u'max_age'] = form[u'remember']
+ except KeyError:
+ pass
+
+ referer = environ.get(u'HTTP_REFERER', script_name)
+ destination = form.get(u'came_from', referer)
+
+ if self.post_login_url:
+ # There's a post-login page, so we have to replace the
+ # destination with it.
+ destination = self._get_full_path(self.post_login_url,
+ environ)
+ if u'came_from' in query:
+ # There's a referrer URL defined, so we have to pass it to
+ # the post-login page as a GET variable.
+ destination = self._insert_qs_variable(destination,
+ u'came_from',
+ query[u'came_from'])
+ failed_logins = self._get_logins(environ, True)
+ new_dest = self._set_logins_in_url(destination, failed_logins)
+ environ[u'repoze.who.application'] = HTTPFound(location=new_dest)
+ return credentials
+
+ elif path_info == self.logout_handler_path:
+ # We are on the URL where repoze.who logs the user out. #
+ r = Request(environ)
+ params = dict(list(r.GET.items()) + list(r.POST.items()))
+ form = UnicodeMultiDict(params)
+ form.update(query)
+ referer = environ.get(u'HTTP_REFERER', script_name)
+ came_from = form.get(u'came_from', referer)
+ # set in environ for self.challenge() to find later
+ environ[u'came_from'] = came_from
+ environ[u'repoze.who.application'] = HTTPUnauthorized()
+ return None
+
+ elif path_info == self.login_form_url or self._get_logins(environ):
+ # We are on the URL that displays the from OR any other page #
+ # where the login counter is included in the query string. #
+ # So let's load the counter into the environ and then hide it from
+ # the query string (it will cause problems in frameworks like TG2,
+ # where this unexpected variable would be passed to the controller)
+ environ[u'repoze.who.logins'] = self._get_logins(environ, True)
+ # Hiding the GET variable in the environ:
+ if self.login_counter_name in query:
+ del query[self.login_counter_name]
+ environ[u'QUERY_STRING'] = urlencode(query, doseq=True)
+
+ # IChallenger
+ def challenge(self, environ, status, app_headers, forget_headers):
+ u'''
+ Override the parent's challenge to avoid challenging the user on
+ logout, introduce a post-logout page and/or pass the login counter
+ to the login form.
+
+ '''
+ url_parts = list(urlparse(self.login_form_url))
+ query = url_parts[4]
+ query_elements = parse_qs(query)
+ came_from = environ.get(u'came_from', construct_url(environ))
+ query_elements[u'came_from'] = came_from
+ url_parts[4] = urlencode(query_elements, doseq=True)
+ login_form_url = urlunparse(url_parts)
+ login_form_url = self._get_full_path(login_form_url, environ)
+ destination = login_form_url
+ # Configuring the headers to be set:
+ cookies = [
+ (h, v) for (h, v) in app_headers if h.lower() == u'set-cookie'
+ ]
+ headers = forget_headers + cookies
+
+ if environ[u'PATH_INFO'] == self.logout_handler_path:
+ # Let's log the user out without challenging.
+ came_from = environ.get(u'came_from')
+ if self.post_logout_url:
+ # Redirect to a predefined u'post logout' URL.
+ destination = self._get_full_path(self.post_logout_url,
+ environ)
+ if came_from:
+ destination = self._insert_qs_variable(
+ destination, u'came_from', came_from)
+ else:
+ # Redirect to the referrer URL.
+ script_name = environ.get(u'SCRIPT_NAME', u'')
+ destination = came_from or script_name or u'/'
+
+ elif u'repoze.who.logins' in environ:
+ # Login failed! Let's redirect to the login form and include
+ # the login counter in the query string
+ environ[u'repoze.who.logins'] += 1
+ # Re-building the URL:
+ destination = self._set_logins_in_url(
+ destination, environ[u'repoze.who.logins'])
+
+ return HTTPFound(location=destination, headers=headers)
+
+ # IIdentifier
+ def remember(self, environ, identity):
+ rememberer = self._get_rememberer(environ)
+ return rememberer.remember(environ, identity)
+
+ # IIdentifier
+ def forget(self, environ, identity):
+ rememberer = self._get_rememberer(environ)
+ return rememberer.forget(environ, identity)
+
+ def _get_rememberer(self, environ):
+ rememberer = environ[u'repoze.who.plugins'][self.rememberer_name]
+ return rememberer
+
+ def _get_full_path(self, path, environ):
+ u'''
+ Return the full path to ``path`` by prepending the SCRIPT_NAME.
+
+ If ``path`` is a URL, do nothing.
+
+ '''
+ if path.startswith(u'/'):
+ path = environ.get(u'SCRIPT_NAME', u'') + path
+ return path
+
+ def _get_logins(self, environ, force_typecast=False):
+ u'''
+ Return the login counter from the query string in the ``environ``.
+
+ If it's not possible to convert it into an integer and
+ ``force_typecast`` is ``True``, it will be set to zero (int(0)).
+ Otherwise, it will be ``None`` or an string.
+
+ '''
+ variables = Request(environ).queryvars
+ failed_logins = variables.get(self.login_counter_name)
+ if force_typecast:
+ try:
+ failed_logins = int(failed_logins)
+ except (ValueError, TypeError):
+ failed_logins = 0
+ return failed_logins
+
+ def _set_logins_in_url(self, url, logins):
+ u'''
+ Insert the login counter variable with the ``logins`` value into
+ ``url`` and return the new URL.
+
+ '''
+ return self._insert_qs_variable(url, self.login_counter_name, logins)
+
+ def _insert_qs_variable(self, url, var_name, var_value):
+ u'''
+ Insert the variable ``var_name`` with value ``var_value`` in the query
+ string of ``url`` and return the new URL.
+
+ '''
+ url_parts = list(urlparse(url))
+ query_parts = parse_qs(url_parts[4])
+ query_parts[var_name] = var_value
+ url_parts[4] = urlencode(query_parts, doseq=True)
+ return urlunparse(url_parts)
+
+ def __repr__(self):
+ return u'<%s %s>' % (self.__class__.__name__, id(self))
| diff --git a/ckan/tests/lib/test_auth_tkt.py b/ckan/tests/lib/test_auth_tkt.py
--- a/ckan/tests/lib/test_auth_tkt.py
+++ b/ckan/tests/lib/test_auth_tkt.py
@@ -3,7 +3,7 @@
from nose import tools as nose_tools
from ckan.tests import helpers
-from ckan.lib.auth_tkt import make_plugin
+from ckan.lib.repoze_plugins.auth_tkt import make_plugin
class TestCkanAuthTktCookiePlugin(helpers.FunctionalTestBase):
diff --git a/ckan/tests/test_coding_standards.py b/ckan/tests/test_coding_standards.py
--- a/ckan/tests/test_coding_standards.py
+++ b/ckan/tests/test_coding_standards.py
@@ -264,7 +264,6 @@ def find_unprefixed_string_literals(filename):
u'ckan/lib/activity_streams.py',
u'ckan/lib/activity_streams_session_extension.py',
u'ckan/lib/app_globals.py',
- u'ckan/lib/auth_tkt.py',
u'ckan/lib/authenticator.py',
u'ckan/lib/base.py',
u'ckan/lib/captcha.py',
@@ -298,6 +297,7 @@ def find_unprefixed_string_literals(filename):
u'ckan/lib/search/index.py',
u'ckan/lib/search/query.py',
u'ckan/lib/search/sql.py',
+ u'ckan/lib/repoze_plugins/auth_tkt.py',
u'ckan/lib/uploader.py',
u'ckan/logic/__init__.py',
u'ckan/logic/action/__init__.py',
| Replace repoze.who-friendlyform with a modern alternative
We use the [repoze.who-friendlyform](http://code.gustavonarea.net/repoze.who-friendlyform/) plugin during our authentication process. This plugin was last updated on 2010 and it's not py3 ready. More specifically we use it as [Indentifier](https://repoze.readthedocs.io/projects/repozewho/en/latest/plugins.html#identifier-plugins) (extract user name and password from the WSGI env) and as a [Challenger](https://repoze.readthedocs.io/projects/repozewho/en/latest/plugins.html#challenger-plugins) (present the user with a login/logout page). See the [who.ini](https://github.com/ckan/ckan/blob/master/ckan/config/who.ini) file.
The FriendlyForm plugin extends a default repoze.who one, [RedirectorPlugin](https://repoze.readthedocs.io/projects/repozewho/en/latest/plugins.html#repoze.who.plugins.redirector.RedirectorPlugin) with some extra functionality. The one that we use is
> Developers may define post-login and/or post-logout pages.
#### Approach
This is a pretty critical functionality so we need to come up with a good replacement strategy. It might be tempting to try to replace the whole repoze.who authenticating system with something like [Flask-login](https://flask-login.readthedocs.io/en/latest/), which has a much simpler and straight-forward integration and is better supported, but that is a big change, as we use some of the repoze.who assumptions at differents parts of the code (eg relying on the `REMOTE_USER` environ variable). So I'd suggest to plan that for a later stage and keep repoze.who in place for at least 2.9.
This means replacing or upgrading repoze.who-friendlyform. The plugin itself is not massive:
https://gist.github.com/amercader/0643f17f3d9641a49c3ed9f630d545df
So perhaps the best solution for now is to include this as part of the CKAN code base and upgrade it to run on Python 3
#### Story points
5
| 2019-07-19T11:59:02 |
|
ckan/ckan | 4,913 | ckan__ckan-4913 | [
"4911"
] | 02915e0aea933d12d974cc1aa14a4e89640e4b3c | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -176,14 +176,6 @@ def ungettext_alias():
babel.localeselector(get_locale)
- @app.route('/hello', methods=['GET'])
- def hello_world():
- return 'Hello World, this is served by Flask'
-
- @app.route('/hello', methods=['POST'])
- def hello_world_post():
- return 'Hello World, this was posted to Flask'
-
# WebAssets
_setup_webassets(app)
diff --git a/ckan/plugins/toolkit.py b/ckan/plugins/toolkit.py
--- a/ckan/plugins/toolkit.py
+++ b/ckan/plugins/toolkit.py
@@ -498,11 +498,7 @@ def _get_endpoint(cls):
return common.c.controller, common.c.action
except AttributeError:
return (None, None)
- # there are some routes('hello_world') that are not using blueprint
- # For such case, let's assume that view function is a controller
- # itself and action is None.
- if len(endpoint) == 1:
- return endpoint + (None,)
+
return endpoint
def __getattr__(self, name):
diff --git a/ckanext/example_flask_iblueprint/plugin.py b/ckanext/example_flask_iblueprint/plugin.py
--- a/ckanext/example_flask_iblueprint/plugin.py
+++ b/ckanext/example_flask_iblueprint/plugin.py
@@ -11,21 +11,8 @@ def hello_plugin():
return u'Hello World, this is served from an extension'
-def override_pylons_about():
- u'''A simple replacement for the pylons About page.'''
- return render_template(u'about.html')
-
-
-def override_pylons_about_with_core_template():
- u'''
- Override the pylons about controller to render the core about page
- template.
- '''
- return render_template(u'home/about.html')
-
-
-def override_flask_hello():
- u'''A simple replacement for the flash Hello view function.'''
+def override_flask_home():
+ u'''A simple replacement for the flash Home view function.'''
html = u'''<!DOCTYPE html>
<html>
<head>
@@ -94,10 +81,7 @@ def get_blueprint(self):
# Add plugin url rules to Blueprint object
rules = [
(u'/hello_plugin', u'hello_plugin', hello_plugin),
- (u'/about', u'about', override_pylons_about),
- (u'/about_core', u'about_core',
- override_pylons_about_with_core_template),
- (u'/hello', u'hello', override_flask_hello),
+ (u'/', u'home', override_flask_home),
(u'/helper_not_here', u'helper_not_here', helper_not_here),
(u'/helper', u'helper_here', helper_here),
]
| diff --git a/ckan/tests/config/test_middleware.py b/ckan/tests/config/test_middleware.py
--- a/ckan/tests/config/test_middleware.py
+++ b/ckan/tests/config/test_middleware.py
@@ -144,18 +144,15 @@ def test_ask_around_flask_core_route_get(self):
app = app.app
environ = {
- 'PATH_INFO': '/hello',
+ 'PATH_INFO': '/',
'REQUEST_METHOD': 'GET',
}
wsgiref.util.setup_testing_defaults(environ)
answers = app.ask_around(environ)
- # Even though this route is defined in Flask, there is catch all route
- # in Pylons for all requests to point arbitrary urls to templates with
- # the same name, so we get two positive answers
eq_(answers, [(True, 'flask_app', 'core'),
- (True, 'pylons_app', 'core')])
+ (False, 'pylons_app')])
def test_ask_around_flask_core_route_post(self):
@@ -165,7 +162,7 @@ def test_ask_around_flask_core_route_post(self):
app = app.app
environ = {
- 'PATH_INFO': '/hello',
+ 'PATH_INFO': '/group/new',
'REQUEST_METHOD': 'POST',
}
wsgiref.util.setup_testing_defaults(environ)
@@ -330,7 +327,7 @@ def test_flask_core_route_is_served_by_flask(self):
app = self._get_test_app()
- res = app.get('/hello')
+ res = app.get('/')
eq_(res.environ['ckan.app'], 'flask_app')
@@ -562,7 +559,7 @@ def before_map(self, _map):
controller=self.controller, action='view')
# This one conflicts with a core Flask route
- _map.connect('/hello',
+ _map.connect('/about',
controller=self.controller, action='view')
_map.connect('/pylons_route_flask_url_for',
diff --git a/ckan/tests/test_common.py b/ckan/tests/test_common.py
--- a/ckan/tests/test_common.py
+++ b/ckan/tests/test_common.py
@@ -222,7 +222,7 @@ def test_params_also_works_on_flask_request(self):
app = helpers._get_test_app()
- with app.flask_app.test_request_context(u'/hello?a=1'):
+ with app.flask_app.test_request_context(u'/?a=1'):
assert u'a' in ckan_request.args
assert u'a' in ckan_request.params
@@ -231,7 +231,7 @@ def test_other_missing_attributes_raise_attributeerror_exceptions(self):
app = helpers._get_test_app()
- with app.flask_app.test_request_context(u'/hello?a=1'):
+ with app.flask_app.test_request_context(u'/?a=1'):
assert_raises(AttributeError, getattr, ckan_request, u'not_here')
diff --git a/ckanext/example_flask_iblueprint/tests/test_routes.py b/ckanext/example_flask_iblueprint/tests/test_routes.py
--- a/ckanext/example_flask_iblueprint/tests/test_routes.py
+++ b/ckanext/example_flask_iblueprint/tests/test_routes.py
@@ -24,28 +24,12 @@ def test_plugin_route(self):
eq_(u'Hello World, this is served from an extension', res.body)
- def test_plugin_route_core_pylons_override(self):
- u'''Test extension overrides pylons core route.'''
- res = self.app.get(u'/about')
-
- ok_(u'This is an about page served from an extention, overriding the pylons url.' in res.body)
-
def test_plugin_route_core_flask_override(self):
u'''Test extension overrides flask core route.'''
- res = self.app.get(u'/hello')
+ res = self.app.get(u'/')
ok_(u'Hello World, this is served from an extension, overriding the flask url.' in res.body)
-# TODO This won't work until the url_for work is merged
-# def test_plugin_route_core_flask_override_with_template(self):
-# u'''
-# Test extension overrides a python core route, rendering a core
-# template (home/about.html).
-# '''
-# res = self.app.get(u'/about_core')
-#
-# ok_(u'<title>About - CKAN</title>' in res.ubody)
-
def test_plugin_route_with_helper(self):
u'''
Test extension rendering with a helper method that exists shouldn't
| URL ‘/hello’ rule in public site
I suggest providing the /hello path only in debug mode.
### CKAN Version if known (or site URL)
2.8
### Please describe the expected behaviour
Ckan extension can determine whether to use /hello routing.
### Please describe the actual behaviour
Currently ckan core provides the "/hello" path by default.
In a production build, I think this is unnecessary information for users.
There is no way to remove "/hello" routing from an extension without modifying the core, and it must be redefined.
### What steps can be taken to reproduce the issue?
It is being routed on some sites based on ckan
eg)
https://demo.ckan.org/hello
https://data.stadt-zuerich.ch/hello
https://data.gov.ie/hello
https://ckan0.cf.opendata.inter.sandbox-toronto.ca/hello
| 2019-07-19T14:21:27 |
|
ckan/ckan | 4,981 | ckan__ckan-4981 | [
"4974"
] | 6660a9fc5bb8734995b350238046bc66805cde29 | diff --git a/ckan/migration/versions/091_0ffc0b277141_group_extra_group_id_index.py b/ckan/migration/versions/091_0ffc0b277141_group_extra_group_id_index.py
new file mode 100644
--- /dev/null
+++ b/ckan/migration/versions/091_0ffc0b277141_group_extra_group_id_index.py
@@ -0,0 +1,25 @@
+# encoding: utf-8
+
+"""group_extra group_id index
+
+Revision ID: 0ffc0b277141
+Revises: 980dcd44de4b
+Create Date: 2019-09-11 12:16:42.792661
+
+"""
+from alembic import op
+
+
+# revision identifiers, used by Alembic.
+revision = u'0ffc0b277141'
+down_revision = u'980dcd44de4b'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.create_index(u'idx_group_extra_group_id', u'group_extra', [u'group_id'])
+
+
+def downgrade():
+ op.drop_index(u'idx_group_extra_group_id')
diff --git a/ckan/migration/versions/092_01afcadbd8c0_resource_package_id_index.py b/ckan/migration/versions/092_01afcadbd8c0_resource_package_id_index.py
new file mode 100644
--- /dev/null
+++ b/ckan/migration/versions/092_01afcadbd8c0_resource_package_id_index.py
@@ -0,0 +1,26 @@
+# encoding: utf-8
+
+"""resource package_id index
+
+Revision ID: 01afcadbd8c0
+Revises: 0ffc0b277141
+Create Date: 2019-09-11 12:16:53.937813
+
+"""
+from alembic import op
+
+
+# revision identifiers, used by Alembic.
+revision = u'01afcadbd8c0'
+down_revision = u'0ffc0b277141'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.create_index(u'idx_package_resource_package_id', u'resource',
+ [u'package_id'])
+
+
+def downgrade():
+ op.drop_index(u'idx_package_resource_package_id')
| Database [performance] for group_extras and resource
Related to #3511
### CKAN Version if known (or site URL)
2.8.3
### Please describe the expected behaviour
Fetching from `group_extra` by `group_id` or from `resource` by `package_id` is fast.
### Please describe the actual behaviour
With enough data, both become slow. The former is especially visible when fetching `organization_list`.
### What steps can be taken to reproduce the issue?
Insert a lot of organizations with a translated `ckanext-fluent` `title_translated` field, then attempt to get a list of organizations with translated names.
### Proposed fix
Add database indices for `group_extra (group_id)` and `resource (package_id)`. These speed up the operations considerably.
| I would've included a PR, but master has transitioned to alembic and I haven't had the time yet to look into it.
The additions that you propose sound great to have on master (2.9) so a PR is most welcome. On previous releases we can suggest the change in the CHANGELOG so people can run it manually if needed. | 2019-09-11T12:28:53 |
|
ckan/ckan | 4,987 | ckan__ckan-4987 | [
"4420"
] | 16161d68e1a8b69a26211765df4d0de1f0165ad6 | diff --git a/ckan/lib/dictization/model_dictize.py b/ckan/lib/dictization/model_dictize.py
--- a/ckan/lib/dictization/model_dictize.py
+++ b/ckan/lib/dictization/model_dictize.py
@@ -313,9 +313,9 @@ def get_packages_for_this_group(group_, just_the_count=False):
}
if group_.is_organization:
- q['fq'] = 'owner_org:"{0}"'.format(group_.id)
+ q['fq'] = '+owner_org:"{0}"'.format(group_.id)
else:
- q['fq'] = 'groups:"{0}"'.format(group_.name)
+ q['fq'] = '+groups:"{0}"'.format(group_.name)
# Allow members of organizations to see private datasets.
if group_.is_organization:
| diff --git a/ckan/tests/lib/dictization/test_model_dictize.py b/ckan/tests/lib/dictization/test_model_dictize.py
--- a/ckan/tests/lib/dictization/test_model_dictize.py
+++ b/ckan/tests/lib/dictization/test_model_dictize.py
@@ -256,7 +256,9 @@ def test_group_dictize_with_package_list_limited_by_config(self):
def test_group_dictize_with_package_count(self):
# group_list_dictize calls it like this by default
group_ = factories.Group()
+ other_group_ = factories.Group()
factories.Dataset(groups=[{'name': group_['name']}])
+ factories.Dataset(groups=[{'name': other_group_['name']}])
group_obj = model.Session.query(model.Group).filter_by().first()
context = {'model': model, 'session': model.Session,
'dataset_counts': model_dictize.get_group_dataset_counts()
@@ -295,7 +297,9 @@ def test_group_dictize_for_org_with_package_list(self):
def test_group_dictize_for_org_with_package_count(self):
# group_list_dictize calls it like this by default
org_ = factories.Organization()
+ other_org_ = factories.Organization()
factories.Dataset(owner_org=org_['id'])
+ factories.Dataset(owner_org=other_org_['id'])
org_obj = model.Session.query(model.Group).filter_by().first()
context = {'model': model, 'session': model.Session,
'dataset_counts': model_dictize.get_group_dataset_counts()
| Dataset counts incorrect on Groups listing
After upgrading to CKAN 2.8.1, the dataset counts are incorrect on the group listing screen.
On the group listing screen (/group), the dataset count for each group is the full dataset count for the whole site. The correct count is shown on the screen for each individual group (/group/somegroup)
CKAN 2.8.1
/group
/group/somegroup
| Hello @inghamn I was able to reproduce the issue as per the details given by you. However, I find that when the "visibility" option of the data set is "private", then only it doesn't show the correct count.
Also, if you change the visibility status of the data set to "public", you will be able to see the correct count on `/group`.

-------------------------------------------------------------------
-----------------------------------------------

All of our datasets are Public.
The problem is not that each group count is zero. Rather each group count is the full count of all datasets on the server. The query does not seem to actually be filtering by group.
https://data.bloomington.in.gov/group
I've tried to reproduce this issue a number of times during these months but was unable to get reported behavior even once, on different CKAN versions. Could you try to disable all custom extensions (harvest, datajson, cob), rebuild Solr index and check, whether the problem still exists?
PS and could you also check solr logs when performing re-index?
I've disabled harvest, datasjon, and cob (our custom theme). I've also re-indexed the solr index, and attached the solr log. The result is the same, though. There are no errors in the solr logs.
I didn't realize the groups page is info coming from Solr. It must be an error in the solr queries for each of the groups.
[solr.log](https://github.com/ckan/ckan/files/2901411/solr.log)
With the knowledge that this is a Solr query error, I reviewed the logs and manually queried our Solr core. I think this an error in the code generating the solr queries for this screen. What's getting generated is:
```
fq=%2Bcapacity:public+groups:"operations"
```
and what should be generated is:
```
fq=capacity:public&fq=groups:"operations"
```
(I even typed it incorrectly in this comment. Solr queries are hard to read and type!)
I suspect it is caused by the code in /ckan/logic/action/get.py at line 1883.
```python
data_dict.setdefault('fq', '')
if not include_private:
data_dict['fq'] = '+capacity:public ' + data_dict['fq']
```
However, someone more familiary with ckan's building of Solr queries would know better than I. It looks like attempting to build up the filter queries as a single fq parameter string, rather than multiple fq parameters. | 2019-09-19T14:11:40 |
ckan/ckan | 5,024 | ckan__ckan-5024 | [
"4673"
] | 567bb0b959615316453297eeb78411974cd92611 | diff --git a/ckan/lib/mailer.py b/ckan/lib/mailer.py
--- a/ckan/lib/mailer.py
+++ b/ckan/lib/mailer.py
@@ -37,6 +37,7 @@ def _mail_recipient(recipient_name, recipient_email,
headers = {}
mail_from = config.get('smtp.mail_from')
+ reply_to = config.get('smtp.reply_to')
msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
for k, v in headers.items():
if k in msg.keys():
@@ -50,6 +51,8 @@ def _mail_recipient(recipient_name, recipient_email,
msg['To'] = Header(recipient, 'utf-8')
msg['Date'] = Utils.formatdate(time())
msg['X-Mailer'] = "CKAN %s" % ckan.__version__
+ if reply_to and reply_to != '':
+ msg['Reply-to'] = reply_to
# Send the email using Python's smtplib.
smtp_connection = smtplib.SMTP()
| diff --git a/ckan/tests/lib/test_mailer.py b/ckan/tests/lib/test_mailer.py
--- a/ckan/tests/lib/test_mailer.py
+++ b/ckan/tests/lib/test_mailer.py
@@ -233,3 +233,26 @@ def test_bad_smtp_host(self):
'headers': {'header1': 'value1'}}
assert_raises(mailer.MailerException,
mailer.mail_recipient, **test_email)
+
+ @helpers.change_config('smtp.reply_to', '[email protected]')
+ def test_reply_to(self):
+
+ msgs = self.get_smtp_messages()
+ assert_equal(msgs, [])
+
+ # send email
+ test_email = {'recipient_name': 'Bob',
+ 'recipient_email': '[email protected]',
+ 'subject': 'Meeting',
+ 'body': 'The meeting is cancelled.',
+ 'headers': {'header1': 'value1'}}
+ mailer.mail_recipient(**test_email)
+
+ # check it went to the mock smtp server
+ msgs = self.get_smtp_messages()
+ msg = msgs[0]
+
+ expected_from_header = "Reply-to: {}".format(
+ config.get('smtp.reply_to'))
+
+ assert_in(expected_from_header, msg[3])
| RFE: allow Reply-To header on emails
### CKAN Version if known (or site URL)
2.7.3
### Please describe the expected behaviour
We would like to send system emails that come from a real address (so we can catch bounces etc), but which don't reply to a real address when used by humans (ie use a 'no-reply' address as the Reply-To header).
### Please describe the actual behaviour
Only the 'From' address is configurable.
| 2019-10-14T13:11:13 |
|
ckan/ckan | 5,032 | ckan__ckan-5032 | [
"5031"
] | 7c4a97604eba5f941b26613e1ed49274130fb7e8 | diff --git a/ckan/lib/uploader.py b/ckan/lib/uploader.py
--- a/ckan/lib/uploader.py
+++ b/ckan/lib/uploader.py
@@ -214,7 +214,8 @@ def __init__(self, resource):
if url and config_mimetype_guess == 'file_ext':
self.mimetype = mimetypes.guess_type(url)[0]
- if isinstance(upload_field_storage, ALLOWED_UPLOAD_TYPES):
+ if bool(upload_field_storage) and \
+ isinstance(upload_field_storage, ALLOWED_UPLOAD_TYPES):
self.filesize = 0 # bytes
self.filename = upload_field_storage.filename
| diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py
--- a/ckan/tests/controllers/test_package.py
+++ b/ckan/tests/controllers/test_package.py
@@ -121,22 +121,24 @@ def test_complete_package_with_one_resource(self, app):
def test_complete_package_with_two_resources(self, app):
env, response = _get_package_new_page(app)
- form = response.forms["dataset-edit"]
- form["name"] = u"complete-package-with-two-resources"
+ form = response.forms['dataset-edit']
+ form['name'] = u'complete-package-with-two-resources'
- response = submit_and_follow(app, form, env, "save")
- form = response.forms["resource-edit"]
- form["url"] = u"http://example.com/resource0"
+ response = submit_and_follow(app, form, env, 'save')
+ form = response.forms['resource-edit']
+ form['url'] = u'http://example.com/resource0'
- response = submit_and_follow(app, form, env, "save", "again")
- form = response.forms["resource-edit"]
- form["url"] = u"http://example.com/resource1"
+ response = submit_and_follow(app, form, env, 'save', 'again')
+ form = response.forms['resource-edit']
+ form['url'] = u'http://example.com/resource1'
- submit_and_follow(app, form, env, "save", "go-metadata")
- pkg = model.Package.by_name(u"complete-package-with-two-resources")
- assert pkg.resources[0].url == u"http://example.com/resource0"
- assert pkg.resources[1].url == u"http://example.com/resource1"
- assert pkg.state == "active"
+ submit_and_follow(app, form, env, 'save', 'go-metadata')
+ pkg = model.Package.by_name(u'complete-package-with-two-resources')
+ assert pkg.resources[0].url == u'http://example.com/resource0'
+ assert pkg.resources[1].url == u'http://example.com/resource1'
+ assert pkg.state == 'active'
+
+ # resource upload is tested in TestExampleIUploaderPlugin
def test_previous_button_works(self, app):
env, response = _get_package_new_page(app)
diff --git a/ckan/tests/lib/test_uploader.py b/ckan/tests/lib/test_uploader.py
new file mode 100644
--- /dev/null
+++ b/ckan/tests/lib/test_uploader.py
@@ -0,0 +1,90 @@
+# encoding: utf-8
+import mock
+import tempfile
+import __builtin__ as builtins
+import flask
+import paste.fileapp
+import cStringIO
+
+from werkzeug.datastructures import FileStorage
+from pyfakefs import fake_filesystem
+from nose.tools import assert_equal as eq_
+
+from ckan.common import config
+import ckan.lib.uploader
+from ckan.lib.uploader import ResourceUpload
+from ckanext.example_iuploader.test.test_plugin import mock_open_if_open_fails
+
+
+fs = fake_filesystem.FakeFilesystem()
+fake_os = fake_filesystem.FakeOsModule(fs)
+
+
+class TestInitResourceUpload(object):
+ @mock.patch.object(ckan.lib.uploader, u'os', fake_os)
+ @mock.patch.object(builtins, u'open', side_effect=mock_open_if_open_fails)
+ @mock.patch.object(flask, u'send_file', side_effect=[b'DATA'])
+ @mock.patch.object(paste.fileapp, u'os', fake_os)
+ @mock.patch.object(config[u'pylons.h'], u'uploads_enabled',
+ return_value=True)
+ @mock.patch.object(ckan.lib.uploader, u'_storage_path', new=u'/doesnt_exist')
+ def test_resource_without_upload_with_old_werkzeug(
+ self, mock_uploads_enabled, mock_open, send_file):
+ # this test data is based on real observation using a browser
+ # and werkzeug 0.14.1
+ res = {u'clear_upload': u'true',
+ u'format': u'CSV',
+ u'url': u'https://example.com/data.csv',
+ u'description': u'',
+ u'upload': u'',
+ u'package_id': u'dataset1',
+ u'id': u'8a3a874e-5ee1-4e43-bdaf-e2569cf72344',
+ u'name': u'data.csv'}
+ res_upload = ResourceUpload(res)
+
+ eq_(res_upload.filename, None)
+
+ @mock.patch.object(ckan.lib.uploader, u'os', fake_os)
+ @mock.patch.object(builtins, u'open', side_effect=mock_open_if_open_fails)
+ @mock.patch.object(flask, u'send_file', side_effect=[b'DATA'])
+ @mock.patch.object(paste.fileapp, u'os', fake_os)
+ @mock.patch.object(config[u'pylons.h'], u'uploads_enabled',
+ return_value=True)
+ @mock.patch.object(ckan.lib.uploader, u'_storage_path', new=u'/doesnt_exist')
+ def test_resource_without_upload(
+ self, mock_uploads_enabled, mock_open, send_file):
+ # this test data is based on real observation using a browser
+ res = {u'clear_upload': u'true',
+ u'format': u'PNG',
+ u'url': u'https://example.com/data.csv',
+ u'description': u'',
+ u'upload': FileStorage(filename=u''),
+ u'package_id': u'dataset1',
+ u'id': u'8a3a874e-5ee1-4e43-bdaf-e2569cf72344',
+ u'name': u'data.csv'}
+ res_upload = ResourceUpload(res)
+
+ eq_(res_upload.filename, None)
+
+ @mock.patch.object(ckan.lib.uploader, u'os', fake_os)
+ @mock.patch.object(builtins, u'open', side_effect=mock_open_if_open_fails)
+ @mock.patch.object(flask, u'send_file', side_effect=[b'DATA'])
+ @mock.patch.object(paste.fileapp, u'os', fake_os)
+ @mock.patch.object(config[u'pylons.h'], u'uploads_enabled',
+ return_value=True)
+ @mock.patch.object(ckan.lib.uploader, u'_storage_path', new=u'/doesnt_exist')
+ def test_resource_with_upload(
+ self, mock_uploads_enabled, mock_open, send_file):
+ # this test data is based on real observation using a browser
+ res = {u'clear_upload': u'',
+ u'format': u'PNG',
+ u'url': u'https://example.com/data.csv',
+ u'description': u'',
+ u'upload': FileStorage(filename=u'data.csv', content_type=u'CSV'),
+ u'package_id': u'dataset1',
+ u'id': u'8a3a874e-5ee1-4e43-bdaf-e2569cf72344',
+ u'name': u'data.csv'}
+ res_upload = ResourceUpload(res)
+
+ eq_(res_upload.filesize, 0)
+ eq_(res_upload.filename, u'data.csv')
diff --git a/ckan/tests/logic/action/test_create.py b/ckan/tests/logic/action/test_create.py
--- a/ckan/tests/logic/action/test_create.py
+++ b/ckan/tests/logic/action/test_create.py
@@ -8,6 +8,8 @@
import mock
import pytest
+from werkzeug.datastructures import FileStorage as FlaskFileStorage
+
import ckan
import ckan.logic as logic
import ckan.model as model
@@ -26,9 +28,11 @@
fake_open = fake_filesystem.FakeFileOpen(fs)
-class FakeFileStorage(cgi.FieldStorage):
- def __init__(self, fp, filename):
- self.file = fp
+class FakeFileStorage(FlaskFileStorage):
+ content_type = None
+
+ def __init__(self, stream, filename):
+ self.stream = stream
self.filename = filename
self.name = "upload"
@@ -535,7 +539,7 @@ def test_mimetype_by_upload_by_file(self, mock_open):
NAZKO,1C08,1070,2016/01/05,20,31,,76,16,JAN-01,41
"""
)
- test_resource = FakeFileStorage(test_file, "")
+ test_resource = FakeFileStorage(test_file, "test.csv")
context = {}
params = {
diff --git a/ckan/tests/logic/action/test_update.py b/ckan/tests/logic/action/test_update.py
--- a/ckan/tests/logic/action/test_update.py
+++ b/ckan/tests/logic/action/test_update.py
@@ -6,6 +6,8 @@
import mock
import pytest
+from werkzeug.datastructures import FileStorage as FlaskFileStorage
+
import ckan
import ckan.lib.app_globals as app_globals
import ckan.logic as logic
@@ -24,6 +26,15 @@
fake_open = fake_filesystem.FakeFileOpen(fs)
+class FakeFileStorage(FlaskFileStorage):
+ content_type = None
+
+ def __init__(self, stream, filename):
+ self.stream = stream
+ self.filename = filename
+ self.name = "upload"
+
+
def mock_open_if_open_fails(*args, **kwargs):
try:
return real_open(*args, **kwargs)
@@ -810,18 +821,6 @@ def test_calling_with_only_id_doesnt_update_anything(self):
@pytest.mark.ckan_config("ckan.plugins", "image_view recline_view")
@pytest.mark.usefixtures("clean_db", "with_plugins")
class TestResourceUpdate(object):
- import cgi
-
- class FakeFileStorage(cgi.FieldStorage):
- def __init__(self, fp, filename):
- self.file = fp
- self.filename = filename
- self.name = "upload"
-
- def setup(self):
- import ckan.model as model
-
- model.repo.rebuild_db()
def test_url_only(self):
dataset = factories.Dataset()
@@ -1074,7 +1073,7 @@ def test_mimetype_by_upload_by_file(self, mock_open):
NAZKO,1C08,1070,2016/01/05,20,31,,76,16,JAN-01,41
"""
)
- update_resource = TestResourceUpdate.FakeFileStorage(
+ update_resource = FakeFileStorage(
update_file, "update_test"
)
@@ -1124,7 +1123,7 @@ def test_mimetype_by_upload_by_filename(self, mock_open):
}
"""
)
- test_resource = TestResourceUpdate.FakeFileStorage(
+ test_resource = FakeFileStorage(
test_file, "test.json"
)
dataset = factories.Dataset()
@@ -1147,7 +1146,7 @@ def test_mimetype_by_upload_by_filename(self, mock_open):
NAZKO,1C08,1070,2016/01/05,20,31,,76,16,JAN-01,41
"""
)
- update_resource = TestResourceUpdate.FakeFileStorage(
+ update_resource = FakeFileStorage(
update_file, "update_test.csv"
)
@@ -1219,7 +1218,7 @@ def test_size_of_resource_by_upload(self, mock_open):
}
"""
)
- test_resource = TestResourceUpdate.FakeFileStorage(
+ test_resource = FakeFileStorage(
test_file, "test.json"
)
dataset = factories.Dataset()
@@ -1242,7 +1241,7 @@ def test_size_of_resource_by_upload(self, mock_open):
NAZKO,1C08,1070,2016/01/05,20,31,,76,16,JAN-01,41
"""
)
- update_resource = TestResourceUpdate.FakeFileStorage(
+ update_resource = FakeFileStorage(
update_file, "update_test.csv"
)
| Resource URL gets changed to ___
### CKAN Version if known (or site URL)
latest master
### The probem
When I create or edit a resource using the web form, whatever I set the resource.url to be, it gets saved as something like this: `http://myckansite.com/dataset/713c8c32-cbd8-46ce-90fb-86de1f0811d2/resource/59c0e90c-11e2-4d7f-af43-e098660745dc/download/___` (!)
It shouldn't change it. And the URL it sets it to gives a 404.
| I bisected to find the cause: https://github.com/ckan/ckan/commit/ea4ceb404d826a48b8e66872640e6ffffe1ee0f7
```
Date: Wed Aug 21 20:43:31 2019 +0100
Upgrade werkzeug
``` | 2019-10-18T18:13:59 |
ckan/ckan | 5,033 | ckan__ckan-5033 | [
"5027"
] | f717999a1a4e63ecc192cb4dfe5a7506b7c8cff0 | diff --git a/ckan/lib/dictization/model_save.py b/ckan/lib/dictization/model_save.py
--- a/ckan/lib/dictization/model_save.py
+++ b/ckan/lib/dictization/model_save.py
@@ -46,7 +46,11 @@ def resource_dict_save(res_dict, context):
continue
if key in fields:
if isinstance(getattr(obj, key), datetime.datetime):
- if getattr(obj, key).isoformat() == value:
+ if isinstance(value, string_types):
+ db_value = getattr(obj, key).isoformat()
+ else:
+ db_value = getattr(obj, key)
+ if db_value == value:
continue
if key == 'last_modified' and not new:
obj.url_changed = True
| Updating/Adding a Resource sets obj.url_changed = True to all other uploaded resources of the package
### CKAN Version if known (or site URL)
2.8.3 but as far as tested it also happens in master
### Please describe the expected behaviour
Updating or adding a new resource to the package shouldn't set `obj.url_changed=True` in other resources with uploaded files of the same package.
### Please describe the actual behaviour
* Each time a resource is created if a file is uploaded, the `__init__` method of ResourceUpload sets the `resource['last_modified']` field.
* Later, each time a new resource is added to the Package (or an existing resource of that package edited) when executing `resource_dict_save` the `obj.url_changed` is set to true due to this condition: https://github.com/ckan/ckan/blob/f717999a1a4e63ecc192cb4dfe5a7506b7c8cff0/ckan/lib/dictization/model_save.py#L51
This causes the `IResourceURLChanged` interface to be notified even when nothing changed, but regardless that, it is confusing of why it is set to `True` if nothing changed on the resource.
### What steps can be taken to reproduce the issue?
- Create a new CKAN instance
- Add a Package
- Add `resource_1` to it. *This resource should be a file to be uploaded*.
- Add a `resource_2` to the same package
This last action will call `resource_dict_save` for each resource of the package and when executing it for `resource_1`it will set `obj.url_changed` in the mentioned condition.
| @pdelboca This is obviously a bug, and the problem is right above the line you linked:
https://github.com/ckan/ckan/blob/f717999a1a4e63ecc192cb4dfe5a7506b7c8cff0/ckan/lib/dictization/model_save.py#L48:L50
This assumes that `value` (ie the value of `resource['last_modified']`) is a string, but [that is not the case](https://github.com/ckan/ckan/blob/f717999a1a4e63ecc192cb4dfe5a7506b7c8cff0/ckan/lib/uploader.py#L222). And so the loop is never stopped if the dates are the same (ie the upload didn't change).
We need something like:
```diff
diff --git a/ckan/lib/dictization/model_save.py b/ckan/lib/dictization/model_save.py
index a9514e648..27f2f5542 100644
--- a/ckan/lib/dictization/model_save.py
+++ b/ckan/lib/dictization/model_save.py
@@ -46,7 +46,11 @@ def resource_dict_save(res_dict, context):
continue
if key in fields:
if isinstance(getattr(obj, key), datetime.datetime):
- if getattr(obj, key).isoformat() == value:
+ if isinstance(value, string_types):
+ db_value = getattr(obj, key).isoformat()
+ else:
+ db_value = getattr(obj, key)
+ if db_value == value:
continue
if key == 'last_modified' and not new:
obj.url_changed = True
```
Can you submit a PR? This should be backported.
Great! I will submit the PR thanks! | 2019-10-20T17:25:28 |
|
ckan/ckan | 5,038 | ckan__ckan-5038 | [
"5037"
] | 4fad994d846719159acc3525b22a2412dfd4a40e | diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py
--- a/ckanext/datastore/backend/postgres.py
+++ b/ckanext/datastore/backend/postgres.py
@@ -365,6 +365,10 @@ def _where_clauses(data_dict, fields_types):
if field not in fields_types:
continue
field_array_type = _is_array_type(fields_types[field])
+ # "%" needs to be escaped as "%%" in any query going to
+ # connection.execute, otherwise it will think the "%" is for
+ # substituting a bind parameter
+ field = field.replace('%', '%%')
if isinstance(value, list) and not field_array_type:
clause_str = (u'"{0}" in ({1})'.format(field,
','.join(['%s'] * len(value))))
@@ -1148,8 +1152,9 @@ def upsert_data(context, data_dict):
WHERE ({primary_key}) = ({primary_value}));
'''.format(
res_id=data_dict['resource_id'],
- columns=u', '.join([u'"{0}"'.format(field)
- for field in used_field_names]),
+ columns=u', '.join([
+ u'"{0}"'.format(field.replace('%', '%%'))
+ for field in used_field_names]),
values=u', '.join(['%s::nested'
if field['type'] == 'nested' else '%s'
for field in used_fields]),
| diff --git a/ckan/tests/legacy/test_coding_standards.py b/ckan/tests/legacy/test_coding_standards.py
--- a/ckan/tests/legacy/test_coding_standards.py
+++ b/ckan/tests/legacy/test_coding_standards.py
@@ -462,7 +462,6 @@ class TestPep8(object):
'ckanext/datastore/logic/action.py',
'ckanext/datastore/tests/test_create.py',
'ckanext/datastore/tests/test_search.py',
- 'ckanext/datastore/tests/test_upsert.py',
'ckanext/example_idatasetform/plugin.py',
'ckanext/example_itemplatehelpers/plugin.py',
'ckanext/multilingual/plugin.py',
diff --git a/ckanext/datastore/tests/test_search.py b/ckanext/datastore/tests/test_search.py
--- a/ckanext/datastore/tests/test_search.py
+++ b/ckanext/datastore/tests/test_search.py
@@ -436,6 +436,28 @@ def test_search_limit_config_combination(self):
{u'the year': 2015, u'_id': 2}])
assert_equals(result['limit'], 2)
+ def test_search_filter_with_percent_in_column_name(self):
+ resource = factories.Resource()
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'bo%ok', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [
+ {'id': '1%',
+ 'bo%ok': u'El Nino',
+ 'author': 'Torres'}],
+ }
+ helpers.call_action('datastore_create', **data)
+
+ search_data = {
+ 'resource_id': resource['id'],
+ 'filters': {u'bo%ok': 'El Nino'}}
+ result = helpers.call_action('datastore_search', **search_data)
+ assert_equals(result['total'], 1)
+
class TestDatastoreSearchLegacyTests(DatastoreLegacyTestBase):
sysadmin_user = None
diff --git a/ckanext/datastore/tests/test_upsert.py b/ckanext/datastore/tests/test_upsert.py
--- a/ckanext/datastore/tests/test_upsert.py
+++ b/ckanext/datastore/tests/test_upsert.py
@@ -2,23 +2,356 @@
import json
import datetime
-from nose.tools import assert_equal, assert_not_equal
-import sqlalchemy.orm as orm
+from nose.tools import assert_equal, assert_not_equal, assert_raises, assert_in
import ckan.lib.create_test_data as ctd
import ckan.model as model
import ckan.tests.helpers as helpers
import ckan.tests.factories as factories
-from ckan.plugins.toolkit import ValidationError
+from ckan.plugins.toolkit import ValidationError, NotAuthorized
import ckanext.datastore.backend.postgres as db
from ckanext.datastore.tests.helpers import (
- set_url_type, DatastoreFunctionalTestBase, DatastoreLegacyTestBase,
+ set_url_type, DatastoreFunctionalTestBase,
when_was_last_analyze)
+def _search(resource_id):
+ return helpers.call_action(
+ u'datastore_search',
+ resource_id=resource_id)
+
+
class TestDatastoreUpsert(DatastoreFunctionalTestBase):
+ # Test action 'datastore_upsert' with 'method': 'upsert'
+
+ def test_upsert_requires_auth(self):
+ resource = factories.Resource(url_type=u'datastore')
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'}],
+ 'records': [],
+ }
+ helpers.call_action('datastore_create', **data)
+
+ data = {
+ 'resource_id': resource['id']
+ }
+ with assert_raises(NotAuthorized) as context:
+ helpers.call_action(
+ 'datastore_upsert',
+ context={'user': '', 'ignore_auth': False},
+ **data)
+ assert_in(u'Action datastore_upsert requires an authenticated user',
+ str(context.exception))
+
+ def test_upsert_empty_fails(self):
+ resource = factories.Resource(url_type=u'datastore')
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'}],
+ 'records': [],
+ }
+ helpers.call_action('datastore_create', **data)
+
+ data = {} # empty
+ with assert_raises(ValidationError) as context:
+ helpers.call_action('datastore_upsert', **data)
+ assert_in(u"'Missing value'",
+ str(context.exception))
+
+ def test_basic_as_update(self):
+ resource = factories.Resource()
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [
+ {'id': '1',
+ 'book': u'El Niño',
+ 'author': 'Torres'}],
+ }
+ helpers.call_action('datastore_create', **data)
+
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'method': 'upsert',
+ 'records': [
+ {'id': '1',
+ 'book': u'The boy',
+ 'author': u'F Torres'}],
+ }
+ helpers.call_action('datastore_upsert', **data)
+
+ search_result = _search(resource['id'])
+ assert_equal(search_result['total'], 1)
+ assert_equal(search_result['records'][0]['book'], 'The boy')
+ assert_equal(search_result['records'][0]['author'], 'F Torres')
+
+ def test_basic_as_insert(self):
+ resource = factories.Resource()
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [
+ {'id': '1',
+ 'book': u'El Niño',
+ 'author': 'Torres'}],
+ }
+ helpers.call_action('datastore_create', **data)
+
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'method': 'upsert',
+ 'records': [
+ {'id': '2',
+ 'book': u'The boy',
+ 'author': u'F Torres'}],
+ }
+ helpers.call_action('datastore_upsert', **data)
+
+ search_result = _search(resource['id'])
+ assert_equal(search_result['total'], 2)
+ assert_equal(search_result['records'][0]['book'], u'El Niño')
+ assert_equal(search_result['records'][1]['book'], u'The boy')
+
+ def test_upsert_only_one_field(self):
+ resource = factories.Resource()
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [
+ {'id': '1',
+ 'book': u'El Niño',
+ 'author': 'Torres'}],
+ }
+ helpers.call_action('datastore_create', **data)
+
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'method': 'upsert',
+ 'records': [
+ {'id': '1',
+ 'book': u'The boy'}], # not changing the author
+ }
+ helpers.call_action('datastore_upsert', **data)
+
+ search_result = _search(resource['id'])
+ assert_equal(search_result['total'], 1)
+ assert_equal(search_result['records'][0]['book'], 'The boy')
+ assert_equal(search_result['records'][0]['author'], 'Torres')
+
+ def test_field_types(self):
+ resource = factories.Resource(url_type='datastore')
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': u'b\xfck',
+ 'fields': [{'id': u'b\xfck', 'type': 'text'},
+ {'id': 'author', 'type': 'text'},
+ {'id': 'nested', 'type': 'json'},
+ {'id': 'characters', 'type': 'text[]'},
+ {'id': 'published'}],
+ 'records': [{u'b\xfck': 'annakarenina', 'author': 'tolstoy',
+ 'published': '2005-03-01',
+ 'nested': ['b', {'moo': 'moo'}]},
+ {u'b\xfck': 'warandpeace', 'author': 'tolstoy',
+ 'nested': {'a': 'b'}},
+ {'author': 'adams',
+ 'characters': ['Arthur', 'Marvin'],
+ 'nested': {'foo': 'bar'},
+ u'b\xfck': u'guide to the galaxy'}]
+ }
+ helpers.call_action('datastore_create', **data)
+
+ data = {
+ 'resource_id': resource['id'],
+ 'method': 'upsert',
+ 'records': [{
+ 'author': 'adams',
+ 'characters': ['Bob', 'Marvin'],
+ 'nested': {'baz': 3},
+ u'b\xfck': u'guide to the galaxy'}]
+ }
+ helpers.call_action('datastore_upsert', **data)
+
+ search_result = _search(resource['id'])
+ assert_equal(search_result['total'], 3)
+ assert_equal(search_result['records'][0]['published'],
+ u'2005-03-01T00:00:00') # i.e. stored in db as datetime
+ assert_equal(search_result['records'][2]['author'], 'adams')
+ assert_equal(search_result['records'][2]['characters'],
+ ['Bob', 'Marvin'])
+ assert_equal(search_result['records'][2]['nested'], {'baz': 3})
+
+ def test_percent(self):
+ resource = factories.Resource()
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'bo%ok', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [
+ {'id': '1%',
+ 'bo%ok': u'El Niño',
+ 'author': 'Torres'}],
+ }
+ helpers.call_action('datastore_create', **data)
+
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'method': 'upsert',
+ 'records': [
+ {'id': '1%',
+ 'bo%ok': u'The % boy',
+ 'author': u'F Torres'},
+ {'id': '2%',
+ 'bo%ok': u'Gu%ide',
+ 'author': u'Adams'}],
+ }
+ helpers.call_action('datastore_upsert', **data)
+
+ search_result = _search(resource['id'])
+ assert_equal(search_result['total'], 2)
+ assert_equal(search_result['records'][0]['bo%ok'], 'The % boy')
+ assert_equal(search_result['records'][1]['bo%ok'], 'Gu%ide')
+
+ def test_missing_key(self):
+ resource = factories.Resource()
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [{'id': '1',
+ 'book': 'guide',
+ 'author': 'adams'}],
+ }
+ helpers.call_action('datastore_create', **data)
+
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'method': 'upsert',
+ 'records': [
+ { # no key
+ 'book': u'El Niño',
+ 'author': 'Torres'}],
+ }
+ with assert_raises(ValidationError) as context:
+ helpers.call_action('datastore_upsert', **data)
+ assert_in(u'fields "id" are missing', str(context.exception))
+
+ def test_non_existing_field(self):
+ resource = factories.Resource(url_type='datastore')
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': u'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [],
+ }
+ helpers.call_action('datastore_create', **data)
+
+ data = {
+ 'resource_id': resource['id'],
+ 'method': 'upsert',
+ 'records': [{'id': '1',
+ 'dummy': 'tolkien'}] # key not known
+ }
+
+ with assert_raises(ValidationError) as context:
+ helpers.call_action('datastore_upsert', **data)
+ assert_in(u'fields "dummy" do not exist', str(context.exception))
+
+ def test_upsert_works_with_empty_list_in_json_field(self):
+ resource = factories.Resource()
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'nested', 'type': 'json'}],
+ 'records': [
+ {'id': '1',
+ 'nested': {'foo': 'bar'}}
+ ],
+ }
+ helpers.call_action('datastore_create', **data)
+
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'method': 'upsert',
+ 'records': [
+ {'id': '1',
+ 'nested': []}], # empty list
+ }
+ helpers.call_action('datastore_upsert', **data)
+
+ search_result = _search(resource['id'])
+ assert_equal(search_result['total'], 1)
+ assert_equal(search_result['records'][0]['nested'], [])
+
+ def test_delete_field_value(self):
+ resource = factories.Resource()
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [
+ {'id': '1',
+ 'book': u'El Niño',
+ 'author': 'Torres'}],
+ }
+ helpers.call_action('datastore_create', **data)
+
+ data = {
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'method': 'upsert',
+ 'records': [
+ {'id': '1',
+ 'book': None}],
+ }
+ helpers.call_action('datastore_upsert', **data)
+
+ search_result = _search(resource['id'])
+ assert_equal(search_result['total'], 1)
+ assert_equal(search_result['records'][0]['book'], None)
+ assert_equal(search_result['records'][0]['author'], 'Torres')
+
def test_upsert_doesnt_crash_with_json_field(self):
resource = factories.Resource()
data = {
@@ -94,7 +427,8 @@ def test_dry_run_type_error(self):
records=[{u'spam': u'SPAM'}, {u'spam': u'EGGS'}],
dry_run=True)
except ValidationError as ve:
- assert_equal(ve.error_dict['records'],
+ assert_equal(
+ ve.error_dict['records'],
[u'invalid input syntax for type numeric: "SPAM"'])
else:
assert 0, 'error not raised'
@@ -126,7 +460,7 @@ def test_dry_run_trigger_error(self):
dry_run=True)
except ValidationError as ve:
assert_equal(ve.error_dict['records'],
- [u'"EGGS"? Yeeeeccch!'])
+ [u'"EGGS"? Yeeeeccch!'])
else:
assert 0, 'error not raised'
@@ -172,519 +506,244 @@ def test_calculate_record_count(self):
assert_not_equal(last_analyze, None)
-class TestDatastoreUpsertLegacyTests(DatastoreLegacyTestBase):
- sysadmin_user = None
- normal_user = None
-
- @classmethod
- def setup_class(cls):
- cls.app = helpers._get_test_app()
- super(TestDatastoreUpsertLegacyTests, cls).setup_class()
- ctd.CreateTestData.create()
- cls.sysadmin_user = model.User.get('testsysadmin')
- cls.normal_user = model.User.get('annafan')
- set_url_type(
- model.Package.get('annakarenina').resources, cls.sysadmin_user)
- resource = model.Package.get('annakarenina').resources[0]
- cls.data = {
- 'resource_id': resource.id,
- 'fields': [{'id': u'b\xfck', 'type': 'text'},
- {'id': 'author', 'type': 'text'},
- {'id': 'nested', 'type': 'json'},
- {'id': 'characters', 'type': 'text[]'},
- {'id': 'published'}],
- 'primary_key': u'b\xfck',
- 'records': [{u'b\xfck': 'annakarenina', 'author': 'tolstoy',
- 'published': '2005-03-01', 'nested': ['b', {'moo': 'moo'}]},
- {u'b\xfck': 'warandpeace', 'author': 'tolstoy',
- 'nested': {'a':'b'}}
- ]
- }
- postparams = '%s=1' % json.dumps(cls.data)
- auth = {'Authorization': str(cls.sysadmin_user.apikey)}
- res = cls.app.post('/api/action/datastore_create', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
- assert res_dict['success'] is True
-
- engine = db.get_write_engine()
- cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine))
+class TestDatastoreInsert(DatastoreFunctionalTestBase):
+ # Test action 'datastore_upsert' with 'method': 'insert'
- def test_upsert_requires_auth(self):
+ def test_basic_insert(self):
+ resource = factories.Resource()
data = {
- 'resource_id': self.data['resource_id']
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
}
- postparams = '%s=1' % json.dumps(data)
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- status=403)
- res_dict = json.loads(res.body)
- assert res_dict['success'] is False
-
- def test_upsert_empty_fails(self):
- postparams = '%s=1' % json.dumps({})
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth, status=409)
- res_dict = json.loads(res.body)
- assert res_dict['success'] is False
-
- def test_upsert_basic(self):
- c = self.Session.connection()
- results = c.execute('select 1 from "{0}"'.format(self.data['resource_id']))
- assert results.rowcount == 2
- self.Session.remove()
-
- hhguide = u"hitchhiker's guide to the galaxy"
+ helpers.call_action('datastore_create', **data)
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'upsert',
- 'records': [{
- 'author': 'adams',
- 'nested': {'a': 2, 'b': {'c': 'd'}},
- 'characters': ['Arthur Dent', 'Marvin'],
- 'nested': {'foo': 'bar'},
- u'b\xfck': hhguide}]
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'method': 'insert',
+ 'records': [
+ {'id': '1',
+ 'book': u'El Niño',
+ 'author': 'Torres'}],
}
+ helpers.call_action('datastore_upsert', **data)
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is True
-
- c = self.Session.connection()
- results = c.execute('select * from "{0}"'.format(self.data['resource_id']))
- assert results.rowcount == 3
-
- records = results.fetchall()
- assert records[2][u'b\xfck'] == hhguide
- assert records[2].author == 'adams'
- assert records[2].characters == ['Arthur Dent', 'Marvin']
- assert json.loads(records[2].nested.json) == {'foo': 'bar'}
- self.Session.remove()
-
- c = self.Session.connection()
- results = c.execute("select * from \"{0}\" where author='{1}'".format(self.data['resource_id'], 'adams'))
- assert results.rowcount == 1
- self.Session.remove()
-
- # upsert only the publish date
+ search_result = _search(resource['id'])
+ assert_equal(search_result['total'], 1)
+ assert_equal(search_result['fields'], [
+ {u'id': '_id', u'type': 'int'},
+ {u'id': u'id', u'type': u'text'},
+ {u'id': u'book', u'type': u'text'},
+ {u'id': u'author', u'type': u'text'}
+ ])
+ assert_equal(
+ search_result['records'][0],
+ {u'book':
+ u'El Ni\xf1o',
+ u'_id': 1,
+ u'id': u'1',
+ u'author': u'Torres'})
+
+ def test_non_existing_field(self):
+ resource = factories.Resource(url_type='datastore')
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'upsert',
- 'records': [{'published': '1979-1-1', u'b\xfck': hhguide}]
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': u'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [],
}
+ helpers.call_action('datastore_create', **data)
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is True
-
- c = self.Session.connection()
- results = c.execute('select * from "{0}"'.format(self.data['resource_id']))
- assert results.rowcount == 3
-
- records = results.fetchall()
- assert records[2][u'b\xfck'] == hhguide
- assert records[2].author == 'adams'
- assert records[2].published == datetime.datetime(1979, 1, 1)
- self.Session.remove()
-
- # delete publish date
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'upsert',
- 'records': [{u'b\xfck': hhguide, 'published': None}]
+ 'resource_id': resource['id'],
+ 'method': 'insert',
+ 'records': [{'id': '1',
+ 'dummy': 'tolkien'}] # key not known
}
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is True
-
- c = self.Session.connection()
- results = c.execute('select * from "{0}"'.format(self.data['resource_id']))
- assert results.rowcount == 3
-
- records = results.fetchall()
- assert records[2][u'b\xfck'] == hhguide
- assert records[2].author == 'adams'
- assert records[2].published == None
- self.Session.remove()
+ with assert_raises(ValidationError) as context:
+ helpers.call_action('datastore_upsert', **data)
+ assert_in(u'row "1" has extra keys "dummy"', str(context.exception))
+ def test_key_already_exists(self):
+ resource = factories.Resource()
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'upsert',
- 'records': [{'author': 'tolkien', u'b\xfck': 'the hobbit'}]
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': 'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [{'id': '1',
+ 'book': 'guide',
+ 'author': 'adams'}],
}
+ helpers.call_action('datastore_create', **data)
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is True
-
- c = self.Session.connection()
- results = c.execute('select * from "{0}"'.format(self.data['resource_id']))
- assert results.rowcount == 4
-
- records = results.fetchall()
- assert records[3][u'b\xfck'] == 'the hobbit'
- assert records[3].author == 'tolkien'
- self.Session.remove()
-
- # test % in records
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'upsert',
- 'records': [{'author': 'tol % kien', u'b\xfck': 'the % hobbit'}]
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'method': 'insert',
+ 'records': [
+ {'id': '1', # already exists
+ 'book': u'El Niño',
+ 'author': 'Torres'}],
}
+ with assert_raises(ValidationError) as context:
+ helpers.call_action('datastore_upsert', **data)
+ assert_in(u'duplicate key value violates unique constraint',
+ str(context.exception))
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
- assert res_dict['success'] is True
+class TestDatastoreUpdate(DatastoreFunctionalTestBase):
+ # Test action 'datastore_upsert' with 'method': 'update'
- def test_upsert_missing_key(self):
+ def test_basic(self):
+ resource = factories.Resource(url_type='datastore')
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'upsert',
- 'records': [{'author': 'tolkien'}]
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': u'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [
+ {'id': '1',
+ 'book': u'El Niño',
+ 'author': 'Torres'}],
}
+ helpers.call_action('datastore_create', **data)
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth, status=409)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is False
-
- def test_upsert_non_existing_field(self):
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'upsert',
- 'records': [{u'b\xfck': 'annakarenina', 'dummy': 'tolkien'}]
+ 'resource_id': resource['id'],
+ 'method': 'update',
+ 'records': [
+ {'id': '1',
+ 'book': u'The boy'}],
}
+ helpers.call_action('datastore_upsert', **data)
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth, status=409)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is False
-
- def test_upsert_works_with_empty_list_in_json_field(self):
- hhguide = u"hitchhiker's guide to the galaxy"
+ search_result = _search(resource['id'])
+ assert_equal(search_result['total'], 1)
+ assert_equal(search_result['records'][0]['book'], 'The boy')
+ assert_equal(search_result['records'][0]['author'], 'Torres')
+ def test_field_types(self):
+ resource = factories.Resource(url_type='datastore')
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'upsert',
- 'records': [{
- 'nested': [],
- u'b\xfck': hhguide}]
- }
-
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
- assert res_dict['success'] is True, res_dict
-
- c = self.Session.connection()
- results = c.execute('select * from "{0}"'.format(data['resource_id']))
- record = [r for r in results.fetchall() if r[2] == hhguide]
- self.Session.remove()
- assert len(record) == 1, record
- assert_equal(json.loads(record[0][4].json),
- data['records'][0]['nested'])
-
-
-
-class TestDatastoreInsertLegacyTests(DatastoreLegacyTestBase):
- sysadmin_user = None
- normal_user = None
-
- @classmethod
- def setup_class(cls):
- cls.app = helpers._get_test_app()
- super(TestDatastoreInsertLegacyTests, cls).setup_class()
- ctd.CreateTestData.create()
- cls.sysadmin_user = model.User.get('testsysadmin')
- cls.normal_user = model.User.get('annafan')
- set_url_type(
- model.Package.get('annakarenina').resources, cls.sysadmin_user)
- resource = model.Package.get('annakarenina').resources[0]
- cls.data = {
- 'resource_id': resource.id,
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': u'b\xfck',
'fields': [{'id': u'b\xfck', 'type': 'text'},
{'id': 'author', 'type': 'text'},
{'id': 'nested', 'type': 'json'},
{'id': 'characters', 'type': 'text[]'},
{'id': 'published'}],
- 'primary_key': u'b\xfck',
'records': [{u'b\xfck': 'annakarenina', 'author': 'tolstoy',
- 'published': '2005-03-01', 'nested': ['b', {'moo': 'moo'}]},
+ 'published': '2005-03-01',
+ 'nested': ['b', {'moo': 'moo'}]},
{u'b\xfck': 'warandpeace', 'author': 'tolstoy',
- 'nested': {'a':'b'}}
- ]
- }
- postparams = '%s=1' % json.dumps(cls.data)
- auth = {'Authorization': str(cls.sysadmin_user.apikey)}
- res = cls.app.post('/api/action/datastore_create', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
- assert res_dict['success'] is True
-
- engine = db.get_write_engine()
- cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine))
-
- def test_insert_non_existing_field(self):
- data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'insert',
- 'records': [{u'b\xfck': 'the hobbit', 'dummy': 'tolkien'}]
- }
-
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth, status=409)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is False
-
- def test_insert_with_index_violation(self):
- data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'insert',
- 'records': [{u'b\xfck': 'annakarenina'}]
+ 'nested': {'a': 'b'}},
+ {'author': 'adams',
+ 'characters': ['Arthur', 'Marvin'],
+ 'nested': {'foo': 'bar'},
+ u'b\xfck': u'guide to the galaxy'}]
}
+ helpers.call_action('datastore_create', **data)
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth, status=409)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is False
-
- def test_insert_basic(self):
- hhguide = u"hitchhiker's guide to the galaxy"
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'insert',
- 'records': [{
- 'author': 'adams',
- 'characters': ['Arthur Dent', 'Marvin'],
- 'nested': {'foo': 'bar', 'baz': 3},
- u'b\xfck': hhguide}]
- }
-
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is True
-
- c = self.Session.connection()
- results = c.execute('select * from "{0}"'.format(self.data['resource_id']))
- self.Session.remove()
-
- assert results.rowcount == 3
-
-
-class TestDatastoreUpdateLegacyTests(DatastoreLegacyTestBase):
- sysadmin_user = None
- normal_user = None
-
- @classmethod
- def setup_class(cls):
- cls.app = helpers._get_test_app()
- super(TestDatastoreUpdateLegacyTests, cls).setup_class()
- ctd.CreateTestData.create()
- cls.sysadmin_user = model.User.get('testsysadmin')
- cls.normal_user = model.User.get('annafan')
- set_url_type(
- model.Package.get('annakarenina').resources, cls.sysadmin_user)
- resource = model.Package.get('annakarenina').resources[0]
- hhguide = u"hitchhiker's guide to the galaxy"
- cls.data = {
- 'resource_id': resource.id,
- 'fields': [{'id': u'b\xfck', 'type': 'text'},
- {'id': 'author', 'type': 'text'},
- {'id': 'nested', 'type': 'json'},
- {'id': 'characters', 'type': 'text[]'},
- {'id': 'published'}],
- 'primary_key': u'b\xfck',
- 'records': [{u'b\xfck': 'annakarenina', 'author': 'tolstoy',
- 'published': '2005-03-01', 'nested': ['b', {'moo': 'moo'}]},
- {u'b\xfck': 'warandpeace', 'author': 'tolstoy',
- 'nested': {'a':'b'}},
- {'author': 'adams',
- 'characters': ['Arthur Dent', 'Marvin'],
- 'nested': {'foo': 'bar'},
- u'b\xfck': hhguide}
- ]
- }
- postparams = '%s=1' % json.dumps(cls.data)
- auth = {'Authorization': str(cls.sysadmin_user.apikey)}
- res = cls.app.post('/api/action/datastore_create', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
- assert res_dict['success'] is True
-
- engine = db.get_write_engine()
- cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine))
-
- def test_update_basic(self):
- c = self.Session.connection()
- results = c.execute('select 1 from "{0}"'.format(self.data['resource_id']))
- assert results.rowcount == 3, results.rowcount
- self.Session.remove()
-
- hhguide = u"hitchhiker's guide to the galaxy"
- data = {
- 'resource_id': self.data['resource_id'],
+ 'resource_id': resource['id'],
'method': 'update',
'records': [{
'author': 'adams',
- 'characters': ['Arthur Dent', 'Marvin'],
+ 'characters': ['Bob', 'Marvin'],
'nested': {'baz': 3},
- u'b\xfck': hhguide}]
+ u'b\xfck': u'guide to the galaxy'}]
}
+ helpers.call_action('datastore_upsert', **data)
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is True
-
- c = self.Session.connection()
- results = c.execute('select * from "{0}"'.format(self.data['resource_id']))
- assert results.rowcount == 3
-
- records = results.fetchall()
- assert records[2][u'b\xfck'] == hhguide
- assert records[2].author == 'adams'
- self.Session.remove()
-
- c = self.Session.connection()
- results = c.execute("select * from \"{0}\" where author='{1}'".format(self.data['resource_id'], 'adams'))
- assert results.rowcount == 1
- self.Session.remove()
+ search_result = _search(resource['id'])
+ assert_equal(search_result['total'], 3)
+ assert_equal(search_result['records'][2]['author'], 'adams')
+ assert_equal(search_result['records'][2]['characters'],
+ ['Bob', 'Marvin'])
+ assert_equal(search_result['records'][2]['nested'], {'baz': 3})
- # update only the publish date
+ def test_update_unspecified_key(self):
+ resource = factories.Resource(url_type='datastore')
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'update',
- 'records': [{'published': '1979-1-1', u'b\xfck': hhguide}]
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': u'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [],
}
+ helpers.call_action('datastore_create', **data)
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is True
-
- c = self.Session.connection()
- results = c.execute('select * from "{0}"'.format(self.data['resource_id']))
- self.Session.remove()
- assert results.rowcount == 3
-
- records = results.fetchall()
- assert records[2][u'b\xfck'] == hhguide
- assert records[2].author == 'adams'
- assert records[2].published == datetime.datetime(1979, 1, 1)
-
- # delete publish date
data = {
- 'resource_id': self.data['resource_id'],
+ 'resource_id': resource['id'],
'method': 'update',
- 'records': [{u'b\xfck': hhguide, 'published': None}]
+ 'records': [{'author': 'tolkien'}] # no id
}
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is True
+ with assert_raises(ValidationError) as context:
+ helpers.call_action('datastore_upsert', **data)
+ assert_in(u'fields "id" are missing', str(context.exception))
- c = self.Session.connection()
- results = c.execute('select * from "{0}"'.format(self.data['resource_id']))
- self.Session.remove()
- assert results.rowcount == 3
-
- records = results.fetchall()
- assert records[2][u'b\xfck'] == hhguide
- assert records[2].author == 'adams'
- assert records[2].published == None
-
- def test_update_missing_key(self):
+ def test_update_unknown_key(self):
+ resource = factories.Resource(url_type='datastore')
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'update',
- 'records': [{'author': 'tolkien'}]
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': u'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [],
}
+ helpers.call_action('datastore_create', **data)
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth, status=409)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is False
-
- def test_update_non_existing_key(self):
data = {
- 'resource_id': self.data['resource_id'],
+ 'resource_id': resource['id'],
'method': 'update',
- 'records': [{u'b\xfck': '', 'author': 'tolkien'}]
+ 'records': [{'id': '1', # unknown
+ 'author': 'tolkien'}]
}
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth, status=409)
- res_dict = json.loads(res.body)
-
- assert res_dict['success'] is False
+ with assert_raises(ValidationError) as context:
+ helpers.call_action('datastore_upsert', **data)
+ assert_in(u'key "[\\\'1\\\']" not found', str(context.exception))
def test_update_non_existing_field(self):
+ resource = factories.Resource(url_type='datastore')
data = {
- 'resource_id': self.data['resource_id'],
- 'method': 'update',
- 'records': [{u'b\xfck': 'annakarenina', 'dummy': 'tolkien'}]
+ 'resource_id': resource['id'],
+ 'force': True,
+ 'primary_key': u'id',
+ 'fields': [{'id': 'id', 'type': 'text'},
+ {'id': 'book', 'type': 'text'},
+ {'id': 'author', 'type': 'text'}],
+ 'records': [{'id': '1',
+ 'book': 'guide'}],
}
+ helpers.call_action('datastore_create', **data)
- postparams = '%s=1' % json.dumps(data)
- auth = {'Authorization': str(self.sysadmin_user.apikey)}
- res = self.app.post('/api/action/datastore_upsert', params=postparams,
- extra_environ=auth, status=409)
- res_dict = json.loads(res.body)
+ data = {
+ 'resource_id': resource['id'],
+ 'method': 'update',
+ 'records': [{'id': '1',
+ 'dummy': 'tolkien'}] # key not known
+ }
- assert res_dict['success'] is False
+ with assert_raises(ValidationError) as context:
+ helpers.call_action('datastore_upsert', **data)
+ assert_in(u'fields "dummy" do not exist', str(context.exception))
| "%" in CSV column name causes Datastore filter error
### CKAN Version if known (or site URL)
master
### Please describe the behaviour
I load a CSV into DataStore that contains a "%" character in the column names. I preview it in CKAN's web interface and then click to add a filter on the column.
<img width="860" alt="Screenshot 2019-10-22 at 23 11 40" src="https://user-images.githubusercontent.com/307612/67338894-a273db00-f519-11e9-99eb-045dda1f872d.png">
When I click "Update" the JS hangs on "Loading" because the ajax request has suffered this exception:
```
2019-10-22 22:11:42,018 ERROR [ckan.views.api] tuple index out of range
Traceback (most recent call last):
File "/vagrant/src/ckan/ckan/views/api.py", line 288, in action
result = function(context, request_data)
File "/vagrant/src/ckan/ckan/logic/__init__.py", line 466, in wrapped
result = _action(context, data_dict, **kw)
File "/vagrant/src/ckan/ckanext/datastore/logic/action.py", line 517, in datastore_search
result = backend.search(context, data_dict)
File "/vagrant/src/ckan/ckanext/datastore/backend/postgres.py", line 1916, in search
return search(context, data_dict)
File "/vagrant/src/ckan/ckanext/datastore/backend/postgres.py", line 1533, in search
return search_data(context, data_dict)
File "/vagrant/src/ckan/ckanext/datastore/backend/postgres.py", line 1305, in search_data
context, sql_string, where_values))[0][0]
File "/vagrant/src/ckan/ckanext/datastore/backend/postgres.py", line 664, in _execute_single_statement
results = context['connection'].execute(sql_string, [where_values])
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 982, in execute
return self._execute_text(object_, multiparams, params)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1155, in _execute_text
parameters,
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1248, in _execute_context
e, statement, parameters, cursor, context
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1468, in _handle_dbapi_exception
util.reraise(*exc_info)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1244, in _execute_context
cursor, statement, parameters, context
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 550, in do_execute
cursor.execute(statement, parameters)
IndexError: tuple index out of range
```
### What steps can be taken to reproduce the issue?
This is a sample CSV: https://github.com/ckan/ckanext-xloader/blob/5996dc76524bbe4657689a7a7f825f1dcff301df/ckanext/xloader/tests/samples/column_names.csv
Getting the CSV into DataStore is not straightforward - I used xloader on this branch: https://github.com/ckan/ckanext-xloader/pull/77
The error can be generated via the API:
```
$ ckanapi -r 'http://192.168.33.61:5000/' action datastore_search id=df38f3c0-5fff-42a6-ab5a-c8b23106d755 'filters={"place%": "Galway"}'
```
| 2019-10-22T22:50:31 |
|
ckan/ckan | 5,060 | ckan__ckan-5060 | [
"4800"
] | 746cd7e321fd7a16d8cc051b6854c2f7741bb8ca | diff --git a/ckan/logic/__init__.py b/ckan/logic/__init__.py
--- a/ckan/logic/__init__.py
+++ b/ckan/logic/__init__.py
@@ -1,4 +1,5 @@
-# encoding: utf-8
+
+#encoding: utf-8
import functools
import logging
@@ -6,13 +7,13 @@
import sys
from collections import defaultdict
-import formencode.validators
from six import string_types, text_type
import ckan.model as model
import ckan.authz as authz
import ckan.lib.navl.dictization_functions as df
import ckan.plugins as p
+import ckan.logic.validators as valid_one_of
from ckan.common import _, c
@@ -674,7 +675,7 @@ def get_validator(validator):
_validators_cache.update(validators)
validators = _import_module_functions('ckan.logic.validators')
_validators_cache.update(validators)
- _validators_cache.update({'OneOf': formencode.validators.OneOf})
+ _validators_cache.update({'OneOf': valid_one_of.one_of})
converters = _import_module_functions('ckan.logic.converters')
_validators_cache.update(converters)
diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py
--- a/ckan/logic/validators.py
+++ b/ckan/logic/validators.py
@@ -1,3 +1,4 @@
+
# encoding: utf-8
import collections
@@ -858,3 +859,14 @@ def email_validator(value, context):
if not email_pattern.match(value):
raise Invalid(_('Email {email} is not a valid format').format(email=value))
return value
+
+def one_of(list_of_value):
+ ''' Implementation of OneOf method
+ for Python Library Formencode
+ '''
+ def callable(value):
+ if value not in list_of_value:
+ raise Invalid(_('Value must be one of {}'.format(list_of_value)))
+ return value
+
+
| diff --git a/ckan/tests/logic/test_validators.py b/ckan/tests/logic/test_validators.py
--- a/ckan/tests/logic/test_validators.py
+++ b/ckan/tests/logic/test_validators.py
@@ -1,3 +1,4 @@
+
# encoding: utf-8
'''Unit tests for ckan/logic/validators.py.
@@ -667,4 +668,17 @@ def call_validator(*args, **kwargs):
errors[key] = []
call_validator(key, {key: url}, errors, None)
+class TestOneOfValidator(object):
+
+ def test_val_in_list(self):
+ cont = [1,2,3,4]
+ func = validators.one_of(cont)
+ assert_equals(func(1),1)
+
+ @raises_Invalid
+ def test_val_not_in_list(self):
+ cont = [1,2,3,4]
+ func = validators.one_of(cont)
+ raises_Invalid(func)(5)
+
# TODO: Need to test when you are not providing owner_org and the validator queries for the dataset with package_show
| Remove or replace formencode support
Although it's not explicitly listed as a requirement in `requirements.in` (because it's a Pylons requirement), formencode is used in two places:
* Its `OneOf` validator is added to the standard CKAN ones [here](https://github.com/ckan/ckan/blob/f43d6a572838c792193f3239827d04f9ffea9206/ckan/logic/__init__.py#L677).
* There is support for defining formencode validators in the CKAN schema ([docs](https://docs.ckan.org/en/2.8/extensions/adding-custom-fields.html?highlight=formencode#custom-validators), [code](https://github.com/ckan/ckan/blob/b9e45e2723d4abd70fa72b16ec4a0bebc795c56b/ckan/lib/navl/dictization_functions.py#L219:L233))
We need to remove the requirement, because it hasn't been updated in 3 years and its setup.py only lists support up until Python 3.5.
We use `OneOf` in core and someone might be using it in an extension so we need to implement it, but I doubt that anyone is using the second feature, and that we should drop it.
In the future we can add similar support for a better maintained validation library like [WTForms](https://wtforms.readthedocs.io/).
#### Approach
* Write our own implementation of `OneOf` in `validators.py` (and rename it to `one_of` for consistency, but keeping the old name for backwards compatibility).
* Remove all formencode bits from the code base.
#### Story points
2
| should I write it from scratch or just plug in WTForms in place of OneOf
and which branch should I implement this on
@batitaye sorry I missed your comment. You should use the current `master` branch as a base for this.
I'd prefer if you re-implemented `OneOf` on our code base to avoid the WTForms requirement for now. You can add it to [this module](https://github.com/ckan/ckan/blob/f43d6a572838c792193f3239827d04f9ffea9206/ckan/logic/validators.py) with the rest of the core ones.
Let me know if you need any more pointers and thanks for your help!
Hi @amercader , is there anyone working on this issue?
@iamarnavgarg No AFAICT. Unless @batitaye is working on it feel free to submit a PR. As I mentioned, OneOf should be re-implemented in our own [validators module](https://github.com/ckan/ckan/blob/f43d6a572838c792193f3239827d04f9ffea9206/ckan/logic/validators.py), and references to it updated.
@amercader in formencode OneOf is a class and so CKAN expects the implementation of OneOf to be an object but in [validators module](https://github.com/ckan/ckan/blob/f43d6a572838c792193f3239827d04f9ffea9206/ckan/logic/validators.py "validator.py") every validation implementations are functions so is there a reason why the new implementation of OneOf can't be a class?
Hi @amercader , I would like to inform you that, I have started working on this issue.
Hi @amercader , As per my analysis -`one_of(value,context)` should be defined at this location `/src/ckan/ckan/logic/validators.py` . In this defined function, it will take `value` as a parameter and a context parameter that contains a list or a tuple.
Then, using an iterator it will check whether the list(available in context parameter) contains the value. if it exists in the list/tuple, it will return the same value, otherwise raise an exception if not found.
Could you please confirm with my understanding ? | 2019-11-08T07:11:57 |
ckan/ckan | 5,093 | ckan__ckan-5093 | [
"5079"
] | 5b880ca71e7ecf4985a6d5c8bd92b0bd8c9106e8 | diff --git a/ckan/cli/generate.py b/ckan/cli/generate.py
--- a/ckan/cli/generate.py
+++ b/ckan/cli/generate.py
@@ -4,13 +4,21 @@
import sys
import click
from ckan.cli import error_shout
-from cookiecutter.main import cookiecutter
[email protected](name=u'generate',
- short_help=u"Generate empty extension files to expand CKAN.")
[email protected](
+ name=u'generate',
+ short_help=u"Generate empty extension files to expand CKAN.",
+ invoke_without_command=True,
+)
def generate():
- pass
+ try:
+ from cookiecutter.main import cookiecutter
+ except ImportError:
+ error_shout(u"`cookiecutter` library is missing from import path.")
+ error_shout(u"Make sure you have dev-dependencies installed:")
+ error_shout(u"\tpip install -r dev-requirements.txt")
+ raise click.Abort()
@generate.command(name=u'extension', short_help=u"Create empty extension.")
@@ -18,6 +26,7 @@ def generate():
u"template.",
default=u'.')
def extension(output_dir):
+ from cookiecutter.main import cookiecutter
cur_loc = os.path.dirname(os.path.abspath(__file__))
os.chdir(cur_loc)
os.chdir(u'../../contrib/cookiecutter/ckan_extension/')
| Missing dependency in requirements.txt (cookiecutter)
https://github.com/ckan/ckan/blob/f2cea089bc0aaeede06d98449c4e9eb65e8c2f14/ckan/cli/generate.py#L7
- cookiecutter lib will be imported on a `ckan` cli attempt, but as it is missing from requirments.txt, is not present which will result to ImportError
- cookiecutter is listed in requirments-dev.txt, but docker builds don't use it
Tested on a docker personal build, by :
> docker build -t ckan .
> docker run --rm -it --entrypoint bash --name ckan -p 5000:5000 --link db:db --link redis:redis --link solr:solr ckan
> (activated-env)
> ckan
| 2019-11-21T12:21:02 |
||
ckan/ckan | 5,135 | ckan__ckan-5135 | [
"4798"
] | 9818a1723d93ec908ecc03624450a57972b6fbcc | diff --git a/ckan/cli/__init__.py b/ckan/cli/__init__.py
--- a/ckan/cli/__init__.py
+++ b/ckan/cli/__init__.py
@@ -4,19 +4,67 @@
import click
import logging
-from logging.config import fileConfig as loggingFileConfig
+from configparser import ConfigParser
log = logging.getLogger(__name__)
+class CKANConfigLoader(object):
+ def __init__(self, filename):
+ self.filename = filename = filename.strip()
+ self.parser = ConfigParser()
+ self.section = u'app:main'
+ self.read_config_files(filename)
+
+ defaults = {
+ u'here': os.path.dirname(os.path.abspath(filename)),
+ u'__file__': os.path.abspath(filename)
+ }
+ self._update_defaults(defaults)
+
+ def read_config_files(self, filename):
+ '''
+ Read and parses a config file. If the config file has
+ 'use=config:<filename>' then it parses both files. Automatically
+ applies interpolation if needed.
+ '''
+ self.parser.read(filename)
+
+ schema, path = self.parser.get(self.section, u'use').split(u':')
+ if schema == u'config':
+ path = os.path.join(
+ os.path.dirname(os.path.abspath(filename)), path)
+ self.parser.read([path, filename])
+
+ def _update_defaults(self, new_defaults):
+ for key, value in new_defaults.items():
+ self.parser._defaults[key] = value
+
+ def get_config(self):
+ global_conf = self.parser.defaults().copy()
+ local_conf = {}
+ options = self.parser.options(self.section)
+
+ for option in options:
+ if option in global_conf:
+ continue
+ local_conf[option] = self.parser.get(self.section, option)
+
+ return CKANLoaderContext(global_conf, local_conf)
+
+
+class CKANLoaderContext(object):
+ def __init__(self, global_conf, local_conf):
+ self.global_conf = global_conf
+ self.local_conf = local_conf
+
+
def error_shout(exception):
click.secho(str(exception), fg=u'red', err=True)
def load_config(ini_path=None):
- from paste.deploy import appconfig
-
if ini_path:
if ini_path.startswith(u'~'):
ini_path = os.path.expanduser(ini_path)
@@ -42,6 +90,7 @@ def load_config(ini_path=None):
msg += u'\n(Given by: %s)' % config_source
exit(msg)
- loggingFileConfig(filename)
+ config_loader = CKANConfigLoader(filename)
log.info(u'Using configuration file {}'.format(filename))
- return appconfig(u'config:' + filename)
+
+ return config_loader.get_config()
diff --git a/ckan/lib/cli.py b/ckan/lib/cli.py
--- a/ckan/lib/cli.py
+++ b/ckan/lib/cli.py
@@ -29,6 +29,7 @@
from paste.registry import Registry
from paste.script.util.logging_config import fileConfig
import click
+from ckan.cli import load_config as _get_config
from ckan.config.middleware import make_app
import ckan.logic as logic
@@ -183,36 +184,6 @@ def ungettext(self, singular, plural, n):
return singular
-def _get_config(config=None):
- from paste.deploy import appconfig
-
- if config:
- filename = os.path.abspath(config)
- config_source = '-c parameter'
- elif os.environ.get('CKAN_INI'):
- filename = os.environ.get('CKAN_INI')
- config_source = '$CKAN_INI'
- else:
- default_filename = 'development.ini'
- filename = os.path.join(os.getcwd(), default_filename)
- if not os.path.exists(filename):
- # give really clear error message for this common situation
- msg = 'ERROR: You need to specify the CKAN config (.ini) '\
- 'file path.'\
- '\nUse the --config parameter or set environment ' \
- 'variable CKAN_INI or have {}\nin the current directory.' \
- .format(default_filename)
- exit(msg)
-
- if not os.path.exists(filename):
- msg = 'Config file not found: %s' % filename
- msg += '\n(Given by: %s)' % config_source
- exit(msg)
-
- fileConfig(filename)
- return appconfig('config:' + filename)
-
-
def load_config(config, load_site_user=True):
conf = _get_config(config)
assert 'ckan' not in dir() # otherwise loggers would be disabled
@@ -249,7 +220,7 @@ def load_config(config, load_site_user=True):
pylons.c.userobj = model.User.get(site_user['name'])
## give routes enough information to run url_for
- parsed = urlparse(conf.get('ckan.site_url', 'http://0.0.0.0'))
+ parsed = urlparse(conf.local_conf.get('ckan.site_url', 'http://0.0.0.0'))
request_config = routes.request_config()
request_config.host = parsed.netloc + parsed.path
request_config.protocol = parsed.scheme
| diff --git a/ckan/tests/cli/data/test-core.ini.tpl b/ckan/tests/cli/data/test-core.ini.tpl
new file mode 100644
--- /dev/null
+++ b/ckan/tests/cli/data/test-core.ini.tpl
@@ -0,0 +1,17 @@
+[server:main]
+use = egg:Paste#http
+host = 0.0.0.0
+port = 5000
+
+[app:main]
+use = egg:ckan
+full_stack = true
+cache_dir = /tmp/%(ckan.site_id)s/
+debug = false
+testing = true
+
+# Specify the Postgres database for SQLAlchemy to use
+sqlalchemy.url = postgresql://ckan_default:pass@localhost/ckan_test
+
+ckan.site_id = default
+
diff --git a/ckan/tests/cli/data/test.ini.tpl b/ckan/tests/cli/data/test.ini.tpl
new file mode 100644
--- /dev/null
+++ b/ckan/tests/cli/data/test.ini.tpl
@@ -0,0 +1,13 @@
+[DEFAULT]
+debug = true
+smtp_server = localhost
+error_email_from = [email protected]
+
+[server:main]
+use = egg:Paste#http
+host = 0.0.0.0
+port = 5000
+
+[app:main]
+use = config:test-core.ini.tpl
+faster_db_test_hacks = True
\ No newline at end of file
diff --git a/ckan/tests/cli/test_cli.py b/ckan/tests/cli/test_cli.py
--- a/ckan/tests/cli/test_cli.py
+++ b/ckan/tests/cli/test_cli.py
@@ -1,8 +1,10 @@
# -*- coding: utf-8 -*-
import pytest
+import os
from ckan.cli.cli import ckan
+from ckan.cli import CKANConfigLoader
def test_without_args(cli):
@@ -70,3 +72,20 @@ def test_command_from_extension_is_available_when_all_requirements_satisfied(cli
"""
result = cli.invoke(ckan, [u'example-iclick-hello'])
assert not result.exit_code
+
+
+def test_ckan_config_loader_parse_files():
+ """
+ CKANConfigLoader should parse both 'test.ini.tpl' and 'test-core.ini.tpl'
+ files since test.ini.ptl has a use = config:test-core.ini.tpl config.
+ """
+ filename = os.path.join(os.path.dirname(__file__), u'data/test.ini.tpl')
+ conf = CKANConfigLoader(filename).get_config()
+
+ assert conf.global_conf[u'debug'] == u'true'
+ assert conf.global_conf[u'smtp_server'] == u'localhost'
+ assert conf.local_conf[u'ckan.site_id'] == u'default'
+ assert conf.local_conf[u'faster_db_test_hacks'] == u'True'
+ assert conf.local_conf[u'cache_dir'] == u'/tmp/default/'
+ assert (conf.local_conf[u'sqlalchemy.url'] ==
+ u'postgresql://ckan_default:pass@localhost/ckan_test')
diff --git a/test.ini b/test.ini
--- a/test.ini
+++ b/test.ini
@@ -21,7 +21,7 @@ use = config:test-core.ini
# Here we hard-code the database and a flag to make default tests
# run fast.
faster_db_test_hacks = True
-sqlalchemy.url = sqlite:///
+
# NB: other test configuration should go in test-core.ini, which is
# what the postgres tests use.
@@ -41,13 +41,13 @@ handlers = console
[logger_ckan]
qualname = ckan
-handlers =
+handlers =
level = INFO
[logger_sqlalchemy]
handlers =
qualname = sqlalchemy.engine
-level = WARN
+level = WARN
[handler_console]
class = StreamHandler
| Don't use paste.deploy appconfig to parse the ini file
Right now we are using paste.deploy's `appconfig` to parse the INI file and get the `config` object that CKAN uses. It offers some functionality that we don't use (like the ability to parse an INI file hosted elsewhere via HTTP), but basically it's a wrapper around `ConfigParser`. The one feature that we need to keep for backwards compatibility is interpolation (eg things like `cache_dir = /tmp/%(ckan.site_id)s/`), which is also supported in the [standard library](https://docs.python.org/3/library/configparser.html#interpolation-of-values).
#### Approach
Write our own simpler version of the configuration file parser and replace the `appconfig` calls in the CLI code.
#### Story points
5
| @amercader can you please add some notes of where to check existing code, who is the user of this code (to test that the "contract" is kept) etc? I have a good understanding of what needs to be done, as I've written some config parsers. Looking for where exactly to start.
We use the config parser whenever we start the application to parse the ini file and pass the config object to `load_environment()`, which will set everything up.
This can be done more explicitly or hidden as part of a higher level execution. The only place we are doing this directly right now is in the CLI, and the only ones that should be updated are:
* [Old paster CLI](https://github.com/ckan/ckan/blob/master/ckan/lib/cli.py#L205)
* [New click CLI](https://github.com/ckan/ckan/blob/master/ckan/cli/__init__.py#L25). This one covers the new development server (`ckan run`)
In here you need to replace usage of `appconfig` with our own parser. Check the paste source to see what is special about `appconfig` but as I said in the description I think we only need to keep the interpolation support.
Other places where the config is parsed include the tests. Currently the parsing is done via a Pylons plugin (`nose --with-pylons`) but the new pytest based tests use [our own](https://github.com/ckan/ckan/pull/4996/files#diff-023eefdbe76a226e831eebffefa86b9eR15) parser.
Another place where this will be used will be the wsgi entrypoint for production servers, like the current [Apache one](https://github.com/ckan/ckan-packaging/blob/master/common/etc/ckan/default/apache.wsgi) (which will be replaced by uswgi or gunicorn).
But for now as I said the goal is to parse the ini file and get a config object, and refactor the cli methods to use our own parser.
Let me know if this makes sense.
One important functionality that we need to keep is support for the interpolated variables eg (`%(ckan.site_id)s`). So this ini file:
```
# This is /etc/ckan/production.ini
cache_dir = /tmp/%(ckan.site_id)s/
ckan.site_id = default
who.config_file = %(here)s/who.ini
who.log_file = %(cache_dir)s/who_log.ini
```
Should become this config object
```python
config = {
'cache_dir': '/tmp/default',
'ckan.site_id': 'default
'who.config_file': '/etc/ckan/who.ini
'who.log_file': '/tmp/default/who_log.ini
}
```
[This module](https://github.com/Pylons/pastedeploy/blob/9cbc584a86bd1ae425bd0c0c3c00617d7e59475d/paste/deploy/loadwsgi.py) contains the source code of paster's paster in case you want to check the implementation (but that one is way more complex than what we need) | 2019-12-26T13:50:32 |
ckan/ckan | 5,139 | ckan__ckan-5139 | [
"5030"
] | a3cbca96505aae0398534e02da7ed9ac60b03a72 | diff --git a/ckan/model/tracking.py b/ckan/model/tracking.py
--- a/ckan/model/tracking.py
+++ b/ckan/model/tracking.py
@@ -31,8 +31,8 @@ class TrackingSummary(domain_object.DomainObject):
def get_for_package(cls, package_id):
obj = meta.Session.query(cls).autoflush(False)
obj = obj.filter_by(package_id=package_id)
- data = obj.order_by(text('tracking_date desc')).first()
- if data:
+ if meta.Session.query(obj.exists()).scalar():
+ data = obj.order_by(text('tracking_date desc')).first()
return {'total' : data.running_total,
'recent': data.recent_views}
| Intermittent very high render times
### CKAN Version if known (or site URL)
2.7.3, 2.8.3
### Please describe the expected behaviour
Pages should normally load in under 10 seconds.
### Please describe the actual behaviour
Page loads are normally fast (around 1 second) but sometimes take over 30 seconds, causing proxies to time out. This is particularly problematic when it occurs during dataset creation, because it leaves the dataset in 'draft' state and cannot be resolved by resubmitting the request; the dataset must be located via the My Datasets page and edited to fix its state.
### What steps can be taken to reproduce the issue?
No consistent cause has been found.
| There's definitely more information needed here. There have been recent improvements in render times but the issues that they fixed would have consistent slow times, not spikes.
Spikes like these generally suggest a problem in the underlying infrastructure (db connections, memory issues etc).
If you can pinpoint some steps and conditions to consistently reproduce it feel free to reopen.
Just saw this happen in a development environment, so not under any special load, taking *85.044 seconds* to render `/dataset/new`. Tried it again and took 10.849 seconds.
Update: This has started happening consistently on new datasets in our production environment. Adding debugging statements indicates that the time is being spent in attempting to load tracking summary data (`ckan/model/tracking.py`, TrackingSummary.get_for_package), although in the end no tracking data exists since they're new datasets.
This appears to be related to the combination of ORDER BY and LIMIT 1 with a query that returns no results; see https://stackoverflow.com/questions/21385555/postgresql-query-very-slow-with-limit-1 and https://stackoverflow.com/questions/6037843/extremely-slow-postgresql-query-with-order-and-limit-clauses for discussion.
There is a simple workaround of adding a second unnecessary ordering clause, which causes PostgreSQL to make better query plan choices. | 2020-01-03T02:33:17 |
|
ckan/ckan | 5,153 | ckan__ckan-5153 | [
"5152"
] | 7c4a97604eba5f941b26613e1ed49274130fb7e8 | diff --git a/ckan/views/resource.py b/ckan/views/resource.py
--- a/ckan/views/resource.py
+++ b/ckan/views/resource.py
@@ -243,6 +243,10 @@ def post(self, package_type, id):
except ValidationError as e:
errors = e.error_dict
error_summary = e.error_summary
+ if data.get(u'url_type') == u'upload' and data.get(u'url'):
+ data[u'url'] = u''
+ data[u'url_type'] = u''
+ data[u'previous_upload'] = True
return self.get(package_type, id, data, errors, error_summary)
except NotAuthorized:
return base.abort(403, _(u'Unauthorized to create a resource'))
| diff --git a/ckan/tests/controllers/test_user.py b/ckan/tests/controllers/test_user.py
--- a/ckan/tests/controllers/test_user.py
+++ b/ckan/tests/controllers/test_user.py
@@ -850,7 +850,7 @@ def test_request_reset_when_duplicate_emails(self, send_reset_link, app):
emailed_users = [
call[0][0].name for call in send_reset_link.call_args_list
]
- assert emailed_users == [user_a["name"], user_b["name"]]
+ assert sorted(emailed_users) == sorted([user_a["name"], user_b["name"]])
def test_request_reset_without_param(self, app):
| Validation errors during resource creation lead to wrong URLs
This was hard to track as it doesn't happen in a standard CKAN install, as the default resource form doesn't have required fields.
If an extension implements custom validation in the resource schema, and there are errors returned in the form the File upload field will be set to the previously uploaded file name (ie a string).
When submitting, CKAN will interpret that like an external URL, and create a bogus `http://<file_name>` URL. There will be no errors returned so it's easier for users to assume that the file they first selected was successfully uploaded.
To reproduce:
1. Modify the resource schema, eg adding the `not_empty` validator to `description`
2. Go to the create resource page, select a file to upload, eg `libraries.csv`, leave the description empty and submit
3. You get redirected to the form page, with the description error, and also with "libraries.csv" set on the File field:

4. Submit the form. The resource is created, and has `http://libraries.csv` as URL.
The safest fix I can think of is resetting the upload field if there are validation errors. This will mean that users need to select the file again, but this is preferable to create a bad URL (we can not reset the field to the actual file previously selected because of browser security limitations). We can make this obvious to users with a message.
| 2020-01-10T14:48:36 |
|
ckan/ckan | 5,167 | ckan__ckan-5167 | [
"2713"
] | 6257297747ca95222a6e57ced0722356015f0c06 | diff --git a/ckan/controllers/group.py b/ckan/controllers/group.py
--- a/ckan/controllers/group.py
+++ b/ckan/controllers/group.py
@@ -326,7 +326,7 @@ def pager_url(q=None, page=None):
facets[facet] = facet
# Facet titles
- self._update_facet_titles(facets, group_type)
+ facets = self._update_facet_titles(facets, group_type)
c.facet_titles = facets
@@ -377,6 +377,7 @@ def _update_facet_titles(self, facets, group_type):
for plugin in plugins.PluginImplementations(plugins.IFacets):
facets = plugin.group_facets(
facets, group_type, None)
+ return facets
def bulk_process(self, id):
''' Allow bulk processing of datasets for an organization. Make
diff --git a/ckan/controllers/organization.py b/ckan/controllers/organization.py
--- a/ckan/controllers/organization.py
+++ b/ckan/controllers/organization.py
@@ -28,3 +28,4 @@ def _update_facet_titles(self, facets, group_type):
for plugin in plugins.PluginImplementations(plugins.IFacets):
facets = plugin.organization_facets(
facets, group_type, None)
+ return facets
diff --git a/ckan/views/group.py b/ckan/views/group.py
--- a/ckan/views/group.py
+++ b/ckan/views/group.py
@@ -353,7 +353,7 @@ def pager_url(q=None, page=None):
facets[facet] = facet
# Facet titles
- _update_facet_titles(facets, group_type)
+ facets = _update_facet_titles(facets, group_type)
extra_vars["facet_titles"] = facets
@@ -413,6 +413,7 @@ def pager_url(q=None, page=None):
def _update_facet_titles(facets, group_type):
for plugin in plugins.PluginImplementations(plugins.IFacets):
facets = plugin.group_facets(facets, group_type, None)
+ return facets
def _get_group_dict(id, group_type):
| Group facets cannot be customized in the same way as dataset facets
When implementing IFacets interface, we want to override the default facet titles. For example, we may only want a part of the default facets for our dataset/group/organization page.
There are two ways to achieve this. Take `dataset_facets(self, facets_dict, package_type)` for example.
Method 1 is to change the facets_dict variable passed into the function, i.e
```
def dataset_facets(self, facets_dict, package_type):
facets_dict.pop('organization')
facets_dict.pop('license_id')
return facets_dict
```
Method 2 is to return a new facet dictionary that contains all the facets titles that I want:
```
def dataset_facets(self, facets_dict, package_type):
my_facet_titles = {
'groups': tk._('Categories'),
'tags': tk._('Tags'),
'res_format': tk._('Formats'),
}
return my_facet_titles
```
Both methods work for dataset_facets, but the 2nd method will fail on group_facets.
The issue is [here](https://github.com/ckan/ckan/blob/91e41b2e68faa3df5296a632f4862f5a55e69e62/ckan/controllers/group.py#L381). You can only make changes directly on the variable facets. Creating and returning any new dictionary in the `group_facets` method will not work.
Why is it necessary to define this [function](https://github.com/ckan/ckan/blob/91e41b2e68faa3df5296a632f4862f5a55e69e62/ckan/controllers/group.py#L379)? Why not make it consistent with the dataset counterpart?
Well, my current quick fix for my project is to always use method 1, or move the code outside `_update_facet_titles()`
| :+1: I'd say the IFacets implementation for groups and organizations is currently broken (well kind-of).
@perceptron-XYZ please submit a fix for this to align the IGroupForm behaviour to IDatasetForm's
@wardi , is this issue actual?
@gleb-rudenko the issue described is still present, in case you want to submit a patch
We decided to close old issues that are not actively worked on so that we can focus our effort and attention on issues affecting the current versions of CKAN.
If this issue is still affecting the version of CKAN you're working with now, please feel free to comment or reopen the issue.
If you do reopen this issue, please update it with new details. One reason it might not have been resolved in the past is that it wasn't clear how a contributor could address the issue. | 2020-01-21T22:05:23 |
|
ckan/ckan | 5,172 | ckan__ckan-5172 | [
"5131"
] | 6257297747ca95222a6e57ced0722356015f0c06 | diff --git a/ckan/lib/jinja_extensions.py b/ckan/lib/jinja_extensions.py
--- a/ckan/lib/jinja_extensions.py
+++ b/ckan/lib/jinja_extensions.py
@@ -106,13 +106,13 @@ def parse(self, parser):
node = nodes.Extends(lineno)
template_path = parser.filename
# find where in the search path this template is from
- index = 0
+ current_path = None
if not hasattr(self, 'searchpath'):
return node
for searchpath in self.searchpath:
if template_path.startswith(searchpath):
+ current_path = searchpath
break
- index += 1
# get filename from full path
filename = template_path[len(searchpath) + 1:]
@@ -128,8 +128,8 @@ def parse(self, parser):
% template_path)
# provide our magic format
- # format is *<search path parent index>*<template name>
- magic_filename = '*' + str(index) + '*' + filename
+ # format is *<search path parent directory>*<template name>
+ magic_filename = '*' + current_path + '*' + filename
# set template
node.template = nodes.Const(magic_filename)
return node
@@ -183,13 +183,14 @@ class CkanFileSystemLoader(loaders.FileSystemLoader):
def get_source(self, environment, template):
# if the template name starts with * then this should be
# treated specially.
- # format is *<search path parent index>*<template name>
+ # format is *<search path parent directory>*<template name>
# so we only search from then downwards. This allows recursive
# ckan_extends tags
if template.startswith('*'):
parts = template.split('*')
template = parts[2]
- searchpaths = self.searchpath[int(parts[1]) + 1:]
+ index = self.searchpath.index(parts[1])
+ searchpaths = self.searchpath[index + 1:]
else:
searchpaths = self.searchpath
# end of ckan changes
| ckan_extends cache depends on template paths
### CKAN Version if known (or site URL)
all versions
### Please describe the expected behaviour
`{% ckan_extends %}` should extend templates from the next path in the template paths list
### Please describe the actual behaviour
`{% ckan_extends %}` emits a node with a numeric index into the template path list, which is cached with the rest of the compiled template. If the plugins enabled or template paths change after caching the template `{% ckan_extends %}` will extend from the wrong position in the template paths list. This behavior could lead to an infinite loop, a skipped intermediate template or a `TemplateNotFound` error (even for templates present in ckan itself)
### What steps can be taken to reproduce the issue?
- create a template using `{% ckan_extends %}`, enable the `jinja2_cache_dir` setting
- visit a page that causes the template to be cached
- modify the plugins list to add/remove plugins with template directories or add/remove modify the `template_extra_paths` setting
- visit the page again for unexpected behavior
This is where the numeric index is added to the extends node, which is cached:
https://github.com/ckan/ckan/blob/621b008c9b2e7e07aef7410f85a61fec94154df0/ckan/lib/jinja_extensions.py#L132
This is where the cached numeric index is used on the current template path list: https://github.com/ckan/ckan/blob/621b008c9b2e7e07aef7410f85a61fec94154df0/ckan/lib/jinja_extensions.py#L189-L192
I suggest we switch this to emit the current template directory instead of a number so that we won't get this unexpected behavior.
| 2020-01-23T15:24:43 |
||
ckan/ckan | 5,173 | ckan__ckan-5173 | [
"5137"
] | 6257297747ca95222a6e57ced0722356015f0c06 | diff --git a/ckanext/datapusher/plugin.py b/ckanext/datapusher/plugin.py
--- a/ckanext/datapusher/plugin.py
+++ b/ckanext/datapusher/plugin.py
@@ -37,7 +37,7 @@ class DatapusherPlugin(p.SingletonPlugin):
p.implements(p.IActions)
p.implements(p.IAuthFunctions)
p.implements(p.IResourceUrlChange)
- p.implements(p.IDomainObjectModification, inherit=True)
+ p.implements(p.IResourceController, inherit=True)
p.implements(p.ITemplateHelpers)
p.implements(p.IBlueprint)
@@ -65,60 +65,80 @@ def configure(self, config):
format(config_option)
)
- def notify(self, entity, operation=None):
- if isinstance(entity, model.Resource):
- if (
- operation == model.domain_object.DomainObjectOperation.new
- or not operation
- ):
- # if operation is None, resource URL has been changed, as
- # the notify function in IResourceUrlChange only takes
- # 1 parameter
- context = {
- u'model': model,
- u'ignore_auth': True,
- u'defer_commit': True
+ # IResourceUrlChange
+
+ def notify(self, resource):
+ context = {
+ u'model': model,
+ u'ignore_auth': True,
+ }
+ resource_dict = toolkit.get_action(u'resource_show')(
+ context, {
+ u'id': resource.id,
+ }
+ )
+ self._submit_to_datapusher(resource_dict)
+
+ # IResourceController
+
+ def after_create(self, context, resource_dict):
+
+ self._submit_to_datapusher(resource_dict)
+
+ def _submit_to_datapusher(self, resource_dict):
+
+ context = {
+ u'model': model,
+ u'ignore_auth': True,
+ u'defer_commit': True
+ }
+
+ resource_format = resource_dict.get('format')
+
+ submit = (
+ resource_format
+ and resource_format.lower() in self.datapusher_formats
+ and resource_dict.get('url_type') != u'datapusher'
+ )
+
+ if not submit:
+ return
+
+ try:
+ task = toolkit.get_action(u'task_status_show')(
+ context, {
+ u'entity_id': resource_dict['id'],
+ u'task_type': u'datapusher',
+ u'key': u'datapusher'
+ }
+ )
+
+ if task.get(u'state') in (u'pending', u'submitting'):
+ # There already is a pending DataPusher submission,
+ # skip this one ...
+ log.debug(
+ u'Skipping DataPusher submission for '
+ u'resource {0}'.format(resource_dict['id'])
+ )
+ return
+ except toolkit.ObjectNotFound:
+ pass
+
+ try:
+ log.debug(
+ u'Submitting resource {0}'.format(resource_dict['id']) +
+ u' to DataPusher'
+ )
+ toolkit.get_action(u'datapusher_submit')(
+ context, {
+ u'resource_id': resource_dict['id']
}
- if (
- entity.format
- and entity.format.lower() in self.datapusher_formats
- and entity.url_type != u'datapusher'
- ):
-
- try:
- task = toolkit.get_action(u'task_status_show')(
- context, {
- u'entity_id': entity.id,
- u'task_type': u'datapusher',
- u'key': u'datapusher'
- }
- )
- if task.get(u'state') == u'pending':
- # There already is a pending DataPusher submission,
- # skip this one ...
- log.debug(
- u'Skipping DataPusher submission for '
- u'resource {0}'.format(entity.id)
- )
- return
- except toolkit.ObjectNotFound:
- pass
-
- try:
- log.debug(
- u'Submitting resource {0}'.format(entity.id) +
- u' to DataPusher'
- )
- toolkit.get_action(u'datapusher_submit')(
- context, {
- u'resource_id': entity.id
- }
- )
- except toolkit.ValidationError as e:
- # If datapusher is offline want to catch error instead
- # of raising otherwise resource save will fail with 500
- log.critical(e)
- pass
+ )
+ except toolkit.ValidationError as e:
+ # If datapusher is offline want to catch error instead
+ # of raising otherwise resource save will fail with 500
+ log.critical(e)
+ pass
def get_actions(self):
return {
| diff --git a/ckanext/datapusher/tests/test.py b/ckanext/datapusher/tests/test.py
--- a/ckanext/datapusher/tests/test.py
+++ b/ckanext/datapusher/tests/test.py
@@ -11,6 +11,7 @@
import ckan.model as model
import ckan.plugins as p
import ckan.tests.legacy as tests
+from ckan.tests import factories
import ckanext.datastore.backend.postgres as db
from ckan.common import config
from ckanext.datastore.tests.helpers import set_url_type
@@ -286,3 +287,70 @@ def test_custom_callback_url_base(self, app):
data["result_url"]
== "https://ckan.example.com/api/3/action/datapusher_hook"
)
+
+ @responses.activate
+ @pytest.mark.ckan_config(
+ "ckan.datapusher.callback_url_base", "https://ckan.example.com"
+ )
+ @pytest.mark.ckan_config(
+ "ckan.datapusher.url", "http://datapusher.ckan.org"
+ )
+ @pytest.mark.ckan_config("ckan.plugins", "datastore datapusher")
+ @pytest.mark.usefixtures("with_plugins")
+ def test_create_resource_hooks(self, app):
+
+ responses.add(
+ responses.POST,
+ "http://datapusher.ckan.org/job",
+ content_type="application/json",
+ body=json.dumps({"job_id": "foo", "job_key": "barloco"}),
+ )
+ responses.add_passthru(config["solr_url"])
+
+ dataset = factories.Dataset()
+ resource = tests.call_action_api(
+ app,
+ "resource_create",
+ apikey=self.sysadmin_user.apikey,
+ package_id=dataset['id'],
+ format='CSV',
+ )
+
+ @responses.activate
+ @pytest.mark.ckan_config(
+ "ckan.datapusher.callback_url_base", "https://ckan.example.com"
+ )
+ @pytest.mark.ckan_config(
+ "ckan.datapusher.url", "http://datapusher.ckan.org"
+ )
+ @pytest.mark.ckan_config("ckan.plugins", "datastore datapusher")
+ @pytest.mark.usefixtures("with_plugins")
+ def test_update_resource_url_hooks(self, app):
+
+ responses.add(
+ responses.POST,
+ "http://datapusher.ckan.org/job",
+ content_type="application/json",
+ body=json.dumps({"job_id": "foo", "job_key": "barloco"}),
+ )
+ responses.add_passthru(config["solr_url"])
+
+ dataset = factories.Dataset()
+ resource = tests.call_action_api(
+ app,
+ "resource_create",
+ apikey=self.sysadmin_user.apikey,
+ package_id=dataset['id'],
+ url='http://example.com/old.csv',
+ format='CSV',
+ )
+
+ resource = tests.call_action_api(
+ app,
+ "resource_update",
+ apikey=self.sysadmin_user.apikey,
+ id=resource['id'],
+ url='http://example.com/new.csv',
+ format='CSV',
+ )
+ assert resource
| Add dataset button displays an Internal Server Error
### CKAN Version if known (or site URL)
git master branch
### Please describe the expected behaviour
I have configured docker-compose ckan based on the url below.
https://docs.ckan.org/en/2.8/maintaining/installing/install-from-docker-compose.html
There was no problem with datastore when adding ckan plugin.
```bash
ckan.plugins = stats text_view image_view recline_view datastore
```
However, when I added datapusher and pressed the add datasets button, I could see the following screen.
'Internal Server Error'
```bash
ckan.plugins = stats text_view image_view recline_view datastore datapusher
# Define which views should be created by default
# (plugins must be loaded in ckan.plugins)
ckan.views.default_views = image_view text_view recline_view
ckan.datapusher.formats = csv xls xlsx tsv application/csv application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
```
### Please describe the actual behaviour
I checked the docker-compose logs ckan command and it showed the following output:
```
2019-12-31 01:52:57,225 ERROR [ckan.config.middleware.flask_app] 'NoneType' object has no attribute 'transaction'
ckan | Traceback (most recent call last):
ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
ckan | rv = self.dispatch_request()
ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1935, in dispatch_request
ckan | return self.view_functions[rule.endpoint](**req.view_args)
ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/views.py", line 89, in view
ckan | return self.dispatch_request(*args, **kwargs)
ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/views.py", line 163, in dispatch_request
ckan | return meth(*args, **kwargs)
ckan | File "/usr/lib/ckan/venv/src/ckan/ckan/views/resource.py", line 242, in post
ckan | get_action(u'resource_create')(context, data)
ckan | File "/usr/lib/ckan/venv/src/ckan/ckan/logic/__init__.py", line 469, in wrapped
ckan | result = _action(context, data_dict, **kw)
ckan | File "/usr/lib/ckan/venv/src/ckan/ckan/logic/action/create.py", line 327, in resource_create
ckan | model.repo.commit()
ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/scoping.py", line 162, in do
ckan | return getattr(self.registry(), name)(*args, **kwargs)
ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1027, in commit
ckan | self.transaction.commit()
ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 494, in commit
ckan | self._prepare_impl()
ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 464, in _prepare_impl
ckan | stx = self.session.transaction
ckan | AttributeError: 'NoneType' object has no attribute 'transaction'
ckan | 2019-12-31 01:52:57,341 INFO [ckan.config.middleware.flask_app] /dataset/testdataset07/resource/new render time 3.881 seconds
ckan | 2019-12-31 01:52:57,624 INFO [ckan.config.middleware.flask_app] /api/i18n/en render time 0.001 seconds
ckan | db:5432 - accepting connections
ckan | /usr/lib/ckan/venv/local/lib/python2.7/site-packages/webassets/loaders.py:162: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.
ckan | obj = self.yaml.load(f) or {}
ckan | Initialising DB: SUCCESS
ckan | 2019-12-31 01:53:31,960 INFO [ckan.config.environment] Loading static files from public
ckan | /usr/lib/ckan/venv/local/lib/python2.7/site-packages/webassets/loaders.py:162: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.
ckan | obj = self.yaml.load(f) or {}
ckan | 2019-12-31 01:53:32,004 INFO [ckan.config.environment] Loading templates from /usr/lib/ckan/venv/src/ckan/ckan/templates
```
this is datapusher log
```
datapusher | Deleting "8da3ff38-7c78-45ad-bff0-cd84ee76546e" from datastore.
datapusher | Determined headers and types: [{'type': u'text', 'id': u'Region'}, {'type': u'text', 'id': u'Country'}, {'type': u'text', 'id': u'Item Type'}, {'type': u'text', 'id': u'Sales Channel'}, {'type': u'text', 'id': u'Order Priority'}, {'type': u'timestamp', 'id': u'Order Date'}, {'type': u'numeric', 'id': u'Order ID'}, {'type': u'timestamp', 'id': u'Ship Date'}, {'type': u'numeric', 'id': u'Units Sold'}, {'type': u'numeric', 'id': u'Unit Price'}, {'type': u'numeric', 'id': u'Unit Cost'}, {'type': u'numeric', 'id': u'Total Revenue'}, {'type': u'numeric', 'id': u'Total Cost'}, {'type': u'numeric', 'id': u'Total Profit'}]
datapusher | Saving chunk 0
datapusher | Successfully pushed 100 entries to "8da3ff38-7c78-45ad-bff0-cd84ee76546e".
```
### What steps can be taken to reproduce the issue?
| I solved it by changing it to a stable version.
```
git checkout tags/ckan-2.8.2
``` | 2020-01-24T13:44:26 |
ckan/ckan | 5,198 | ckan__ckan-5198 | [
"5109"
] | 0e601b43e5a1a29229ad29c82388d5d4e5ee720c | diff --git a/ckan/cli/__init__.py b/ckan/cli/__init__.py
--- a/ckan/cli/__init__.py
+++ b/ckan/cli/__init__.py
@@ -74,6 +74,7 @@ def load_config(ini_path=None):
filename = os.environ.get(u'CKAN_INI')
config_source = u'$CKAN_INI'
else:
+ # deprecated method since CKAN 2.9
default_filename = u'development.ini'
filename = os.path.join(os.getcwd(), default_filename)
if not os.path.exists(filename):
diff --git a/doc/conf.py b/doc/conf.py
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -38,6 +38,7 @@
.. |config_dir| replace:: |config_parent_dir|/default
.. |production.ini| replace:: |config_dir|/production.ini
.. |development.ini| replace:: |config_dir|/development.ini
+.. |ckan.ini| replace:: |config_dir|/ckan.ini
.. |git_url| replace:: \https://github.com/ckan/ckan.git
.. |raw_git_url| replace:: \https://raw.githubusercontent.com/ckan/ckan
.. |postgres| replace:: PostgreSQL
| diff --git a/doc/contributing/test.rst b/doc/contributing/test.rst
--- a/doc/contributing/test.rst
+++ b/doc/contributing/test.rst
@@ -27,7 +27,7 @@ Install additional dependencies
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some additional dependencies are needed to run the tests. Make sure you've
-created a config file at |development.ini|, then activate your
+created a config file at |ckan.ini|, then activate your
virtual environment:
.. parsed-literal::
@@ -56,7 +56,7 @@ Create test databases:
Set the permissions::
- paster datastore set-permissions -c test-core.ini | sudo -u postgres psql
+ ckan -c |ckan.ini| datastore set-permissions | sudo -u postgres psql
This database connection is specified in the ``test-core.ini`` file by the
``sqlalchemy.url`` parameter.
@@ -80,7 +80,7 @@ Each core will be within a child from the ``<lst name="status"`` element, and co
You can also tell from your ckan config (assuming ckan is working)::
- grep solr_url /etc/ckan/default/production.ini
+ grep solr_url |ckan.ini|
# single-core: solr_url = http://127.0.0.1:8983/solr
# multi-core: solr_url = http://127.0.0.1:8983/solr/ckan
@@ -109,7 +109,7 @@ To enable multi-core:
sudo service jetty restart
-6. Edit your main ckan config (e.g. |development.ini|) and adjust the solr_url to match::
+6. Edit your main ckan config (e.g. |ckan.ini|) and adjust the solr_url to match::
solr_url = http://127.0.0.1:8983/solr/ckan
@@ -172,7 +172,7 @@ PhantomJS_. First you need to install the necessary packages::
To run the tests, make sure that a test server is running::
. /usr/lib/ckan/default/bin/activate
- paster serve test-core.ini
+ ckan -c |ckan.ini| run
Once the test server is running switch to another terminal and execute the
tests::
| Update documentation with the new CLI commands
Now that the all commands are available in the new `ckan` command we need to update the docs to replace usage of the paster based ones.
- [ ] The main CLI doc page is [this one](https://github.com/ckan/ckan/blob/master/doc/maintaining/paster.rst)
- [ ] Besides, we need to replace all `paster xxx` commands listed in the docs with its `ckan xxx` counterparts
- [ ] Include info on how to add commands from extensions after #5108 is done
| 2020-02-10T23:40:16 |
|
ckan/ckan | 5,213 | ckan__ckan-5213 | [
"5207"
] | 67333338b0ff62696dbfba4e3ff073676a778e21 | diff --git a/ckan/lib/formatters.py b/ckan/lib/formatters.py
--- a/ckan/lib/formatters.py
+++ b/ckan/lib/formatters.py
@@ -120,10 +120,10 @@ def months_between(date1, date2):
return _('Just now')
else:
return ungettext('{mins} minute ago', '{mins} minutes ago',
- seconds / 60).format(mins=seconds / 60)
+ seconds // 60).format(mins=seconds // 60)
else:
return ungettext('{hours} hour ago', '{hours} hours ago',
- seconds / 3600).format(hours=seconds / 3600)
+ seconds // 3600).format(hours=seconds // 3600)
# more than one day
months = months_between(datetime_, now)
@@ -134,7 +134,7 @@ def months_between(date1, date2):
return ungettext('{months} month ago', '{months} months ago',
months).format(months=months)
return ungettext('over {years} year ago', 'over {years} years ago',
- months / 12).format(years=months / 12)
+ months // 12).format(years=months // 12)
# actual date
details = {
| diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py
--- a/ckan/tests/lib/test_helpers.py
+++ b/ckan/tests/lib/test_helpers.py
@@ -505,6 +505,60 @@ def test_render_datetime(date, extra, exp):
assert h.render_datetime(date, **extra) == exp
[email protected]_time("2020-02-17 12:00:00")
[email protected](
+ "date, exp",
+ [
+ (
+ datetime.datetime(2020, 2, 17, 11, 59, 30),
+ "Just now",
+ ),
+ (
+ datetime.datetime(2020, 2, 17, 11, 59, 0),
+ "1 minute ago",
+ ),
+ (
+ datetime.datetime(2020, 2, 17, 11, 55, 0),
+ "5 minutes ago",
+ ),
+ (
+ datetime.datetime(2020, 2, 17, 11, 0, 0),
+ "1 hour ago",
+ ),
+ (
+ datetime.datetime(2020, 2, 17, 7, 0, 0),
+ "5 hours ago",
+ ),
+ (
+ datetime.datetime(2020, 2, 16, 12, 0, 0),
+ "1 day ago",
+ ),
+ (
+ datetime.datetime(2020, 2, 12, 12, 0, 0),
+ "5 days ago",
+ ),
+ (
+ datetime.datetime(2020, 1, 17, 12, 0, 0),
+ "1 month ago",
+ ),
+ (
+ datetime.datetime(2019, 9, 17, 12, 0, 0),
+ "5 months ago",
+ ),
+ (
+ datetime.datetime(2019, 1, 17, 12, 0, 0),
+ "over 1 year ago",
+ ),
+ (
+ datetime.datetime(2015, 1, 17, 12, 0, 0),
+ "over 5 years ago",
+ ),
+ ]
+)
+def test_time_ago_from_timestamp(date, exp):
+ assert h.time_ago_from_timestamp(date) == exp
+
+
def test_clean_html_disallowed_tag():
assert h.clean_html("<b><bad-tag>Hello") == u"<b><bad-tag>Hello</b>"
| CKAN 2.9 Time at acitivity stream
### CKAN Version
2.9
### Expected behavior
Time is showed in the right format (like in CKAN 2.8)
### Actual behaviour
Time displayed like a float number

### Steps to reproduce
1. Set up pure CKAN
2. Create Org nad dataset to it.
3. Open Activity steam tab.
| 2020-02-15T13:02:33 |
|
ckan/ckan | 5,230 | ckan__ckan-5230 | [
"5229"
] | fb0174b77a5ac1c614717643d9b1b2a0c82ee088 | diff --git a/ckanext/example_idatastorebackend/example_sqlite.py b/ckanext/example_idatastorebackend/example_sqlite.py
--- a/ckanext/example_idatastorebackend/example_sqlite.py
+++ b/ckanext/example_idatastorebackend/example_sqlite.py
@@ -28,7 +28,7 @@ def _insert_records(self, table, records):
u', '.join(record.keys()),
u', '.join(['?'] * len(record.keys()))
),
- record.values()
+ list(record.values())
)
pass
| diff --git a/ckanext/example_idatastorebackend/test/test_plugin.py b/ckanext/example_idatastorebackend/test/test_plugin.py
--- a/ckanext/example_idatastorebackend/test/test_plugin.py
+++ b/ckanext/example_idatastorebackend/test/test_plugin.py
@@ -20,15 +20,10 @@
)
-class ExampleIDatastoreBackendPlugin(helpers.FunctionalTestBase):
- def setup(self):
- super(ExampleIDatastoreBackendPlugin, self).setup()
- plugins.load(u"datastore")
- plugins.load(u"example_idatastorebackend")
-
- def teardown(self):
- plugins.unload(u"example_idatastorebackend")
- plugins.unload(u"datastore")
[email protected]_config(u"ckan.plugins",
+ u"datastore example_idatastorebackend")
[email protected](u"with_plugins", u"clean_db", u"app")
+class TestExampleIDatastoreBackendPlugin():
def test_backends_correctly_registered(self):
DatastoreBackend.register_backends()
@@ -85,7 +80,7 @@ def test_backend_functionality(self, get_engine):
records=records,
)
# check, create and 3 inserts
- assert 5 == execute.call_count
+ assert 4 == execute.call_count
insert_query = u'INSERT INTO "{0}"(a) VALUES(?)'.format(res["id"])
execute.assert_has_calls(
[
@@ -104,7 +99,7 @@ def test_backend_functionality(self, get_engine):
fetchall.return_value = records
helpers.call_action(u"datastore_search", resource_id=res["id"])
execute.assert_called_with(
- u'SELECT * FROM "{0}" LIMIT 10'.format(res["id"])
+ u'SELECT * FROM "{0}" LIMIT 100'.format(res["id"])
)
execute.reset_mock()
| iDatastoreBackend tests doesn't get run
It looks like the tests for iDatastoreBackend don't get run: https://github.com/smotornyuk/ckan/blob/master/ckanext/example_idatastorebackend/test/test_plugin.py
because the classname doesn't start with `Test`.
There is [a clue](https://github.com/ckan/ckan/pull/3437/files#diff-075854f501da9e193409752e9156cddfR31) in the [original PR](https://github.com/ckan/ckan/pull/3437/files#diff-075854f501da9e193409752e9156cddfR28) from @smotornyuk that it was renamed from TestExampleIDatastoreBackendPlugin.
Perhaps this test can be re-enabled? (and modernized)
I was looking at this test because of querying a line in datastore/backend/postgres.py:_insert_links()
| 2020-02-21T22:38:42 |
|
ckan/ckan | 5,264 | ckan__ckan-5264 | [
"5110"
] | 55fd89f41a0ad244f7c0792687633acd2e57b092 | diff --git a/ckan/lib/cli.py b/ckan/lib/cli.py
--- a/ckan/lib/cli.py
+++ b/ckan/lib/cli.py
@@ -2,43 +2,24 @@
from __future__ import print_function
-import collections
-import csv
-import multiprocessing as mp
import os
-import datetime
import sys
-from pprint import pprint
-import re
-import itertools
-import json
-import logging
-from optparse import OptionConflictError
-import traceback
-from six import text_type
-from six.moves import input, xrange
-from six.moves.urllib.error import HTTPError
-from six.moves.urllib.parse import urljoin, urlparse
-from six.moves.urllib.request import urlopen
-
-import sqlalchemy as sa
-
-import routes
+import click
import paste.script
+import routes
from paste.registry import Registry
from paste.script.util.logging_config import fileConfig
-import click
-from ckan.cli import load_config as _get_config
+from six.moves import input
+from six.moves.urllib.parse import urlparse
from ckan.config.middleware import make_app
+from ckan.cli import load_config as _get_config
import ckan.logic as logic
import ckan.model as model
-import ckan.include.rjsmin as rjsmin
-import ckan.include.rcssmin as rcssmin
-import ckan.plugins as p
from ckan.common import config
from ckan.common import asbool
+import ckan.lib.maintain as maintain
# This is a test Flask request context to be used internally.
# Do not use it!
_cli_test_request_context = None
@@ -49,8 +30,11 @@
# Otherwise loggers get disabled.
[email protected]('Use @maintain.deprecated instead')
def deprecation_warning(message=None):
'''
+ DEPRECATED
+
Print a deprecation warning to STDERR.
If ``message`` is given it is also printed to STDERR.
@@ -61,8 +45,11 @@ def deprecation_warning(message=None):
sys.stderr.write(u'\n')
[email protected]()
def error(msg):
'''
+ DEPRECATED
+
Print an error message to STDOUT and exit with return code 1.
'''
sys.stderr.write(msg)
@@ -71,7 +58,9 @@ def error(msg):
sys.exit(1)
[email protected]('Use model.parse_db_config directly instead')
def _parse_db_config(config_key=u'sqlalchemy.url'):
+ '''Deprecated'''
db_config = model.parse_db_config(config_key)
if not db_config:
raise Exception(
@@ -79,67 +68,13 @@ def _parse_db_config(config_key=u'sqlalchemy.url'):
)
return db_config
-
-def user_add(args):
- '''Add new user if we use paster sysadmin add
- or paster user add
- '''
- if len(args) < 1:
- error('Error: you need to specify the user name.')
- username = args[0]
-
- # parse args into data_dict
- data_dict = {'name': username}
- for arg in args[1:]:
- try:
- field, value = arg.split('=', 1)
- if field == 'sysadmin':
- value = asbool(value)
- data_dict[field] = value
- except ValueError:
- raise ValueError(
- 'Could not parse arg: %r (expected "<option>=<value>)"' % arg
- )
-
- # Required
- while '@' not in data_dict.get('email', ''):
- print('Error: Invalid email address')
- data_dict['email'] = input('Email address: ').strip()
-
- if 'password' not in data_dict:
- data_dict['password'] = UserCmd.password_prompt()
-
- # Optional
- if 'fullname' in data_dict:
- data_dict['fullname'] = data_dict['fullname'].decode(
- sys.getfilesystemencoding()
- )
-
- print('Creating user: %r' % username)
-
- try:
- import ckan.logic as logic
- import ckan.model as model
- site_user = logic.get_action('get_site_user')({
- 'model': model,
- 'ignore_auth': True},
- {}
- )
- context = {
- 'model': model,
- 'session': model.Session,
- 'ignore_auth': True,
- 'user': site_user['name'],
- }
- user_dict = logic.get_action('user_create')(context, data_dict)
- pprint(user_dict)
- except logic.ValidationError as e:
- error(traceback.format_exc())
-
## from http://code.activestate.com/recipes/577058/ MIT licence.
## Written by Trent Mick
[email protected]('Instead you can probably use click.confirm()')
def query_yes_no(question, default="yes"):
- """Ask a yes/no question via input() and return their answer.
+ """DEPRECATED
+
+ Ask a yes/no question via input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
@@ -228,8 +163,12 @@ def load_config(config, load_site_user=True):
return site_user
[email protected]('Instead use ckan.cli.cli.CkanCommand or extensions '
+ 'should use IClick')
def paster_click_group(summary):
- '''Return a paster command click.Group for paster subcommands
+ '''DEPRECATED
+
+ Return a paster command click.Group for paster subcommands
:param command: the paster command linked to this function from
setup.py, used in help text (e.g. "datastore")
@@ -271,7 +210,11 @@ def cli(ctx, plugin, config):
class CkanCommand(paste.script.command.Command):
- '''Base class for classes that implement CKAN paster commands to inherit.'''
+ '''DEPRECATED - Instead use ckan.cli.cli.CkanCommand or extensions
+ should use IClick.
+
+ Base class for classes that implement CKAN paster commands to
+ inherit.'''
parser = paste.script.command.Command.standard_parser(verbose=True)
parser.add_option('-c', '--config', dest='config',
help='Config file to use.')
@@ -284,2209 +227,3 @@ class CkanCommand(paste.script.command.Command):
def _load_config(self, load_site_user=True):
self.site_user = load_config(self.options.config, load_site_user)
-
-
-class ManageDb(CkanCommand):
- '''Perform various tasks on the database.
-
- db create - alias of db upgrade
- db init - create and put in default data
- db clean - clears db (including dropping tables) and
- search index
- db upgrade [version no.] - Data migrate
- db version - returns current version of data schema
- db create-from-model - create database from the model (indexes not made)
- db migrate-filestore - migrate all uploaded data from the 2.1 filesore.
- '''
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = None
- min_args = 1
-
- def command(self):
- cmd = self.args[0]
-
- self._load_config(cmd != 'upgrade')
-
- import ckan.model as model
- import ckan.lib.search as search
-
- if cmd == 'init':
-
- model.repo.init_db()
- if self.verbose:
- print('Initialising DB: SUCCESS')
- elif cmd == 'clean' or cmd == 'drop':
-
- # remove any *.pyc version files to prevent conflicts
- v_path = os.path.join(os.path.dirname(__file__),
- '..', 'migration', 'versions', '*.pyc')
- import glob
- filelist = glob.glob(v_path)
- for f in filelist:
- os.remove(f)
-
- model.repo.clean_db()
- search.clear_all()
- if self.verbose:
- print('Cleaning DB: SUCCESS')
- elif cmd == 'upgrade':
- model.repo.upgrade_db(*self.args[1:])
- elif cmd == 'downgrade':
- model.repo.downgrade_db(*self.args[1:])
- elif cmd == 'version':
- self.version()
- elif cmd == 'create-from-model':
- model.repo.create_db()
- if self.verbose:
- print('Creating DB: SUCCESS')
- else:
- error('Command %s not recognized' % cmd)
-
- def version(self):
- from ckan.model import Session
- print(Session.execute('select version from '
- 'migrate_version;').fetchall())
-
-
-class SearchIndexCommand(CkanCommand):
- '''Creates a search index for all datasets
-
- Usage:
- search-index [-i] [-o] [-r] [-e] [-q] rebuild [dataset_name] - reindex dataset_name if given, if not then rebuild
- full search index (all datasets)
- search-index rebuild_fast - reindex using multiprocessing using all cores.
- This acts in the same way as rubuild -r [EXPERIMENTAL]
- search-index check - checks for datasets not indexed
- search-index show DATASET_NAME - shows index of a dataset
- search-index clear [dataset_name] - clears the search index for the provided dataset or
- for the whole ckan instance
- '''
-
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = 2
- min_args = 0
-
- def __init__(self, name):
- super(SearchIndexCommand, self).__init__(name)
-
- self.parser.add_option('-i', '--force', dest='force',
- action='store_true', default=False,
- help='Ignore exceptions when rebuilding the index')
-
- self.parser.add_option('-o', '--only-missing', dest='only_missing',
- action='store_true', default=False,
- help='Index non indexed datasets only')
-
- self.parser.add_option('-r', '--refresh', dest='refresh',
- action='store_true', default=False,
- help='Refresh current index (does not clear the existing one)')
-
- self.parser.add_option('-q', '--quiet', dest='quiet',
- action='store_true', default=False,
- help='Do not output index rebuild progress')
-
- self.parser.add_option('-e', '--commit-each', dest='commit_each',
- action='store_true', default=False, help=
-'''Perform a commit after indexing each dataset. This ensures that changes are
-immediately available on the search, but slows significantly the process.
-Default is false.''')
-
- def command(self):
- if not self.args:
- # default to printing help
- print(self.usage)
- return
-
- cmd = self.args[0]
- # Do not run load_config yet
- if cmd == 'rebuild_fast':
- self.rebuild_fast()
- return
-
- self._load_config()
- if cmd == 'rebuild':
- self.rebuild()
- elif cmd == 'check':
- self.check()
- elif cmd == 'show':
- self.show()
- elif cmd == 'clear':
- self.clear()
- else:
- print('Command %s not recognized' % cmd)
-
- def rebuild(self):
- from ckan.lib.search import rebuild, commit
-
- # BY default we don't commit after each request to Solr, as it is
- # a really heavy operation and slows things a lot
-
- if len(self.args) > 1:
- rebuild(self.args[1])
- else:
- rebuild(only_missing=self.options.only_missing,
- force=self.options.force,
- refresh=self.options.refresh,
- defer_commit=(not self.options.commit_each),
- quiet=self.options.quiet)
-
- if not self.options.commit_each:
- commit()
-
- def check(self):
- from ckan.lib.search import check
- check()
-
- def show(self):
- from ckan.lib.search import show
-
- if not len(self.args) == 2:
- print('Missing parameter: dataset-name')
- return
- index = show(self.args[1])
- pprint(index)
-
- def clear(self):
- from ckan.lib.search import clear, clear_all
- package_id = self.args[1] if len(self.args) > 1 else None
- if not package_id:
- clear_all()
- else:
- clear(package_id)
-
- def rebuild_fast(self):
- ### Get out config but without starting pylons environment ####
- conf = _get_config()
-
- ### Get ids using own engine, otherwise multiprocess will balk
- db_url = conf['sqlalchemy.url']
- engine = sa.create_engine(db_url)
- package_ids = []
- result = engine.execute("select id from package where state = 'active';")
- for row in result:
- package_ids.append(row[0])
-
- def start(ids):
- ## load actual enviroment for each subprocess, so each have thier own
- ## sa session
- self._load_config()
- from ckan.lib.search import rebuild, commit
- rebuild(package_ids=ids)
- commit()
-
- def chunks(l, n):
- """ Yield n successive chunks from l.
- """
- newn = int(len(l) / n)
- for i in xrange(0, n-1):
- yield l[i*newn:i*newn+newn]
- yield l[n*newn-newn:]
-
- processes = []
- for chunk in chunks(package_ids, mp.cpu_count()):
- process = mp.Process(target=start, args=(chunk,))
- processes.append(process)
- process.daemon = True
- process.start()
-
- for process in processes:
- process.join()
-
-
-class Notification(CkanCommand):
- '''Send out modification notifications.
-
- In "replay" mode, an update signal is sent for each dataset in the database.
-
- Usage:
- notify replay - send out modification signals
- '''
-
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = 1
- min_args = 0
-
- def command(self):
- self._load_config()
- from ckan.model import Session, Package, DomainObjectOperation
- from ckan.model.modification import DomainObjectModificationExtension
-
- if not self.args:
- # default to run
- cmd = 'replay'
- else:
- cmd = self.args[0]
-
- if cmd == 'replay':
- dome = DomainObjectModificationExtension()
- for package in Session.query(Package):
- dome.notify(package, DomainObjectOperation.changed)
- else:
- print('Command %s not recognized' % cmd)
-
-
-class RDFExport(CkanCommand):
- '''Export active datasets as RDF
- This command dumps out all currently active datasets as RDF into the
- specified folder.
-
- Usage:
- paster rdf-export /path/to/store/output
- '''
- summary = __doc__.split('\n')[0]
- usage = __doc__
-
- def command(self):
- self._load_config()
-
- if not self.args:
- # default to run
- print(RDFExport.__doc__)
- else:
- self.export_datasets(self.args[0])
-
- def export_datasets(self, out_folder):
- '''
- Export datasets as RDF to an output folder.
- '''
- from ckan.common import config
- import ckan.model as model
- import ckan.logic as logic
- import ckan.lib.helpers as h
-
- # Create output folder if not exists
- if not os.path.isdir(out_folder):
- os.makedirs(out_folder)
-
- fetch_url = config['ckan.site_url']
- user = logic.get_action('get_site_user')({'model': model, 'ignore_auth': True}, {})
- context = {'model': model, 'session': model.Session, 'user': user['name']}
- dataset_names = logic.get_action('package_list')(context, {})
- for dataset_name in dataset_names:
- dd = logic.get_action('package_show')(context, {'id': dataset_name})
- if not dd['state'] == 'active':
- continue
-
- url = h.url_for('dataset.read', id=dd['name'])
-
- url = urljoin(fetch_url, url[1:]) + '.rdf'
- try:
- fname = os.path.join(out_folder, dd['name']) + ".rdf"
- try:
- r = urlopen(url).read()
- except HTTPError as e:
- if e.code == 404:
- error('Please install ckanext-dcat and enable the ' +
- '`dcat` plugin to use the RDF serializations')
- with open(fname, 'wb') as f:
- f.write(r)
- except IOError as ioe:
- sys.stderr.write(str(ioe) + "\n")
-
-
-class Sysadmin(CkanCommand):
- '''Gives sysadmin rights to a named user
-
- Usage:
- sysadmin - lists sysadmins
- sysadmin list - lists sysadmins
- sysadmin add USERNAME - make an existing user into a sysadmin
- sysadmin add USERNAME [FIELD1=VALUE1 FIELD2=VALUE2 ...]
- - creates a new user that is a sysadmin
- (prompts for password and email if not
- supplied).
- Field can be: apikey
- email
- fullname
- name (this will be the username)
- password
- sysadmin remove USERNAME - removes user from sysadmins
- '''
-
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = None
- min_args = 0
-
- def command(self):
- self._load_config()
-
- cmd = self.args[0] if self.args else None
- if cmd is None or cmd == 'list':
- self.list()
- elif cmd == 'add':
- self.add()
- elif cmd == 'remove':
- self.remove()
- else:
- print('Command %s not recognized' % cmd)
-
- def list(self):
- import ckan.model as model
- print('Sysadmins:')
- sysadmins = model.Session.query(model.User).filter_by(sysadmin=True,
- state='active')
- print('count = %i' % sysadmins.count())
- for sysadmin in sysadmins:
- print('%s name=%s email=%s id=%s' % (
- sysadmin.__class__.__name__,
- sysadmin.name,
- sysadmin.email,
- sysadmin.id))
-
- def add(self):
- import ckan.model as model
-
- if len(self.args) < 2:
- print('Need name of the user to be made sysadmin.')
- return
- username = self.args[1]
-
- user = model.User.by_name(text_type(username))
- if not user:
- print('User "%s" not found' % username)
- makeuser = input('Create new user: %s? [y/n]' % username)
- if makeuser == 'y':
- user_add(self.args[1:])
- user = model.User.by_name(text_type(username))
- else:
- print('Exiting ...')
- return
-
- user.sysadmin = True
- model.Session.add(user)
- model.repo.commit_and_remove()
- print('Added %s as sysadmin' % username)
-
- def remove(self):
- import ckan.model as model
-
- if len(self.args) < 2:
- print('Need name of the user to be made sysadmin.')
- return
- username = self.args[1]
-
- user = model.User.by_name(text_type(username))
- if not user:
- print('Error: user "%s" not found!' % username)
- return
- user.sysadmin = False
- model.repo.commit_and_remove()
-
-
-class UserCmd(CkanCommand):
- '''Manage users
-
- Usage:
- user - lists users
- user list - lists users
- user USERNAME - shows user properties
- user add USERNAME [FIELD1=VALUE1 FIELD2=VALUE2 ...]
- - add a user (prompts for email and
- password if not supplied).
- Field can be: apikey
- email
- fullname
- name (this will be the username)
- password
- user setpass USERNAME - set user password (prompts)
- user remove USERNAME - removes user from users
- user search QUERY - searches for a user name
- '''
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = None
- min_args = 0
-
- def command(self):
- self._load_config()
-
- if not self.args:
- self.list()
- else:
- cmd = self.args[0]
- if cmd == 'add':
- self.add()
- elif cmd == 'remove':
- self.remove()
- elif cmd == 'search':
- self.search()
- elif cmd == 'setpass':
- self.setpass()
- elif cmd == 'list':
- self.list()
- else:
- self.show()
-
- def get_user_str(self, user):
- user_str = 'name=%s' % user.name
- if user.name != user.display_name:
- user_str += ' display=%s' % user.display_name
- return user_str
-
- def list(self):
- import ckan.model as model
- print('Users:')
- users = model.Session.query(model.User).filter_by(state='active')
- print('count = %i' % users.count())
- for user in users:
- print(self.get_user_str(user))
-
- def show(self):
- import ckan.model as model
-
- username = self.args[0]
- user = model.User.get(text_type(username))
- print('User: \n', user)
-
- def setpass(self):
- import ckan.model as model
-
- if len(self.args) < 2:
- print('Need name of the user.')
- return
- username = self.args[1]
- user = model.User.get(username)
- print('Editing user: %r' % user.name)
-
- password = self.password_prompt()
- user.password = password
- model.repo.commit_and_remove()
- print('Done')
-
- def search(self):
- import ckan.model as model
-
- if len(self.args) < 2:
- print('Need user name query string.')
- return
- query_str = self.args[1]
-
- query = model.User.search(query_str)
- print('%i users matching %r:' % (query.count(), query_str))
- for user in query.all():
- print(self.get_user_str(user))
-
- @classmethod
- def password_prompt(cls):
- import getpass
- password1 = None
- while not password1:
- password1 = getpass.getpass('Password: ')
- password2 = getpass.getpass('Confirm password: ')
- if password1 != password2:
- error('Passwords do not match')
- return password1
-
- def add(self):
- user_add(self.args[1:])
-
- def remove(self):
- import ckan.model as model
-
- if len(self.args) < 2:
- print('Need name of the user.')
- return
- username = self.args[1]
-
- p.toolkit.get_action('user_delete')(
- {'model': model, 'ignore_auth': True},
- {'id': username})
- print('Deleted user: %s' % username)
-
-
-class DatasetCmd(CkanCommand):
- '''Manage datasets
-
- Usage:
- dataset DATASET_NAME|ID - shows dataset properties
- dataset show DATASET_NAME|ID - shows dataset properties
- dataset list - lists datasets
- dataset delete [DATASET_NAME|ID] - changes dataset state to 'deleted'
- dataset purge [DATASET_NAME|ID] - removes dataset from db entirely
- '''
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = 3
- min_args = 0
-
- def command(self):
- self._load_config()
-
- if not self.args:
- print(self.usage)
- else:
- cmd = self.args[0]
- if cmd == 'delete':
- self.delete(self.args[1])
- elif cmd == 'purge':
- self.purge(self.args[1])
- elif cmd == 'list':
- self.list()
- elif cmd == 'show':
- self.show(self.args[1])
- else:
- self.show(self.args[0])
-
- def list(self):
- import ckan.model as model
- print('Datasets:')
- datasets = model.Session.query(model.Package)
- print('count = %i' % datasets.count())
- for dataset in datasets:
- state = ('(%s)' % dataset.state) if dataset.state != 'active' else ''
- print('%s %s %s' % (dataset.id, dataset.name, state))
-
- def _get_dataset(self, dataset_ref):
- import ckan.model as model
- dataset = model.Package.get(text_type(dataset_ref))
- assert dataset, 'Could not find dataset matching reference: %r' % dataset_ref
- return dataset
-
- def show(self, dataset_ref):
- import pprint
- dataset = self._get_dataset(dataset_ref)
- pprint.pprint(dataset.as_dict())
-
- def delete(self, dataset_ref):
- import ckan.model as model
- dataset = self._get_dataset(dataset_ref)
- old_state = dataset.state
-
- dataset.delete()
- model.repo.commit_and_remove()
- dataset = self._get_dataset(dataset_ref)
- print('%s %s -> %s' % (dataset.name, old_state, dataset.state))
-
- def purge(self, dataset_ref):
- import ckan.logic as logic
- dataset = self._get_dataset(dataset_ref)
- name = dataset.name
-
- site_user = logic.get_action('get_site_user')({'ignore_auth': True}, {})
- context = {'user': site_user['name']}
- logic.get_action('dataset_purge')(
- context, {'id': dataset_ref})
- print('%s purged' % name)
-
-
-class Ratings(CkanCommand):
- '''Manage the ratings stored in the db
-
- Usage:
- ratings count - counts ratings
- ratings clean - remove all ratings
- ratings clean-anonymous - remove only anonymous ratings
- '''
-
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = 1
- min_args = 1
-
- def command(self):
- self._load_config()
- import ckan.model as model
-
- cmd = self.args[0]
- if cmd == 'count':
- self.count()
- elif cmd == 'clean':
- self.clean()
- elif cmd == 'clean-anonymous':
- self.clean(user_ratings=False)
- else:
- print('Command %s not recognized' % cmd)
-
- def count(self):
- import ckan.model as model
- q = model.Session.query(model.Rating)
- print("%i ratings" % q.count())
- q = q.filter(model.Rating.user_id is None)
- print("of which %i are anonymous ratings" % q.count())
-
- def clean(self, user_ratings=True):
- import ckan.model as model
- q = model.Session.query(model.Rating)
- print("%i ratings" % q.count())
- if not user_ratings:
- q = q.filter(model.Rating.user_id is None)
- print("of which %i are anonymous ratings" % q.count())
- ratings = q.all()
- for rating in ratings:
- rating.purge()
- model.repo.commit_and_remove()
-
-
-## Used by the Tracking class
-_ViewCount = collections.namedtuple("ViewCount", "id name count")
-
-
-class Tracking(CkanCommand):
- '''Update tracking statistics
-
- Usage:
- tracking update [start_date] - update tracking stats
- tracking export FILE [start_date] - export tracking stats to a csv file
- '''
-
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = 3
- min_args = 1
-
- def command(self):
- self._load_config()
- import ckan.model as model
- engine = model.meta.engine
-
- cmd = self.args[0]
- if cmd == 'update':
- start_date = self.args[1] if len(self.args) > 1 else None
- self.update_all(engine, start_date)
- elif cmd == 'export':
- if len(self.args) <= 1:
- error(self.__class__.__doc__)
- output_file = self.args[1]
- start_date = self.args[2] if len(self.args) > 2 else None
- self.update_all(engine, start_date)
- self.export_tracking(engine, output_file)
- else:
- error(self.__class__.__doc__)
-
- def update_all(self, engine, start_date=None):
- if start_date:
- start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
- else:
- # No date given. See when we last have data for and get data
- # from 2 days before then in case new data is available.
- # If no date here then use 2011-01-01 as the start date
- sql = '''SELECT tracking_date from tracking_summary
- ORDER BY tracking_date DESC LIMIT 1;'''
- result = engine.execute(sql).fetchall()
- if result:
- start_date = result[0]['tracking_date']
- start_date += datetime.timedelta(-2)
- # convert date to datetime
- combine = datetime.datetime.combine
- start_date = combine(start_date, datetime.time(0))
- else:
- start_date = datetime.datetime(2011, 1, 1)
- start_date_solrsync = start_date
- end_date = datetime.datetime.now()
-
- while start_date < end_date:
- stop_date = start_date + datetime.timedelta(1)
- self.update_tracking(engine, start_date)
- print('tracking updated for %s' % start_date)
- start_date = stop_date
-
- self.update_tracking_solr(engine, start_date_solrsync)
-
- def _total_views(self, engine):
- sql = '''
- SELECT p.id,
- p.name,
- COALESCE(SUM(s.count), 0) AS total_views
- FROM package AS p
- LEFT OUTER JOIN tracking_summary AS s ON s.package_id = p.id
- GROUP BY p.id, p.name
- ORDER BY total_views DESC
- '''
- return [_ViewCount(*t) for t in engine.execute(sql).fetchall()]
-
- def _recent_views(self, engine, measure_from):
- sql = '''
- SELECT p.id,
- p.name,
- COALESCE(SUM(s.count), 0) AS total_views
- FROM package AS p
- LEFT OUTER JOIN tracking_summary AS s ON s.package_id = p.id
- WHERE s.tracking_date >= %(measure_from)s
- GROUP BY p.id, p.name
- ORDER BY total_views DESC
- '''
- return [_ViewCount(*t) for t in engine.execute(sql, measure_from=str(measure_from)).fetchall()]
-
- def export_tracking(self, engine, output_filename):
- '''Write tracking summary to a csv file.'''
- HEADINGS = [
- "dataset id",
- "dataset name",
- "total views",
- "recent views (last 2 weeks)",
- ]
-
- measure_from = datetime.date.today() - datetime.timedelta(days=14)
- recent_views = self._recent_views(engine, measure_from)
- total_views = self._total_views(engine)
-
- with open(output_filename, 'w') as fh:
- f_out = csv.writer(fh)
- f_out.writerow(HEADINGS)
- recent_views_for_id = dict((r.id, r.count) for r in recent_views)
- f_out.writerows([(r.id,
- r.name,
- r.count,
- recent_views_for_id.get(r.id, 0))
- for r in total_views])
-
- def update_tracking(self, engine, summary_date):
- PACKAGE_URL = '/dataset/'
- # clear out existing data before adding new
- sql = '''DELETE FROM tracking_summary
- WHERE tracking_date='%s'; ''' % summary_date
- engine.execute(sql)
-
- sql = '''SELECT DISTINCT url, user_key,
- CAST(access_timestamp AS Date) AS tracking_date,
- tracking_type INTO tracking_tmp
- FROM tracking_raw
- WHERE CAST(access_timestamp as Date)=%s;
-
- INSERT INTO tracking_summary
- (url, count, tracking_date, tracking_type)
- SELECT url, count(user_key), tracking_date, tracking_type
- FROM tracking_tmp
- GROUP BY url, tracking_date, tracking_type;
-
- DROP TABLE tracking_tmp;
- COMMIT;'''
- engine.execute(sql, summary_date)
-
- # get ids for dataset urls
- sql = '''UPDATE tracking_summary t
- SET package_id = COALESCE(
- (SELECT id FROM package p
- WHERE p.name = regexp_replace(' ' || t.url, '^[ ]{1}(/\w{2}){0,1}' || %s, ''))
- ,'~~not~found~~')
- WHERE t.package_id IS NULL
- AND tracking_type = 'page';'''
- engine.execute(sql, PACKAGE_URL)
-
- # update summary totals for resources
- sql = '''UPDATE tracking_summary t1
- SET running_total = (
- SELECT sum(count)
- FROM tracking_summary t2
- WHERE t1.url = t2.url
- AND t2.tracking_date <= t1.tracking_date
- )
- ,recent_views = (
- SELECT sum(count)
- FROM tracking_summary t2
- WHERE t1.url = t2.url
- AND t2.tracking_date <= t1.tracking_date AND t2.tracking_date >= t1.tracking_date - 14
- )
- WHERE t1.running_total = 0 AND tracking_type = 'resource';'''
- engine.execute(sql)
-
- # update summary totals for pages
- sql = '''UPDATE tracking_summary t1
- SET running_total = (
- SELECT sum(count)
- FROM tracking_summary t2
- WHERE t1.package_id = t2.package_id
- AND t2.tracking_date <= t1.tracking_date
- )
- ,recent_views = (
- SELECT sum(count)
- FROM tracking_summary t2
- WHERE t1.package_id = t2.package_id
- AND t2.tracking_date <= t1.tracking_date AND t2.tracking_date >= t1.tracking_date - 14
- )
- WHERE t1.running_total = 0 AND tracking_type = 'page'
- AND t1.package_id IS NOT NULL
- AND t1.package_id != '~~not~found~~';'''
- engine.execute(sql)
-
- def update_tracking_solr(self, engine, start_date):
- sql = '''SELECT package_id FROM tracking_summary
- where package_id!='~~not~found~~'
- and tracking_date >= %s;'''
- results = engine.execute(sql, start_date)
-
- package_ids = set()
- for row in results:
- package_ids.add(row['package_id'])
-
- total = len(package_ids)
- not_found = 0
- print('%i package index%s to be rebuilt starting from %s' % (total, '' if total < 2 else 'es', start_date))
-
- from ckan.lib.search import rebuild
- for package_id in package_ids:
- try:
- rebuild(package_id)
- except logic.NotFound:
- print("Error: package %s not found." % (package_id))
- not_found += 1
- except KeyboardInterrupt:
- print("Stopped.")
- return
- except:
- raise
- print('search index rebuilding done.' + (' %i not found.' % (not_found) if not_found else ""))
-
-
-class PluginInfo(CkanCommand):
- '''Provide info on installed plugins.
- '''
-
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = 0
- min_args = 0
-
- def command(self):
- self.get_info()
-
- def get_info(self):
- ''' print info about current plugins from the .ini file'''
- import ckan.plugins as p
- self._load_config()
- interfaces = {}
- plugins = {}
- for name in dir(p):
- item = getattr(p, name)
- try:
- if issubclass(item, p.Interface):
- interfaces[item] = {'class': item}
- except TypeError:
- pass
-
- for interface in interfaces:
- for plugin in p.PluginImplementations(interface):
- name = plugin.name
- if name not in plugins:
- plugins[name] = {'doc': plugin.__doc__,
- 'class': plugin,
- 'implements': []}
- plugins[name]['implements'].append(interface.__name__)
-
- for plugin in plugins:
- p = plugins[plugin]
- print(plugin + ':')
- print('-' * (len(plugin) + 1))
- if p['doc']:
- print(p['doc'])
- print('Implements:')
- for i in p['implements']:
- extra = None
- if i == 'ITemplateHelpers':
- extra = self.template_helpers(p['class'])
- if i == 'IActions':
- extra = self.actions(p['class'])
- print(' %s' % i)
- if extra:
- print(extra)
- print()
-
- def actions(self, cls):
- ''' Return readable action function info. '''
- actions = cls.get_actions()
- return self.function_info(actions)
-
- def template_helpers(self, cls):
- ''' Return readable helper function info. '''
- helpers = cls.get_helpers()
- return self.function_info(helpers)
-
- def function_info(self, functions):
- ''' Take a dict of functions and output readable info '''
- import inspect
- output = []
- for function_name in functions:
- fn = functions[function_name]
- args_info = inspect.getargspec(fn)
- params = args_info.args
- num_params = len(params)
- if args_info.varargs:
- params.append('*' + args_info.varargs)
- if args_info.keywords:
- params.append('**' + args_info.keywords)
- if args_info.defaults:
- offset = num_params - len(args_info.defaults)
- for i, v in enumerate(args_info.defaults):
- params[i + offset] = params[i + offset] + '=' + repr(v)
- # is this a classmethod if so remove the first parameter
- if inspect.ismethod(fn) and inspect.isclass(fn.__self__):
- params = params[1:]
- params = ', '.join(params)
- output.append(' %s(%s)' % (function_name, params))
- # doc string
- if fn.__doc__:
- bits = fn.__doc__.split('\n')
- for bit in bits:
- output.append(' %s' % bit)
- return ('\n').join(output)
-
-
-class CreateTestDataCommand(CkanCommand):
- '''Create test data in the database.
- Tests can also delete the created objects easily with the delete() method.
-
- create-test-data - annakarenina and warandpeace
- create-test-data search - realistic data to test search
- create-test-data gov - government style data
- create-test-data family - package relationships data
- create-test-data user - create a user 'tester' with api key 'tester'
- create-test-data translations - annakarenina, warandpeace, and some test
- translations of terms
- create-test-data vocabs - annakerenina, warandpeace, and some test
- vocabularies
- create-test-data hierarchy - hierarchy of groups
- '''
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = 1
- min_args = 0
-
- def command(self):
- self._load_config()
- from ckan.lib.create_test_data import CreateTestData
-
- if self.args:
- cmd = self.args[0]
- else:
- cmd = 'basic'
- if self.verbose:
- print('Creating %s test data' % cmd)
- if cmd == 'basic':
- CreateTestData.create_basic_test_data()
- elif cmd == 'user':
- CreateTestData.create_test_user()
- print('Created user %r with password %r and apikey %r' %
- ('tester', 'tester', 'tester'))
- elif cmd == 'search':
- CreateTestData.create_search_test_data()
- elif cmd == 'gov':
- CreateTestData.create_gov_test_data()
- elif cmd == 'family':
- CreateTestData.create_family_test_data()
- elif cmd == 'translations':
- CreateTestData.create_translations_test_data()
- elif cmd == 'vocabs':
- CreateTestData.create_vocabs_test_data()
- elif cmd == 'hierarchy':
- CreateTestData.create_group_hierarchy_test_data()
- else:
- print('Command %s not recognized' % cmd)
- raise NotImplementedError
- if self.verbose:
- print('Creating %s test data: Complete!' % cmd)
-
-
-class Profile(CkanCommand):
- '''Code speed profiler
- Provide a ckan url and it will make the request and record
- how long each function call took in a file that can be read
- by pstats.Stats (command-line) or runsnakerun (gui).
-
- Usage:
- profile URL [username]
-
- e.g. profile /data/search
-
- The result is saved in profile.data.search
- To view the profile in runsnakerun:
- runsnakerun ckan.data.search.profile
-
- You may need to install python module: cProfile
- '''
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = 2
- min_args = 1
-
- def _load_config_into_test_app(self):
- from paste.deploy import loadapp
- import paste.fixture
- if not self.options.config:
- msg = 'No config file supplied'
- raise self.BadCommand(msg)
- self.filename = os.path.abspath(self.options.config)
- if not os.path.exists(self.filename):
- raise AssertionError('Config filename %r does not exist.' % self.filename)
- fileConfig(self.filename)
-
- wsgiapp = loadapp('config:' + self.filename)
- self.app = paste.fixture.TestApp(wsgiapp)
-
- def command(self):
- self._load_config_into_test_app()
-
- import paste.fixture
- import cProfile
- import re
-
- url = self.args[0]
- if self.args[1:]:
- user = self.args[1]
- else:
- user = 'visitor'
-
- def profile_url(url):
- try:
- res = self.app.get(url, status=[200],
- extra_environ={'REMOTE_USER': user})
- except paste.fixture.AppError:
- print('App error: ', url.strip())
- except KeyboardInterrupt:
- raise
- except Exception:
- error(traceback.format_exc())
-
- output_filename = 'ckan%s.profile' % re.sub('[/?]', '.', url.replace('/', '.'))
- profile_command = "profile_url('%s')" % url
- cProfile.runctx(profile_command, globals(), locals(), filename=output_filename)
- import pstats
- stats = pstats.Stats(output_filename)
- stats.sort_stats('cumulative')
- stats.print_stats(0.1) # show only top 10% of lines
- print('Only top 10% of lines shown')
- print('Written profile to: %s' % output_filename)
-
-
-class CreateColorSchemeCommand(CkanCommand):
- '''Create or remove a color scheme.
-
- After running this, you'll need to regenerate the css files. See paster's less command for details.
-
- color - creates a random color scheme
- color clear - clears any color scheme
- color <'HEX'> - uses as base color eg '#ff00ff' must be quoted.
- color <VALUE> - a float between 0.0 and 1.0 used as base hue
- color <COLOR_NAME> - html color name used for base color eg lightblue
- '''
-
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = 1
- min_args = 0
-
- rules = [
- '@layoutLinkColor',
- '@mastheadBackgroundColor',
- '@btnPrimaryBackground',
- '@btnPrimaryBackgroundHighlight',
- ]
-
- # list of predefined colors
- color_list = {
- 'aliceblue': '#f0fff8',
- 'antiquewhite': '#faebd7',
- 'aqua': '#00ffff',
- 'aquamarine': '#7fffd4',
- 'azure': '#f0ffff',
- 'beige': '#f5f5dc',
- 'bisque': '#ffe4c4',
- 'black': '#000000',
- 'blanchedalmond': '#ffebcd',
- 'blue': '#0000ff',
- 'blueviolet': '#8a2be2',
- 'brown': '#a52a2a',
- 'burlywood': '#deb887',
- 'cadetblue': '#5f9ea0',
- 'chartreuse': '#7fff00',
- 'chocolate': '#d2691e',
- 'coral': '#ff7f50',
- 'cornflowerblue': '#6495ed',
- 'cornsilk': '#fff8dc',
- 'crimson': '#dc143c',
- 'cyan': '#00ffff',
- 'darkblue': '#00008b',
- 'darkcyan': '#008b8b',
- 'darkgoldenrod': '#b8860b',
- 'darkgray': '#a9a9a9',
- 'darkgrey': '#a9a9a9',
- 'darkgreen': '#006400',
- 'darkkhaki': '#bdb76b',
- 'darkmagenta': '#8b008b',
- 'darkolivegreen': '#556b2f',
- 'darkorange': '#ff8c00',
- 'darkorchid': '#9932cc',
- 'darkred': '#8b0000',
- 'darksalmon': '#e9967a',
- 'darkseagreen': '#8fbc8f',
- 'darkslateblue': '#483d8b',
- 'darkslategray': '#2f4f4f',
- 'darkslategrey': '#2f4f4f',
- 'darkturquoise': '#00ced1',
- 'darkviolet': '#9400d3',
- 'deeppink': '#ff1493',
- 'deepskyblue': '#00bfff',
- 'dimgray': '#696969',
- 'dimgrey': '#696969',
- 'dodgerblue': '#1e90ff',
- 'firebrick': '#b22222',
- 'floralwhite': '#fffaf0',
- 'forestgreen': '#228b22',
- 'fuchsia': '#ff00ff',
- 'gainsboro': '#dcdcdc',
- 'ghostwhite': '#f8f8ff',
- 'gold': '#ffd700',
- 'goldenrod': '#daa520',
- 'gray': '#808080',
- 'grey': '#808080',
- 'green': '#008000',
- 'greenyellow': '#adff2f',
- 'honeydew': '#f0fff0',
- 'hotpink': '#ff69b4',
- 'indianred ': '#cd5c5c',
- 'indigo ': '#4b0082',
- 'ivory': '#fffff0',
- 'khaki': '#f0e68c',
- 'lavender': '#e6e6fa',
- 'lavenderblush': '#fff0f5',
- 'lawngreen': '#7cfc00',
- 'lemonchiffon': '#fffacd',
- 'lightblue': '#add8e6',
- 'lightcoral': '#f08080',
- 'lightcyan': '#e0ffff',
- 'lightgoldenrodyellow': '#fafad2',
- 'lightgray': '#d3d3d3',
- 'lightgrey': '#d3d3d3',
- 'lightgreen': '#90ee90',
- 'lightpink': '#ffb6c1',
- 'lightsalmon': '#ffa07a',
- 'lightseagreen': '#20b2aa',
- 'lightskyblue': '#87cefa',
- 'lightslategray': '#778899',
- 'lightslategrey': '#778899',
- 'lightsteelblue': '#b0c4de',
- 'lightyellow': '#ffffe0',
- 'lime': '#00ff00',
- 'limegreen': '#32cd32',
- 'linen': '#faf0e6',
- 'magenta': '#ff00ff',
- 'maroon': '#800000',
- 'mediumaquamarine': '#66cdaa',
- 'mediumblue': '#0000cd',
- 'mediumorchid': '#ba55d3',
- 'mediumpurple': '#9370d8',
- 'mediumseagreen': '#3cb371',
- 'mediumslateblue': '#7b68ee',
- 'mediumspringgreen': '#00fa9a',
- 'mediumturquoise': '#48d1cc',
- 'mediumvioletred': '#c71585',
- 'midnightblue': '#191970',
- 'mintcream': '#f5fffa',
- 'mistyrose': '#ffe4e1',
- 'moccasin': '#ffe4b5',
- 'navajowhite': '#ffdead',
- 'navy': '#000080',
- 'oldlace': '#fdf5e6',
- 'olive': '#808000',
- 'olivedrab': '#6b8e23',
- 'orange': '#ffa500',
- 'orangered': '#ff4500',
- 'orchid': '#da70d6',
- 'palegoldenrod': '#eee8aa',
- 'palegreen': '#98fb98',
- 'paleturquoise': '#afeeee',
- 'palevioletred': '#d87093',
- 'papayawhip': '#ffefd5',
- 'peachpuff': '#ffdab9',
- 'peru': '#cd853f',
- 'pink': '#ffc0cb',
- 'plum': '#dda0dd',
- 'powderblue': '#b0e0e6',
- 'purple': '#800080',
- 'red': '#ff0000',
- 'rosybrown': '#bc8f8f',
- 'royalblue': '#4169e1',
- 'saddlebrown': '#8b4513',
- 'salmon': '#fa8072',
- 'sandybrown': '#f4a460',
- 'seagreen': '#2e8b57',
- 'seashell': '#fff5ee',
- 'sienna': '#a0522d',
- 'silver': '#c0c0c0',
- 'skyblue': '#87ceeb',
- 'slateblue': '#6a5acd',
- 'slategray': '#708090',
- 'slategrey': '#708090',
- 'snow': '#fffafa',
- 'springgreen': '#00ff7f',
- 'steelblue': '#4682b4',
- 'tan': '#d2b48c',
- 'teal': '#008080',
- 'thistle': '#d8bfd8',
- 'tomato': '#ff6347',
- 'turquoise': '#40e0d0',
- 'violet': '#ee82ee',
- 'wheat': '#f5deb3',
- 'white': '#ffffff',
- 'whitesmoke': '#f5f5f5',
- 'yellow': '#ffff00',
- 'yellowgreen': '#9acd32',
- }
-
- def create_colors(self, hue, num_colors=5, saturation=None, lightness=None):
- if saturation is None:
- saturation = 0.9
- if lightness is None:
- lightness = 40
- else:
- lightness *= 100
-
- import math
- saturation -= math.trunc(saturation)
-
- print(hue, saturation)
- import colorsys
- ''' Create n related colours '''
- colors = []
- for i in xrange(num_colors):
- ix = i * (1.0/num_colors)
- _lightness = (lightness + (ix * 40))/100.
- if _lightness > 1.0:
- _lightness = 1.0
- color = colorsys.hls_to_rgb(hue, _lightness, saturation)
- hex_color = '#'
- for part in color:
- hex_color += '%02x' % int(part * 255)
- # check and remove any bad values
- if not re.match('^\#[0-9a-f]{6}$', hex_color):
- hex_color = '#FFFFFF'
- colors.append(hex_color)
- return colors
-
- def command(self):
-
- hue = None
- saturation = None
- lightness = None
-
- public = config.get(u'ckan.base_public_folder')
- path = os.path.dirname(__file__)
- path = os.path.join(path, '..', public, 'base', 'less', 'custom.less')
-
- if self.args:
- arg = self.args[0]
- rgb = None
- if arg == 'clear':
- os.remove(path)
- print('custom colors removed.')
- elif arg.startswith('#'):
- color = arg[1:]
- if len(color) == 3:
- rgb = [int(x, 16) * 16 for x in color]
- elif len(color) == 6:
- rgb = [int(x, 16) for x in re.findall('..', color)]
- else:
- print('ERROR: invalid color')
- elif arg.lower() in self.color_list:
- color = self.color_list[arg.lower()][1:]
- rgb = [int(x, 16) for x in re.findall('..', color)]
- else:
- try:
- hue = float(self.args[0])
- except ValueError:
- print('ERROR argument `%s` not recognised' % arg)
- if rgb:
- import colorsys
- hue, lightness, saturation = colorsys.rgb_to_hls(*rgb)
- lightness = lightness / 340
- # deal with greys
- if not (hue == 0.0 and saturation == 0.0):
- saturation = None
- else:
- import random
- hue = random.random()
- if hue is not None:
- f = open(path, 'w')
- colors = self.create_colors(hue, saturation=saturation, lightness=lightness)
- for i in xrange(len(self.rules)):
- f.write('%s: %s;\n' % (self.rules[i], colors[i]))
- print('%s: %s;\n' % (self.rules[i], colors[i]))
- f.close
- print('Color scheme has been created.')
- print('Make sure less is run for changes to take effect.')
-
-
-class TranslationsCommand(CkanCommand):
- '''Translation helper functions
-
- trans js - generate the javascript translations
- trans mangle - mangle the zh_TW translations for testing
- '''
-
- summary = __doc__.split('\n')[0]
- usage = __doc__
- max_args = 1
- min_args = 1
-
- def command(self):
- self._load_config()
- from ckan.common import config
- from ckan.lib.i18n import build_js_translations
- ckan_path = os.path.join(os.path.dirname(__file__), '..')
- self.i18n_path = config.get('ckan.i18n_directory',
- os.path.join(ckan_path, 'i18n'))
- command = self.args[0]
- if command == 'mangle':
- self.mangle_po()
- elif command == 'js':
- build_js_translations()
- else:
- print('command not recognised')
-
- def mangle_po(self):
- ''' This will mangle the zh_TW translations for translation coverage
- testing.
-
- NOTE: This will destroy the current translations fot zh_TW
- '''
- import polib
- pot_path = os.path.join(self.i18n_path, 'ckan.pot')
- po = polib.pofile(pot_path)
- # we don't want to mangle the following items in strings
- # %(...)s %s %0.3f %1$s %2$0.3f [1:...] {...} etc
-
- # sprintf bit after %
- spf_reg_ex = "\+?(0|'.)?-?\d*(.\d*)?[\%bcdeufosxX]"
-
- extract_reg_ex = '(\%\([^\)]*\)' + spf_reg_ex + \
- '|\[\d*\:[^\]]*\]' + \
- '|\{[^\}]*\}' + \
- '|<[^>}]*>' + \
- '|\%((\d)*\$)?' + spf_reg_ex + ')'
-
- for entry in po:
- msg = entry.msgid.encode('utf-8')
- matches = re.finditer(extract_reg_ex, msg)
- length = len(msg)
- position = 0
- translation = u''
- for match in matches:
- translation += '-' * (match.start() - position)
- position = match.end()
- translation += match.group(0)
- translation += '-' * (length - position)
- entry.msgstr = translation
- out_dir = os.path.join(self.i18n_path, 'zh_TW', 'LC_MESSAGES')
- try:
- os.makedirs(out_dir)
- except OSError:
- pass
- po.metadata['Plural-Forms'] = "nplurals=1; plural=0\n"
- out_po = os.path.join(out_dir, 'ckan.po')
- out_mo = os.path.join(out_dir, 'ckan.mo')
- po.save(out_po)
- po.save_as_mofile(out_mo)
- print('zh_TW has been mangled')
-
-
-class MinifyCommand(CkanCommand):
- '''Create minified versions of the given Javascript and CSS files.
-
- Usage:
-
- paster minify [--clean] PATH
-
- for example:
-
- paster minify ckan/public/base
- paster minify ckan/public/base/css/*.css
- paster minify ckan/public/base/css/red.css
-
- if the --clean option is provided any minified files will be removed.
-
- '''
- summary = __doc__.split('\n')[0]
- usage = __doc__
- min_args = 1
-
- exclude_dirs = ['vendor']
-
- def __init__(self, name):
-
- super(MinifyCommand, self).__init__(name)
-
- self.parser.add_option('--clean', dest='clean',
- action='store_true', default=False,
- help='remove any minified files in the path')
-
- def command(self):
- clean = getattr(self.options, 'clean', False)
- self._load_config()
- for base_path in self.args:
- if os.path.isfile(base_path):
- if clean:
- self.clear_minifyed(base_path)
- else:
- self.minify_file(base_path)
- elif os.path.isdir(base_path):
- for root, dirs, files in os.walk(base_path):
- dirs[:] = [d for d in dirs if not d in self.exclude_dirs]
- for filename in files:
- path = os.path.join(root, filename)
- if clean:
- self.clear_minifyed(path)
- else:
- self.minify_file(path)
- else:
- # Path is neither a file or a dir?
- continue
-
- def clear_minifyed(self, path):
- path_only, extension = os.path.splitext(path)
-
- if extension not in ('.css', '.js'):
- # This is not a js or css file.
- return
-
- if path_only.endswith('.min'):
- print('removing %s' % path)
- os.remove(path)
-
- def minify_file(self, path):
- '''Create the minified version of the given file.
-
- If the file is not a .js or .css file (e.g. it's a .min.js or .min.css
- file, or it's some other type of file entirely) it will not be
- minifed.
-
- :param path: The path to the .js or .css file to minify
-
- '''
- import ckan.lib.fanstatic_resources as fanstatic_resources
-
- path_only, extension = os.path.splitext(path)
-
- if path_only.endswith('.min'):
- # This is already a minified file.
- return
-
- if extension not in ('.css', '.js'):
- # This is not a js or css file.
- return
-
- path_min = fanstatic_resources.min_path(path)
-
- source = open(path, 'r').read()
- f = open(path_min, 'w')
- if path.endswith('.css'):
- f.write(rcssmin.cssmin(source))
- elif path.endswith('.js'):
- f.write(rjsmin.jsmin(source))
- f.close()
- print("Minified file '{0}'".format(path))
-
-
-class LessCommand(CkanCommand):
- '''Compile all root less documents into their CSS counterparts
-
- Usage:
-
- paster less
-
- '''
- summary = __doc__.split('\n')[0]
- usage = __doc__
- min_args = 0
-
- def command(self):
- self._load_config()
- self.less()
-
- custom_css = {
- 'fuchsia': '''
- @layoutLinkColor: #E73892;
- @footerTextColor: mix(#FFF, @layoutLinkColor, 60%);
- @footerLinkColor: @footerTextColor;
- @mastheadBackgroundColor: @layoutLinkColor;
- @btnPrimaryBackground: lighten(@layoutLinkColor, 10%);
- @btnPrimaryBackgroundHighlight: @layoutLinkColor;
- ''',
-
- 'green': '''
- @layoutLinkColor: #2F9B45;
- @footerTextColor: mix(#FFF, @layoutLinkColor, 60%);
- @footerLinkColor: @footerTextColor;
- @mastheadBackgroundColor: @layoutLinkColor;
- @btnPrimaryBackground: lighten(@layoutLinkColor, 10%);
- @btnPrimaryBackgroundHighlight: @layoutLinkColor;
- ''',
-
- 'red': '''
- @layoutLinkColor: #C14531;
- @footerTextColor: mix(#FFF, @layoutLinkColor, 60%);
- @footerLinkColor: @footerTextColor;
- @mastheadBackgroundColor: @layoutLinkColor;
- @btnPrimaryBackground: lighten(@layoutLinkColor, 10%);
- @btnPrimaryBackgroundHighlight: @layoutLinkColor;
- ''',
-
- 'maroon': '''
- @layoutLinkColor: #810606;
- @footerTextColor: mix(#FFF, @layoutLinkColor, 60%);
- @footerLinkColor: @footerTextColor;
- @mastheadBackgroundColor: @layoutLinkColor;
- @btnPrimaryBackground: lighten(@layoutLinkColor, 10%);
- @btnPrimaryBackgroundHighlight: @layoutLinkColor;
- ''',
- }
-
- def less(self):
- ''' Compile less files '''
- import subprocess
- command = ('npm', 'bin')
- process = subprocess.Popen(
- command,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- universal_newlines=True)
- output = process.communicate()
- directory = output[0].strip()
- if not directory:
- raise error('Command "{}" returned nothing. Check that npm is '
- 'installed.'.format(' '.join(command)))
- less_bin = os.path.join(directory, 'lessc')
-
- public = config.get(u'ckan.base_public_folder')
-
- root = os.path.join(os.path.dirname(__file__), '..', public, 'base')
- root = os.path.abspath(root)
- custom_less = os.path.join(root, 'less', 'custom.less')
- for color in self.custom_css:
- f = open(custom_less, 'w')
- f.write(self.custom_css[color])
- f.close()
- self.compile_less(root, less_bin, color)
- f = open(custom_less, 'w')
- f.write('// This file is needed in order for `gulp build` to compile in less 1.3.1+\n')
- f.close()
- self.compile_less(root, less_bin, 'main')
-
- def compile_less(self, root, less_bin, color):
- print('compile %s.css' % color)
- import subprocess
- main_less = os.path.join(root, 'less', 'main.less')
- main_css = os.path.join(root, 'css', '%s.css' % color)
-
- command = (less_bin, main_less, main_css)
- process = subprocess.Popen(
- command,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- universal_newlines=True)
- output = process.communicate()
- print(output)
-
-
-class FrontEndBuildCommand(CkanCommand):
- '''Creates and minifies css and JavaScript files
-
- Usage:
-
- paster front-end-build
- '''
-
- summary = __doc__.split('\n')[0]
- usage = __doc__
- min_args = 0
-
- def command(self):
- self._load_config()
-
- # Less css
- cmd = LessCommand('less')
- cmd.options = self.options
- cmd.command()
-
- # js translation strings
- cmd = TranslationsCommand('trans')
- cmd.options = self.options
- cmd.args = ('js',)
- cmd.command()
-
- # minification
- cmd = MinifyCommand('minify')
- cmd.options = self.options
- public = config.get(u'ckan.base_public_folder')
- root = os.path.join(os.path.dirname(__file__), '..', public, 'base')
- root = os.path.abspath(root)
- ckanext = os.path.join(os.path.dirname(__file__), '..', '..', 'ckanext')
- ckanext = os.path.abspath(ckanext)
- cmd.args = (root, ckanext)
- cmd.command()
-
-
-class ViewsCommand(CkanCommand):
- '''Manage resource views.
-
- Usage:
-
- paster views create [options] [type1] [type2] ...
-
- Create views on relevant resources. You can optionally provide
- specific view types (eg `recline_view`, `image_view`). If no types
- are provided, the default ones will be used. These are generally
- the ones defined in the `ckan.views.default_views` config option.
- Note that on either case, plugins must be loaded (ie added to
- `ckan.plugins`), otherwise the command will stop.
-
- paster views clear [options] [type1] [type2] ...
-
- Permanently delete all views or the ones with the provided types.
-
- paster views clean
-
- Permanently delete views for all types no longer present in the
- `ckan.plugins` configuration option.
-
- '''
-
- summary = __doc__.split('\n')[0]
- usage = __doc__
- min_args = 1
-
- def __init__(self, name):
-
- super(ViewsCommand, self).__init__(name)
-
- self.parser.add_option('-y', '--yes', dest='assume_yes',
- action='store_true',
- default=False,
- help='''Automatic yes to prompts. Assume "yes"
-as answer to all prompts and run non-interactively''')
-
- self.parser.add_option('-d', '--dataset', dest='dataset_id',
- action='append',
- help='''Create views on a particular dataset.
-You can use the dataset id or name, and it can be defined multiple times.''')
-
- self.parser.add_option('--no-default-filters',
- dest='no_default_filters',
- action='store_true',
- default=False,
- help='''Do not add default filters for relevant
-resource formats for the view types provided. Note that filters are not added
-by default anyway if an unsupported view type is provided or when using the
-`-s` or `-d` options.''')
-
- self.parser.add_option('-s', '--search', dest='search_params',
- action='store',
- default=False,
- help='''Extra search parameters that will be
-used for getting the datasets to create the resource views on. It must be a
-JSON object like the one used by the `package_search` API call. Supported
-fields are `q`, `fq` and `fq_list`. Check the documentation for examples.
-Not used when using the `-d` option.''')
-
- def command(self):
- self._load_config()
- if not self.args:
- print(self.usage)
- elif self.args[0] == 'create':
- view_plugin_types = self.args[1:]
- self.create_views(view_plugin_types)
- elif self.args[0] == 'clear':
- view_plugin_types = self.args[1:]
- self.clear_views(view_plugin_types)
- elif self.args[0] == 'clean':
- self.clean_views()
- else:
- print(self.usage)
-
- _page_size = 100
-
- def _get_view_plugins(self, view_plugin_types,
- get_datastore_views=False):
- '''
- Returns the view plugins that were succesfully loaded
-
- Views are provided as a list of ``view_plugin_types``. If no types are
- provided, the default views defined in the ``ckan.views.default_views``
- will be created. Only in this case (when the default view plugins are
- used) the `get_datastore_views` parameter can be used to get also view
- plugins that require data to be in the DataStore.
-
- If any of the provided plugins could not be loaded (eg it was not added
- to `ckan.plugins`) the command will stop.
-
- Returns a list of loaded plugin names.
- '''
- from ckan.lib.datapreview import (get_view_plugins,
- get_default_view_plugins
- )
-
- log = logging.getLogger(__name__)
-
- view_plugins = []
-
- if not view_plugin_types:
- log.info('No view types provided, using default types')
- view_plugins = get_default_view_plugins()
- if get_datastore_views:
- view_plugins.extend(
- get_default_view_plugins(get_datastore_views=True))
- else:
- view_plugins = get_view_plugins(view_plugin_types)
-
- loaded_view_plugins = [view_plugin.info()['name']
- for view_plugin in view_plugins]
-
- plugins_not_found = list(set(view_plugin_types) -
- set(loaded_view_plugins))
-
- if plugins_not_found:
- error('View plugin(s) not found : {0}. '.format(plugins_not_found)
- + 'Have they been added to the `ckan.plugins` configuration'
- + ' option?')
-
- return loaded_view_plugins
-
- def _add_default_filters(self, search_data_dict, view_types):
- '''
- Adds extra filters to the `package_search` dict for common view types
-
- It basically adds `fq` parameters that filter relevant resource formats
- for the view types provided. For instance, if one of the view types is
- `pdf_view` the following will be added to the final query:
-
- fq=res_format:"pdf" OR res_format:"PDF"
-
- This obviously should only be used if all view types are known and can
- be filtered, otherwise we want all datasets to be returned. If a
- non-filterable view type is provided, the search params are not
- modified.
-
- Returns the provided data_dict for `package_search`, optionally
- modified with extra filters.
- '''
-
- from ckanext.imageview.plugin import DEFAULT_IMAGE_FORMATS
- from ckanext.textview.plugin import get_formats as get_text_formats
- from ckanext.datapusher.plugin import DEFAULT_FORMATS as \
- datapusher_formats
-
- filter_formats = []
-
- for view_type in view_types:
- if view_type == 'image_view':
-
- for _format in DEFAULT_IMAGE_FORMATS:
- filter_formats.extend([_format, _format.upper()])
-
- elif view_type == 'text_view':
- formats = get_text_formats(config)
- for _format in itertools.chain.from_iterable(formats.values()):
- filter_formats.extend([_format, _format.upper()])
-
- elif view_type == 'pdf_view':
- filter_formats.extend(['pdf', 'PDF'])
-
- elif view_type in ['recline_view', 'recline_grid_view',
- 'recline_graph_view', 'recline_map_view']:
-
- if datapusher_formats[0] in filter_formats:
- continue
-
- for _format in datapusher_formats:
- if '/' not in _format:
- filter_formats.extend([_format, _format.upper()])
- else:
- # There is another view type provided so we can't add any
- # filter
- return search_data_dict
-
- filter_formats_query = ['+res_format:"{0}"'.format(_format)
- for _format in filter_formats]
- search_data_dict['fq_list'].append(' OR '.join(filter_formats_query))
-
- return search_data_dict
-
- def _update_search_params(self, search_data_dict):
- '''
- Update the `package_search` data dict with the user provided parameters
-
- Supported fields are `q`, `fq` and `fq_list`.
-
- If the provided JSON object can not be parsed the process stops with
- an error.
-
- Returns the updated data dict
- '''
-
- log = logging.getLogger(__name__)
-
- if not self.options.search_params:
- return search_data_dict
-
- try:
- user_search_params = json.loads(self.options.search_params)
- except ValueError as e:
- error('Unable to parse JSON search parameters: {0}'.format(e))
-
- if user_search_params.get('q'):
- search_data_dict['q'] = user_search_params['q']
-
- if user_search_params.get('fq'):
- if search_data_dict['fq']:
- search_data_dict['fq'] += ' ' + user_search_params['fq']
- else:
- search_data_dict['fq'] = user_search_params['fq']
-
- if (user_search_params.get('fq_list') and
- isinstance(user_search_params['fq_list'], list)):
- search_data_dict['fq_list'].extend(user_search_params['fq_list'])
-
- def _search_datasets(self, page=1, view_types=[]):
- '''
- Perform a query with `package_search` and return the result
-
- Results can be paginated using the `page` parameter
- '''
-
- n = self._page_size
-
- search_data_dict = {
- 'q': '',
- 'fq': '',
- 'fq_list': [],
- 'include_private': True,
- 'rows': n,
- 'start': n * (page - 1),
- }
-
- if self.options.dataset_id:
-
- search_data_dict['q'] = ' OR '.join(
- ['id:{0} OR name:"{0}"'.format(dataset_id)
- for dataset_id in self.options.dataset_id]
- )
-
- elif self.options.search_params:
-
- self._update_search_params(search_data_dict)
-
- elif not self.options.no_default_filters:
-
- self._add_default_filters(search_data_dict, view_types)
-
- if not search_data_dict.get('q'):
- search_data_dict['q'] = '*:*'
-
- query = p.toolkit.get_action('package_search')(
- {}, search_data_dict)
-
- return query
-
- def create_views(self, view_plugin_types=[]):
-
- from ckan.lib.datapreview import add_views_to_dataset_resources
-
- log = logging.getLogger(__name__)
-
- datastore_enabled = 'datastore' in config['ckan.plugins'].split()
-
- loaded_view_plugins = self._get_view_plugins(view_plugin_types,
- datastore_enabled)
-
- context = {'user': self.site_user['name']}
-
- page = 1
- while True:
- query = self._search_datasets(page, loaded_view_plugins)
-
- if page == 1 and query['count'] == 0:
- error('No datasets to create resource views on, exiting...')
-
- elif page == 1 and not self.options.assume_yes:
-
- msg = ('\nYou are about to check {0} datasets for the ' +
- 'following view plugins: {1}\n' +
- ' Do you want to continue?')
-
- confirm = query_yes_no(msg.format(query['count'],
- loaded_view_plugins))
-
- if confirm == 'no':
- error('Command aborted by user')
-
- if query['results']:
- for dataset_dict in query['results']:
-
- if not dataset_dict.get('resources'):
- continue
-
- views = add_views_to_dataset_resources(
- context,
- dataset_dict,
- view_types=loaded_view_plugins)
-
- if views:
- view_types = list({view['view_type']
- for view in views})
- msg = ('Added {0} view(s) of type(s) {1} to ' +
- 'resources from dataset {2}')
- log.debug(msg.format(len(views),
- ', '.join(view_types),
- dataset_dict['name']))
-
- if len(query['results']) < self._page_size:
- break
-
- page += 1
- else:
- break
-
- log.info('Done')
-
- def clear_views(self, view_plugin_types=[]):
-
- log = logging.getLogger(__name__)
-
- if not self.options.assume_yes:
- if view_plugin_types:
- msg = 'Are you sure you want to delete all resource views ' + \
- 'of type {0}?'.format(', '.join(view_plugin_types))
- else:
- msg = 'Are you sure you want to delete all resource views?'
-
- result = query_yes_no(msg, default='no')
-
- if result == 'no':
- error('Command aborted by user')
-
- context = {'user': self.site_user['name']}
- logic.get_action('resource_view_clear')(
- context, {'view_types': view_plugin_types})
-
- log.info('Done')
-
- def clean_views(self):
- names = []
- for plugin in p.PluginImplementations(p.IResourceView):
- names.append(str(plugin.info()['name']))
-
- results = model.ResourceView.get_count_not_in_view_types(names)
-
- if not results:
- print('No resource views to delete')
- return
-
- print('This command will delete.\n')
- for row in results:
- print('%s of type %s' % (row[1], row[0]))
-
- result = query_yes_no('Do you want to delete these resource views:', default='no')
-
- if result == 'no':
- print('Not Deleting.')
- return
-
- model.ResourceView.delete_not_in_view_types(names)
- model.Session.commit()
- print('Deleted resource views.')
-
-
-class ConfigToolCommand(paste.script.command.Command):
- '''Tool for editing options in a CKAN config file
-
- paster config-tool <default.ini> <key>=<value> [<key>=<value> ...]
- paster config-tool <default.ini> -f <custom_options.ini>
-
- Examples:
- paster config-tool default.ini sqlalchemy.url=123 'ckan.site_title=ABC'
- paster config-tool default.ini -s server:main -e port=8080
- paster config-tool default.ini -f custom_options.ini
- '''
- parser = paste.script.command.Command.standard_parser(verbose=True)
- default_verbosity = 1
- group_name = 'ckan'
- usage = __doc__
- summary = usage.split('\n')[0]
-
- parser.add_option('-s', '--section', dest='section',
- default='app:main', help='Section of the config file')
- parser.add_option(
- '-e', '--edit', action='store_true', dest='edit', default=False,
- help='Checks the option already exists in the config file')
- parser.add_option(
- '-f', '--file', dest='merge_filepath', metavar='FILE',
- help='Supply an options file to merge in')
-
- def command(self):
- from ckan.lib import config_tool
- if len(self.args) < 1:
- self.parser.error('Not enough arguments (got %i, need at least 1)'
- % len(self.args))
- config_filepath = self.args[0]
- if not os.path.exists(config_filepath):
- self.parser.error('Config filename %r does not exist.' %
- config_filepath)
- if self.options.merge_filepath:
- config_tool.config_edit_using_merge_file(
- config_filepath, self.options.merge_filepath)
- options = self.args[1:]
- if not (options or self.options.merge_filepath):
- self.parser.error('No options provided')
- if options:
- for option in options:
- if '=' not in option:
- error(
- 'An option does not have an equals sign: %r '
- 'It should be \'key=value\'. If there are spaces '
- 'you\'ll need to quote the option.\n' % option)
- try:
- config_tool.config_edit_using_option_strings(
- config_filepath, options, self.options.section,
- edit=self.options.edit)
- except config_tool.ConfigToolError as e:
- error(traceback.format_exc())
-
-
-class JobsCommand(CkanCommand):
- '''Manage background jobs
-
- Usage:
-
- paster jobs worker [--burst] [QUEUES]
-
- Start a worker that fetches jobs from queues and executes
- them. If no queue names are given then the worker listens
- to the default queue, this is equivalent to
-
- paster jobs worker default
-
- If queue names are given then the worker listens to those
- queues and only those:
-
- paster jobs worker my-custom-queue
-
- Hence, if you want the worker to listen to the default queue
- and some others then you must list the default queue explicitly:
-
- paster jobs worker default my-custom-queue
-
- If the `--burst` option is given then the worker will exit
- as soon as all its queues are empty.
-
- paster jobs list [QUEUES]
-
- List currently enqueued jobs from the given queues. If no queue
- names are given then the jobs from all queues are listed.
-
- paster jobs show ID
-
- Show details about a specific job.
-
- paster jobs cancel ID
-
- Cancel a specific job. Jobs can only be canceled while they are
- enqueued. Once a worker has started executing a job it cannot
- be aborted anymore.
-
- paster jobs clear [QUEUES]
-
- Cancel all jobs on the given queues. If no queue names are
- given then ALL queues are cleared.
-
- paster jobs test [QUEUES]
-
- Enqueue a test job. If no queue names are given then the job is
- added to the default queue. If queue names are given then a
- separate test job is added to each of the queues.
- '''
-
- summary = __doc__.split(u'\n')[0]
- usage = __doc__
- min_args = 0
-
-
- def __init__(self, *args, **kwargs):
- super(JobsCommand, self).__init__(*args, **kwargs)
- try:
- self.parser.add_option(u'--burst', action='store_true',
- default=False,
- help=u'Start worker in burst mode.')
- except OptionConflictError:
- # Option has already been added in previous call
- pass
-
- def command(self):
- self._load_config()
- try:
- cmd = self.args.pop(0)
- except IndexError:
- print(self.__doc__)
- sys.exit(0)
- if cmd == u'worker':
- self.worker()
- elif cmd == u'list':
- self.list()
- elif cmd == u'show':
- self.show()
- elif cmd == u'cancel':
- self.cancel()
- elif cmd == u'clear':
- self.clear()
- elif cmd == u'test':
- self.test()
- else:
- error(u'Unknown command "{}"'.format(cmd))
-
- def worker(self):
- from ckan.lib.jobs import Worker
- Worker(self.args).work(burst=self.options.burst)
-
- def list(self):
- data_dict = {
- u'queues': self.args,
- }
- jobs = p.toolkit.get_action(u'job_list')({}, data_dict)
- for job in jobs:
- if job[u'title'] is None:
- job[u'title'] = ''
- else:
- job[u'title'] = u'"{}"'.format(job[u'title'])
- print(u'{created} {id} {queue} {title}'.format(**job))
-
- def show(self):
- if not self.args:
- error(u'You must specify a job ID')
- id = self.args[0]
- try:
- job = p.toolkit.get_action(u'job_show')({}, {u'id': id})
- except logic.NotFound:
- error(u'There is no job with ID "{}"'.format(id))
- print(u'ID: {}'.format(job[u'id']))
- if job[u'title'] is None:
- title = u'None'
- else:
- title = u'"{}"'.format(job[u'title'])
- print(u'Title: {}'.format(title))
- print(u'Created: {}'.format(job[u'created']))
- print(u'Queue: {}'.format(job[u'queue']))
-
- def cancel(self):
- if not self.args:
- error(u'You must specify a job ID')
- id = self.args[0]
- try:
- p.toolkit.get_action(u'job_cancel')({}, {u'id': id})
- except logic.NotFound:
- error(u'There is no job with ID "{}"'.format(id))
- print(u'Cancelled job {}'.format(id))
-
- def clear(self):
- data_dict = {
- u'queues': self.args,
- }
- queues = p.toolkit.get_action(u'job_clear')({}, data_dict)
- queues = (u'"{}"'.format(q) for q in queues)
- print(u'Cleared queue(s) {}'.format(u', '.join(queues)))
-
- def test(self):
- from ckan.lib.jobs import DEFAULT_QUEUE_NAME, enqueue, test_job
- for queue in (self.args or [DEFAULT_QUEUE_NAME]):
- job = enqueue(test_job, [u'A test job'], title=u'A test job', queue=queue)
- print(u'Added test job {} to queue "{}"'.format(job.id, queue))
diff --git a/ckanext/datastore/commands.py b/ckanext/datastore/commands.py
--- a/ckanext/datastore/commands.py
+++ b/ckanext/datastore/commands.py
@@ -7,7 +7,7 @@
_parse_db_config,
paster_click_group,
)
-from ckan.lib.cli.cli import click_config_option
+from ckan.cli.cli import click_config_option
from ckanext.datastore.backend.postgres import identifier
from ckanext.datastore.blueprint import DUMP_FORMATS, dump_to
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -51,29 +51,8 @@ def parse_version(s):
'main = ckan.config.install:CKANInstaller',
],
'paste.paster_command': [
- 'db = ckan.lib.cli:ManageDb',
- 'create-test-data = ckan.lib.cli:CreateTestDataCommand',
- 'sysadmin = ckan.lib.cli:Sysadmin',
- 'user = ckan.lib.cli:UserCmd',
- 'dataset = ckan.lib.cli:DatasetCmd',
- 'search-index = ckan.lib.cli:SearchIndexCommand',
- 'ratings = ckan.lib.cli:Ratings',
- 'notify = ckan.lib.cli:Notification',
- 'rdf-export = ckan.lib.cli:RDFExport',
- 'tracking = ckan.lib.cli:Tracking',
- 'plugin-info = ckan.lib.cli:PluginInfo',
- 'profile = ckan.lib.cli:Profile',
- 'color = ckan.lib.cli:CreateColorSchemeCommand',
- 'check-po-files = ckan.i18n.check_po_files:CheckPoFiles',
- 'trans = ckan.lib.cli:TranslationsCommand',
- 'minify = ckan.lib.cli:MinifyCommand',
- 'less = ckan.lib.cli:LessCommand',
'datastore = ckanext.datastore.commands:datastore_group',
'datapusher = ckanext.datapusher.cli:DatapusherCommand',
- 'front-end-build = ckan.lib.cli:FrontEndBuildCommand',
- 'views = ckan.lib.cli:ViewsCommand',
- 'config-tool = ckan.lib.cli:ConfigToolCommand',
- 'jobs = ckan.lib.cli:JobsCommand',
],
'console_scripts': [
'ckan = ckan.cli.cli:ckan',
| diff --git a/ckan/tests/cli/test_jobs.py b/ckan/tests/cli/test_jobs.py
--- a/ckan/tests/cli/test_jobs.py
+++ b/ckan/tests/cli/test_jobs.py
@@ -1,22 +1,36 @@
# -*- coding: utf-8 -*-
-import os
import datetime
+import os
+import os.path
import tempfile
-import ckan.lib.jobs as jobs
from ckan.cli.cli import ckan
-from ckan.tests.helpers import RQTestBase
+import ckan.lib.jobs as jobs
+import ckan.tests.helpers as helpers
+
+
+def test_unknown_command(cli):
+ """
+ Test error handling for unknown ``ckan jobs`` sub-command.
+ """
+ result = cli.invoke(ckan, [u"jobs", u"does-not-exist"])
+ assert result.exit_code != 0
+ assert u"No such command" in result.output
+
+class TestJobsList(helpers.RQTestBase):
+ """
+ Tests for ``ckan jobs list``.
+ """
-class TestJobShow(RQTestBase):
def test_list_default_queue(self, cli):
"""
Test output of ``jobs list`` for default queue.
"""
job = self.enqueue()
- result = cli.invoke(ckan, [u"jobs", u"list"])
- fields = result.output.split()
+ stdout = cli.invoke(ckan, [u"jobs", u"list"]).output
+ fields = stdout.split(u"\n")[-2].split()
assert len(fields) == 3
dt = datetime.datetime.strptime(fields[0], u"%Y-%m-%dT%H:%M:%S")
now = datetime.datetime.utcnow()
@@ -29,8 +43,8 @@ def test_list_other_queue(self, cli):
Test output of ``jobs.list`` for non-default queue.
"""
job = self.enqueue(queue=u"my_queue")
- result = cli.invoke(ckan, [u"jobs", u"list"])
- fields = result.output.split()
+ stdout = cli.invoke(ckan, [u"jobs", u"list"]).output
+ fields = stdout.split(u"\n")[-2].split()
assert len(fields) == 3
assert fields[2] == u"my_queue"
@@ -39,8 +53,8 @@ def test_list_title(self, cli):
Test title output of ``jobs list``.
"""
job = self.enqueue(title=u"My_Title")
- result = cli.invoke(ckan, [u"jobs", u"list"])
- fields = result.output.split()
+ stdout = cli.invoke(ckan, [u"jobs", u"list"]).output
+ fields = stdout.split(u"\n")[-2].split()
assert len(fields) == 4
assert fields[3] == u'"My_Title"'
@@ -51,15 +65,15 @@ def test_list_filter(self, cli):
job1 = self.enqueue(queue=u"q1")
job2 = self.enqueue(queue=u"q2")
job3 = self.enqueue(queue=u"q3")
- result = cli.invoke(ckan, [u"jobs", u"list", u"q1", u"q2"])
- assert u"q1" in result.output
- assert u"q2" in result.output
- assert u"q3" not in result.output
+ stdout = cli.invoke(ckan, [u"jobs", u"list", u"q1", u"q2"]).output
+ assert u"q1" in stdout
+ assert u"q2" in stdout
+ assert u"q3" not in stdout
-class TestJobShow(RQTestBase):
+class TestJobShow(helpers.RQTestBase):
"""
- Tests for ``paster jobs show``.
+ Tests for ``ckan jobs show``.
"""
def test_show_existing(self, cli):
@@ -67,21 +81,22 @@ def test_show_existing(self, cli):
Test ``jobs show`` for an existing job.
"""
job = self.enqueue(queue=u"my_queue", title=u"My Title")
- result = cli.invoke(ckan, [u"jobs", u"show", job.id])
- assert job.id in result.output
- assert jobs.remove_queue_name_prefix(job.origin) in result.output
+ output = cli.invoke(ckan, [u"jobs", u"show", job.id]).output
+ assert job.id in output
+ assert jobs.remove_queue_name_prefix(job.origin) in output
def test_show_missing_id(self, cli):
"""
Test ``jobs show`` with a missing ID.
"""
result = cli.invoke(ckan, [u"jobs", u"show"])
- assert result.exit_code
+ assert result.exit_code != 0
+ assert u'Error: Missing argument "id".' in result.output
-class TestJobsCancel(RQTestBase):
+class TestJobsCancel(helpers.RQTestBase):
"""
- Tests for ``paster jobs cancel``.
+ Tests for ``ckan jobs cancel``.
"""
def test_cancel_existing(self, cli):
@@ -90,18 +105,19 @@ def test_cancel_existing(self, cli):
"""
job1 = self.enqueue()
job2 = self.enqueue()
- result = cli.invoke(ckan, [u"jobs", u"cancel", job1.id])
+ stdout = cli.invoke(ckan, [u"jobs", u"cancel", job1.id]).output
all_jobs = self.all_jobs()
assert len(all_jobs) == 1
assert all_jobs[0].id == job2.id
- assert job1.id in result.output
+ assert job1.id in stdout
def test_cancel_not_existing(self, cli):
"""
Test ``jobs cancel`` for a not existing job.
"""
result = cli.invoke(ckan, [u"jobs", u"cancel", u"does-not-exist"])
- assert result.exit_code
+ # FIXME: after https://github.com/ckan/ckan/issues/5158
+ # assert result.exit_code != 0
assert u"does-not-exist" in result.output
def test_cancel_missing_id(self, cli):
@@ -109,12 +125,13 @@ def test_cancel_missing_id(self, cli):
Test ``jobs cancel`` with a missing ID.
"""
result = cli.invoke(ckan, [u"jobs", u"cancel"])
- assert result.exit_code
+ assert result.exit_code != 0
+ assert u'Error: Missing argument "id".' in result.output
-class TestJobsClear(RQTestBase):
+class TestJobsClear(helpers.RQTestBase):
"""
- Tests for ``paster jobs clear``.
+ Tests for ``ckan jobs clear``.
"""
def test_clear_all_queues(self, cli):
@@ -125,10 +142,10 @@ def test_clear_all_queues(self, cli):
self.enqueue()
self.enqueue(queue=u"q1")
self.enqueue(queue=u"q2")
- result = cli.invoke(ckan, [u"jobs", u"clear"])
- assert jobs.DEFAULT_QUEUE_NAME in result.output
- assert u"q1" in result.output
- assert u"q2" in result.output
+ stdout = cli.invoke(ckan, [u"jobs", u"clear"]).output
+ assert jobs.DEFAULT_QUEUE_NAME in stdout
+ assert u"q1" in stdout
+ assert u"q2" in stdout
assert self.all_jobs() == []
def test_clear_specific_queues(self, cli):
@@ -140,25 +157,25 @@ def test_clear_specific_queues(self, cli):
self.enqueue(queue=u"q2")
self.enqueue(queue=u"q2")
self.enqueue(queue=u"q3")
- result = cli.invoke(ckan, [u"jobs", u"clear", u"q2", u"q3"])
- assert u"q2" in result.output
- assert u"q3" in result.output
- assert jobs.DEFAULT_QUEUE_NAME not in result.output
- assert u"q1" not in result.output
+ stdout = cli.invoke(ckan, [u"jobs", u"clear", u"q2", u"q3"]).output
+ assert u"q2" in stdout
+ assert u"q3" in stdout
+ assert jobs.DEFAULT_QUEUE_NAME not in stdout
+ assert u"q1" not in stdout
all_jobs = self.all_jobs()
assert set(all_jobs) == {job1, job2}
-class TestJobsTest(RQTestBase):
+class TestJobsTest(helpers.RQTestBase):
"""
- Tests for ``paster jobs test``.
+ Tests for ``ckan jobs test``.
"""
def test_test_default_queue(self, cli):
"""
Test ``jobs test`` for the default queue.
"""
- cli.invoke(ckan, [u"jobs", u"test"])
+ stdout = cli.invoke(ckan, [u"jobs", u"test"]).output
all_jobs = self.all_jobs()
assert len(all_jobs) == 1
assert (
@@ -170,8 +187,7 @@ def test_test_specific_queues(self, cli):
"""
Test ``jobs test`` for specific queues.
"""
-
- cli.invoke(ckan, [u"jobs", u"test", u"q1", u"q2"])
+ stdout = cli.invoke(ckan, [u"jobs", u"test", u"q1", u"q2"]).output
all_jobs = self.all_jobs()
assert len(all_jobs) == 2
assert {jobs.remove_queue_name_prefix(j.origin) for j in all_jobs} == {
@@ -180,9 +196,9 @@ def test_test_specific_queues(self, cli):
}
-class TestJobsWorker(RQTestBase):
+class TestJobsWorker(helpers.RQTestBase):
"""
- Tests for ``paster jobs worker``.
+ Tests for ``ckan jobs worker``.
"""
# All tests of ``jobs worker`` must use the ``--burst`` option to
diff --git a/ckan/tests/cli/test_user.py b/ckan/tests/cli/test_user.py
--- a/ckan/tests/cli/test_user.py
+++ b/ckan/tests/cli/test_user.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
import pytest
+
from ckan.cli.cli import ckan
@@ -19,7 +20,8 @@ def test_cli_user_add_valid_args(self, cli):
u"[email protected]",
]
result = cli.invoke(ckan, args)
- assert not result.exit_code
+
+ assert result.exit_code == 0
def test_cli_user_add_no_args(self, cli):
"""Command with no args raises SystemExit.
| Remove old paster CLI commands
Once #5108 and #5109 are done we can remove the old paster commands in `ckan/lib/cli.py`.
At least for CKAN 2.9 let's remove the actual commands only and keep the `CkanCommand` class as this is present in the toolkit and needed by extensions to implement paster-based commands. Also utilities like `load_config` as they might be imported from extensions.
There's is some click-based stuff in there which I don't know if it's still relevant (`click_config_option`, `paster_click_group`...). If no longer needed it can be removed.
| I would like to take this one.
@EvgeniiaVak great! Let us know if you need any pointers
@amercader
Yes, some pointers would be helpful. Although I don't know what exactly to ask for. As I understand, there was paster, that was used for everything, now flask is used for creating the server, click - for cli commands.
I can also wait for https://github.com/ckan/ckan/issues/5109 and continue to lean how ckan in general works in the mean time.
I hope this feature is not very urgent, because I don't think I can complete it very soon.
@EvgeniiaVak not a problem and sorry for not coming back to you sooner.
The old paster commands are defined in `ckan/lib/cli.py`. Their new equivalents are written in Click and located in `ckan/cli/cli.py`.
The next version of CKAN will only use the new Click based CLI so we want to remove as much as possible from the old paster ones to avoid confusion. But we can't delete the whole ckan/lib/cli.py module because extensions rely on some classes and methods from that module to write their own commands, and we want to give them time to migrate.
So here's how we could approach it:
- [ ] Remove all `XYZCommand` classes from ckan/lib/cli.py, except the main `CkanCommand` one.
- [ ] Keep the `load_config` and `query_yes_no` methods as these are used by extensions, all the rest of methods and unused imports can be removed
- [ ] Check that the new CLI works fine (`ckan -h`) and that the old CLI still works on a command provided by an extension, eg from ckanext-harvest `paster --plugin=ckanext-harvest harvester sources -c /path/to/ini` (it can be any command from any extension)
Let me know if this helps
@amercader
Yes, this clarifies things very much, thank you! | 2020-03-06T16:19:00 |
ckan/ckan | 5,281 | ckan__ckan-5281 | [
"4925",
"4925"
] | 78b37bd9e95500daf9176d2c9b1d375392a5f170 | diff --git a/ckanext/datapusher/logic/action.py b/ckanext/datapusher/logic/action.py
--- a/ckanext/datapusher/logic/action.py
+++ b/ckanext/datapusher/logic/action.py
@@ -61,13 +61,13 @@ def datapusher_submit(context, data_dict):
datapusher_url = config.get('ckan.datapusher.url')
- site_url = h.url_for('/', qualified=True)
-
callback_url_base = config.get('ckan.datapusher.callback_url_base')
if callback_url_base:
+ site_url = callback_url_base
callback_url = urljoin(
callback_url_base.rstrip('/'), '/api/3/action/datapusher_hook')
else:
+ site_url = h.url_for('/', qualified=True)
callback_url = h.url_for(
'/api/3/action/datapusher_hook', qualified=True)
| datapusher and ckan in docker-compose
CKAN Version 2.8.3
I've been following the changes in #4879 as I have the same problem running datapusher and ckan both in docker-compose cluster where the public ckan url is not available.
When running datapusher in a docker cluster generated by docker-compose the public ckan site url is not available to the local datapusher server - neither is it localhost. So we need to give the datapusher the correct callback url to update ckan.
Currently it always uses the site url and this fails to update.
datapusher is still using the site_url instead of the url set by
CKAN_DATAPUSHER_URL=http://datapusher:8800
CKAN__DATAPUSHER__CALLBACK_URL_BASE=http://ckan:5000
which is the internal docker-compose name (and works)
Error log is
datapusher | --------------------------------------------------------------------------------
datapusher | ERROR in scheduler [/usr/lib/python2.7/site-packages/apscheduler/scheduler.py:520]:
datapusher | Job "push_to_datastore (trigger: RunTriggerNow, run = True, next run at: None)" raised an exception
datapusher | --------------------------------------------------------------------------------
datapusher | ConnectionError: HTTPConnectionPool(host='ckan.dev.pfr.co.nz', port=5000): Max retries exceeded with url: /api/3/action/resource_show (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7feb6b45f5d0>: Failed to establish a new connection: [Errno 113] Host is unreachable',))
CKAN__DATAPUSHER__CALLBACK_URL_BASE is read into the system in
**Action.py datapusher_submit**
datapusher_url = config.get('ckan.datapusher.url')
callback_url_base = config.get('ckan.datapusher.callback_url_base')
if callback_url_base:
callback_url = urlparse.urljoin(
callback_url_base.rstrip('/'), '/api/3/action/datapusher_hook')
else:
callback_url = h.url_for(
'/api/3/action/datapusher_hook', qualified=True)
So assuming the config is read correctly callback_url_base = http://ckan:5000
and thus callback_url = http://ckan:5000/api/3/action/datapusher_hook
Adding log statements we get
ckan | 2019-07-25 11:46:02,882 INFO [ckanext.datapusher.logic.action] http://ckan:5000
ckan | 2019-07-25 11:46:02,882 INFO [ckanext.datapusher.logic.action] http://ckan:5000/api/3/action/datapusher_hook
confirming value of callback_url
Next a POST request is generated to the datapusher with a body
data=json.dumps({
'api_key': user['apikey'],
'job_type': 'push_to_datastore',
'result_url': callback_url,
'metadata': {
'ignore_hash': data_dict.get('ignore_hash', False),
'ckan_url': site_url,
'resource_id': res_id,
'set_url_type': data_dict.get('set_url_type', False),
'task_created': task['last_updated'],
'original_url': resource_dict.get('url'),
}
}))
Note that result_url = callback_url and ckan_url = site_url which is ckan.dev.pfr.co.nz:5000
This body is then processed in the datapusher service
**jobs.py - push_to_datastore**
These values are pulled from the input body
data = input['metadata']
ckan_url = data['ckan_url']
resource_id = data['resource_id']
api_key = input.get('api_key')
so ckan_url is still http://ckan.dev.pfr.co.nz:5000 and not http://ckan:5000
Where is the value of 'callback_url' read or used?
as far as I can see 'result_url' is never used. ckan_url is used exclusively.
Is there a different version of datapusher I should be using that makes use of the callback_url or has this bit not been done yet?
Thanks Andrew
datapusher and ckan in docker-compose
CKAN Version 2.8.3
I've been following the changes in #4879 as I have the same problem running datapusher and ckan both in docker-compose cluster where the public ckan url is not available.
When running datapusher in a docker cluster generated by docker-compose the public ckan site url is not available to the local datapusher server - neither is it localhost. So we need to give the datapusher the correct callback url to update ckan.
Currently it always uses the site url and this fails to update.
datapusher is still using the site_url instead of the url set by
CKAN_DATAPUSHER_URL=http://datapusher:8800
CKAN__DATAPUSHER__CALLBACK_URL_BASE=http://ckan:5000
which is the internal docker-compose name (and works)
Error log is
datapusher | --------------------------------------------------------------------------------
datapusher | ERROR in scheduler [/usr/lib/python2.7/site-packages/apscheduler/scheduler.py:520]:
datapusher | Job "push_to_datastore (trigger: RunTriggerNow, run = True, next run at: None)" raised an exception
datapusher | --------------------------------------------------------------------------------
datapusher | ConnectionError: HTTPConnectionPool(host='ckan.dev.pfr.co.nz', port=5000): Max retries exceeded with url: /api/3/action/resource_show (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7feb6b45f5d0>: Failed to establish a new connection: [Errno 113] Host is unreachable',))
CKAN__DATAPUSHER__CALLBACK_URL_BASE is read into the system in
**Action.py datapusher_submit**
datapusher_url = config.get('ckan.datapusher.url')
callback_url_base = config.get('ckan.datapusher.callback_url_base')
if callback_url_base:
callback_url = urlparse.urljoin(
callback_url_base.rstrip('/'), '/api/3/action/datapusher_hook')
else:
callback_url = h.url_for(
'/api/3/action/datapusher_hook', qualified=True)
So assuming the config is read correctly callback_url_base = http://ckan:5000
and thus callback_url = http://ckan:5000/api/3/action/datapusher_hook
Adding log statements we get
ckan | 2019-07-25 11:46:02,882 INFO [ckanext.datapusher.logic.action] http://ckan:5000
ckan | 2019-07-25 11:46:02,882 INFO [ckanext.datapusher.logic.action] http://ckan:5000/api/3/action/datapusher_hook
confirming value of callback_url
Next a POST request is generated to the datapusher with a body
data=json.dumps({
'api_key': user['apikey'],
'job_type': 'push_to_datastore',
'result_url': callback_url,
'metadata': {
'ignore_hash': data_dict.get('ignore_hash', False),
'ckan_url': site_url,
'resource_id': res_id,
'set_url_type': data_dict.get('set_url_type', False),
'task_created': task['last_updated'],
'original_url': resource_dict.get('url'),
}
}))
Note that result_url = callback_url and ckan_url = site_url which is ckan.dev.pfr.co.nz:5000
This body is then processed in the datapusher service
**jobs.py - push_to_datastore**
These values are pulled from the input body
data = input['metadata']
ckan_url = data['ckan_url']
resource_id = data['resource_id']
api_key = input.get('api_key')
so ckan_url is still http://ckan.dev.pfr.co.nz:5000 and not http://ckan:5000
Where is the value of 'callback_url' read or used?
as far as I can see 'result_url' is never used. ckan_url is used exclusively.
Is there a different version of datapusher I should be using that makes use of the callback_url or has this bit not been done yet?
Thanks Andrew
| Hi,
Facing the same issue here. Tried to fix it but got stuck.
Replacing `'ckan_url': site_url`, in ckanext/datapusher/logic/action.py with `ckan_url': callback_url_base` does not work as `callback_url_base = config.get('ckan.datapusher.callback_url_base')` assigns None.
Fixed it by adding `'ckan.datapusher.callback_url_base': 'CKAN__DATAPUSHER__CALLBACK_URL_BASE'` at line 157 in in ckan/config/environment.py
However in datapusher repo
File: datapusher/jobs.py
Method: push_to_datastore
```
try:
resource = get_resource(resource_id, ckan_url, api_key)
except util.JobError, e:
#try again in 5 seconds just incase CKAN is slow at adding resource
time.sleep(5)
resource = get_resource(resource_id, ckan_url, api_key)
# check if the resource url_type is a datastore
if resource.get('url_type') == 'datastore':
logger.info('Dump files are managed with the Datastore API')
return
# check scheme
url = resource.get('url')
scheme = urlparse.urlsplit(url).scheme
```
`url = resource.get('url')` is called for pushing which still contains the site_url. Not sure about this fix.
Just noting for myself that until this is fixed I have to set the expected ckan ip in /etc/hosts/ of the datapusher container
Hi,
Facing the same issue here. Tried to fix it but got stuck.
Replacing `'ckan_url': site_url`, in ckanext/datapusher/logic/action.py with `ckan_url': callback_url_base` does not work as `callback_url_base = config.get('ckan.datapusher.callback_url_base')` assigns None.
Fixed it by adding `'ckan.datapusher.callback_url_base': 'CKAN__DATAPUSHER__CALLBACK_URL_BASE'` at line 157 in in ckan/config/environment.py
However in datapusher repo
File: datapusher/jobs.py
Method: push_to_datastore
```
try:
resource = get_resource(resource_id, ckan_url, api_key)
except util.JobError, e:
#try again in 5 seconds just incase CKAN is slow at adding resource
time.sleep(5)
resource = get_resource(resource_id, ckan_url, api_key)
# check if the resource url_type is a datastore
if resource.get('url_type') == 'datastore':
logger.info('Dump files are managed with the Datastore API')
return
# check scheme
url = resource.get('url')
scheme = urlparse.urlsplit(url).scheme
```
`url = resource.get('url')` is called for pushing which still contains the site_url. Not sure about this fix.
Just noting for myself that until this is fixed I have to set the expected ckan ip in /etc/hosts/ of the datapusher container | 2020-03-13T23:17:00 |
|
ckan/ckan | 5,301 | ckan__ckan-5301 | [
"5253"
] | 17e08465367f1452fd32da950ced045ca136c78e | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -134,10 +134,28 @@ def make_flask_stack(conf):
raise RuntimeError(u'You must provide a value for the secret key'
' with the SECRET_KEY config option')
+ root_path = config.get('ckan.root_path', None)
if debug:
from flask_debugtoolbar import DebugToolbarExtension
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
- DebugToolbarExtension(app)
+ debug_ext = DebugToolbarExtension()
+
+ # register path that includes `ckan.site_root` before
+ # initializing debug app. In such a way, our route receives
+ # higher precedence.
+
+ # TODO: After removal of Pylons code, switch to
+ # `APPLICATION_ROOT` config value for flask application. Right
+ # now it's a bad option because we are handling both pylons
+ # and flask urls inside helpers and splitting this logic will
+ # bring us tons of headache.
+ if root_path:
+ app.add_url_rule(
+ root_path.replace('{{LANG}}', '').rstrip('/') +
+ '/_debug_toolbar/static/<path:filename>',
+ '_debug_toolbar.static', debug_ext.send_static_file
+ )
+ debug_ext.init_app(app)
from werkzeug.debug import DebuggedApplication
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
@@ -266,7 +284,7 @@ def ungettext_alias():
'bundle': True,
'rollup': fanstatic_enable_rollup,
}
- root_path = config.get('ckan.root_path', None)
+
if root_path:
root_path = re.sub('/{{LANG}}', '', root_path)
fanstatic_config['base_url'] = root_path
| diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py
--- a/ckan/tests/lib/test_helpers.py
+++ b/ckan/tests/lib/test_helpers.py
@@ -150,6 +150,16 @@ def test_url_for_with_root_path_locale_and_script_name_env(self, monkeypatch):
generated_url = h.url_for("dataset.read", id="my_dataset", locale="de")
assert generated_url == url
+ @pytest.mark.ckan_config("debug", True)
+ @pytest.mark.ckan_config("DEBUG", True) # Flask's internal debug flag
+ @pytest.mark.ckan_config("ckan.root_path", "/my/custom/path")
+ def test_debugtoolbar_url(self, ckan_config):
+ # test against built-in `url_for`, that is used by debugtoolbar ext.
+ from flask import url_for
+ expected = "/my/custom/path/_debug_toolbar/static/test.js"
+ url = url_for('_debug_toolbar.static', filename='test.js')
+ assert url == expected
+
class TestHelpersUrlForFlaskandPylons(BaseUrlFor):
def test_url_for_flask_route_new_syntax(self):
| Flask Debug toolbar does not show when CKAN is not in the root
### CKAN 2.8.3
### Please describe the expected behaviour
When debug mode is enabled (by setting [the _debug_ option](https://docs.ckan.org/en/2.8/maintaining/configuration.html#debug) to True), a "FDT" button should show in the right margin offering [Flask-DebugToolbar](https://pypi.org/project/Flask-DebugToolbar/).
### Please describe the actual behaviour
The FDT button does not show and several network errors occur. JavaScript files required by Flask-DebugToolbar fail to load with HTTP 404 errors, because their URL according to the HTML document is wrong.
### What steps can be taken to reproduce the issue?
1. Install CKAN below the root, for example in https://example.com/recherche/
1. Enable debugging (change the configuration file and restart Apache httpd)
1. Load a page, such as the home page
---
This occurs because the _static_path_ Jinja variable's value, which should be the path where Flask-DebugToolbar is, points too high. It lacks the site's base path. For example, on our site, instead of "/recherche/_debug_toolbar/static/", the value is just "/_debug_toolbar/static/" ("/recherche" is missing).
Flask-DebugToolbar defines _static_path_ in DebugToolbar.\_\_init\_\_(). To workaround, the base path can be hardcoded to prepend it to the value returned by url_for(), by changing flask_debugtoolbar/toolbar.py:20 to:
`'static_path': '/recherche' + url_for('_debug_toolbar.static', filename='')`
| Not particularly related to this bug, but just to prevent others from being confused...
The FDT does not show on all pages. It is supposed to show on the homepage for instance, but as of CKAN 2.8.3, there are still many pages which have not moved to Flask, where the FDT button simply is not supposed to show. | 2020-03-25T14:51:22 |
ckan/ckan | 5,314 | ckan__ckan-5314 | [
"3259"
] | fcb38ba903b2c2b51b8620bd24571b284a86a2d6 | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -251,7 +251,7 @@ def _group_or_org_list(context, data_dict, is_org=False):
data_dict, logic.schema.default_pagination_schema(), context)
if errors:
raise ValidationError(errors)
- sort = data_dict.get('sort') or 'title'
+ sort = data_dict.get('sort') or config.get('ckan.default_group_sort') or 'title'
q = data_dict.get('q')
all_fields = asbool(data_dict.get('all_fields', None))
@@ -358,7 +358,7 @@ def group_list(context, data_dict):
``'packages'`` (optional, default: ``'name'``) Deprecated use sort.
:type order_by: string
:param sort: sorting of the search results. Optional. Default:
- "name asc" string of field name and sort-order. The allowed fields are
+ "title asc" string of field name and sort-order. The allowed fields are
'name', 'package_count' and 'title'
:type sort: string
:param limit: the maximum number of groups returned (optional)
@@ -409,7 +409,7 @@ def organization_list(context, data_dict):
``'packages'`` (optional, default: ``'name'``) Deprecated use sort.
:type order_by: string
:param sort: sorting of the search results. Optional. Default:
- "name asc" string of field name and sort-order. The allowed fields are
+ "title asc" string of field name and sort-order. The allowed fields are
'name', 'package_count' and 'title'
:type sort: string
:param limit: the maximum number of organizations returned (optional)
@@ -1559,7 +1559,7 @@ def package_search(context, data_dict):
:param fq_list: additional filter queries to apply.
:type fq_list: list of strings
:param sort: sorting of the search results. Optional. Default:
- ``'relevance asc, metadata_modified desc'``. As per the solr
+ ``'score desc, metadata_modified desc'``. As per the solr
documentation, this is a comma-separated string of field names and
sort-orderings.
:type sort: string
@@ -1696,7 +1696,7 @@ def package_search(context, data_dict):
abort = data_dict.get('abort_search', False)
if data_dict.get('sort') in (None, 'rank'):
- data_dict['sort'] = 'score desc, metadata_modified desc'
+ data_dict['sort'] = config.get('ckan.search.default_package_sort') or 'score desc, metadata_modified desc'
results = []
if not abort:
| diff --git a/ckan/tests/logic/action/test_get.py b/ckan/tests/logic/action/test_get.py
--- a/ckan/tests/logic/action/test_get.py
+++ b/ckan/tests/logic/action/test_get.py
@@ -289,6 +289,29 @@ def test_group_list_sort_by_package_count_ascending(self):
assert group_list == ["bb", "aa"]
+ def test_group_list_sort_default(self):
+
+ factories.Group(name="zz", title="aa")
+ factories.Group(name="yy", title="bb")
+
+ group_list = helpers.call_action(
+ "group_list"
+ )
+
+ assert group_list == ['zz', 'yy']
+
+ @pytest.mark.ckan_config("ckan.default_group_sort", "name")
+ def test_group_list_sort_from_config(self):
+
+ factories.Group(name="zz", title="aa")
+ factories.Group(name="yy", title="bb")
+
+ group_list = helpers.call_action(
+ "group_list"
+ )
+
+ assert group_list == ['yy', 'zz']
+
def eq_expected(self, expected_dict, result_dict):
superfluous_keys = set(result_dict) - set(expected_dict)
assert not superfluous_keys, "Did not expect key: %s" % " ".join(
@@ -1342,6 +1365,19 @@ def test_sort(self):
result_names = [result["name"] for result in search_result["results"]]
assert result_names == [u"test2", u"test1", u"test0"]
+ @pytest.mark.ckan_config("ckan.search.default_package_sort", "metadata_created asc")
+ def test_sort_default_from_config(self):
+ factories.Dataset(name="test0")
+ factories.Dataset(name="test1")
+ factories.Dataset(name="test2")
+
+ search_result = helpers.call_action(
+ "package_search"
+ )
+
+ result_names = [result["name"] for result in search_result["results"]]
+ assert result_names == [u"test0", u"test1", u"test2"]
+
def test_package_search_on_resource_name(self):
"""
package_search() should allow searching on resource name field.
| Organizations are sorted by name instead of title.
### CKAN Version if known (or site URL)
2.5.2
### Please describe the expected behaviour
Organizations should be sorted by title since the title is the shown value in web interfaces.
### Please describe the actual behaviour
Organizations are sorted by name by default without any selected sorting and in the sorting dropdown.
### What steps can be taken to reproduce the issue?
Create or modify organizations so that its title starts with different letter than its name. Open Organizations list and the organization is in position which does not make sense with the shown data.
| @amercader, I can take a look at it.
@amercader , PR is ready for this issue, its quite straightforward.
Hi @amercader , can this update be backported to CKAN 2.5 and CKAN 2.6.
Sorting by title is so embarrassing for multi-byte languages. We Japanese use MB characters for title and name is alphabetic only. MB characters are sorted with its character codes that is totally not associated with semantics nor pronunciation. So we have to control display order with tweaking group and organization names. In Addition, API specification says default is "name asc". I personally think it should be returned back to "name asc". (I found this problem when updating from 2.5) | 2020-03-29T13:14:44 |
ckan/ckan | 5,342 | ckan__ckan-5342 | [
"5323"
] | c03ab1e2c158eb8ad7d43084b031ec7e82bab6a9 | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -704,7 +704,9 @@ def user_list(context, data_dict):
string (optional) (you must be a sysadmin to use this filter)
:type email: string
:param order_by: which field to sort the list by (optional, default:
- ``'name'``). Can be any user field.
+ ``'display_name'``). Users can be sorted by ``'id'``, ``'name'``,
+ ``'fullname'``, ``'display_name'``, ``'created'``, ``'about'``,
+ ``'sysadmin'`` or ``'number_created_packages'``.
:type order_by: string
:param all_fields: return full user dictionaries instead of just names.
(optional, default: ``True``)
@@ -721,7 +723,7 @@ def user_list(context, data_dict):
q = data_dict.get('q', '')
email = data_dict.get('email')
- order_by = data_dict.get('order_by', 'name')
+ order_by = data_dict.get('order_by', 'display_name')
all_fields = asbool(data_dict.get('all_fields', True))
if all_fields:
@@ -747,14 +749,31 @@ def user_list(context, data_dict):
if email:
query = query.filter_by(email=email)
+ order_by_field = None
if order_by == 'edits':
raise ValidationError('order_by=edits is no longer supported')
- query = query.order_by(
- _case([(
- _or_(model.User.fullname == None,
- model.User.fullname == ''),
- model.User.name)],
- else_=model.User.fullname))
+ elif order_by == 'number_created_packages':
+ order_by_field = order_by
+ elif order_by != 'display_name':
+ try:
+ order_by_field = getattr(model.User, order_by)
+ except AttributeError:
+ pass
+ if order_by == 'display_name' or order_by_field is None:
+ query = query.order_by(
+ _case(
+ [(
+ _or_(
+ model.User.fullname == None,
+ model.User.fullname == ''
+ ),
+ model.User.name
+ )],
+ else_=model.User.fullname
+ )
+ )
+ else:
+ query = query.order_by(order_by_field)
# Filter deleted users
query = query.filter(model.User.state != model.State.DELETED)
| diff --git a/ckan/tests/logic/action/test_get.py b/ckan/tests/logic/action/test_get.py
--- a/ckan/tests/logic/action/test_get.py
+++ b/ckan/tests/logic/action/test_get.py
@@ -907,6 +907,87 @@ def test_user_list_filtered_by_email(self):
got_user = got_users[0]
assert got_user == user_a["name"]
+ def test_user_list_order_by_default(self):
+ default_user = helpers.call_action('get_site_user', ignore_auth=True)
+
+ users = [
+ factories.User(fullname="Xander Bird", name="bird_x"),
+ factories.User(fullname="Max Hankins", name="hankins_m"),
+ factories.User(fullname="", name="morgan_w"),
+ factories.User(fullname="Kathy Tillman", name="tillman_k"),
+ ]
+ expected_names = [
+ u['name'] for u in [
+ users[3], # Kathy Tillman
+ users[1], # Max Hankins
+ users[2], # morgan_w
+ users[0], # Xander Bird
+ ]
+ ]
+
+ got_users = helpers.call_action('user_list')
+ got_names = [
+ u['name'] for u in got_users if u['name'] != default_user['name']
+ ]
+
+ assert got_names == expected_names
+
+ def test_user_list_order_by_fullname_only(self):
+ default_user = helpers.call_action('get_site_user', ignore_auth=True)
+
+ users = [
+ factories.User(fullname="Xander Bird", name="bird_x"),
+ factories.User(fullname="Max Hankins", name="hankins_m"),
+ factories.User(fullname="", name="morgan_w"),
+ factories.User(fullname="Kathy Tillman", name="tillman_k"),
+ ]
+ expected_fullnames = sorted([u['fullname'] for u in users])
+
+ got_users = helpers.call_action('user_list', order_by='fullname')
+ got_fullnames = [
+ u['fullname'] for u in got_users if u['name'] != default_user['name']
+ ]
+
+ assert got_fullnames == expected_fullnames
+
+ def test_user_list_order_by_created_datasets(self):
+ default_user = helpers.call_action('get_site_user', ignore_auth=True)
+
+ users = [
+ factories.User(fullname="Xander Bird", name="bird_x"),
+ factories.User(fullname="Max Hankins", name="hankins_m"),
+ factories.User(fullname="Kathy Tillman", name="tillman_k"),
+ ]
+ datasets = [
+ factories.Dataset(user=users[1]),
+ factories.Dataset(user=users[1])
+ ]
+ for dataset in datasets:
+ dataset["title"] = "Edited title"
+ helpers.call_action(
+ 'package_update', context={'user': users[1]['name']}, **dataset
+ )
+ expected_names = [
+ u['name'] for u in [
+ users[0], # 0 packages created
+ users[2], # 0 packages created
+ users[1], # 2 packages created
+ ]
+ ]
+
+ got_users = helpers.call_action(
+ 'user_list', order_by='number_created_packages'
+ )
+ got_names = [
+ u['name'] for u in got_users if u['name'] != default_user['name']
+ ]
+
+ assert got_names == expected_names
+
+ def test_user_list_order_by_edits(self):
+ with pytest.raises(logic.ValidationError):
+ helpers.call_action('user_list', order_by='edits')
+
@pytest.mark.usefixtures("clean_db", "with_request_context")
class TestUserShow(object):
| user_list action ignores order_by param
### CKAN Version if known (or site URL)
2.8
### Please describe the expected behaviour
```py
users = toolkit.get_action('user_list')(context, {
'order_by': 'number_created_packages'
})
```
sorts users by `number_created_packages`
### Please describe the actual behaviour
```py
users = toolkit.get_action('user_list')(context, {
'order_by': 'number_created_packages'
})
```
sorts users by name
### What steps can be taken to reproduce the issue?
see above
---
Bug is here:
https://github.com/ckan/ckan/blob/64774670b722ed1bd3808901137fa80753d3c772/ckan/logic/action/get.py#L750:L757
Related discussion: https://github.com/okfn/ckanext-unhcr/pull/268#discussion_r395679730
| 2020-04-14T14:02:30 |
|
ckan/ckan | 5,386 | ckan__ckan-5386 | [
"5385"
] | a379b8eaa02fc5dc2d331d494d1660d5cde4e08d | diff --git a/ckanext/datapusher/logic/action.py b/ckanext/datapusher/logic/action.py
--- a/ckanext/datapusher/logic/action.py
+++ b/ckanext/datapusher/logic/action.py
@@ -60,7 +60,7 @@ def datapusher_submit(context, data_dict):
datapusher_url = config.get('ckan.datapusher.url')
- site_url = 'http://ckan:5000'
+ site_url = h.url_for('/', qualified=True)
callback_url_base = config.get('ckan.datapusher.callback_url_base')
if callback_url_base:
| Datapusher requests failing in 2.7.7 when using uwsgi sockets
### CKAN Version if known (or site URL)
2.7.7
### Please describe the expected behaviour
Datapusher requests to ckan should succeed when using nginx proxy and uwsgi sockets on the ckan server
### Please describe the actual behaviour
Datapusher fails with an error in the UI, and uswgi error in the ckan container logs:
```
invalid request block size: 21327 (max 4096)...skip
```
### What steps can be taken to reproduce the issue?
Run ckan with datapusher, ckan running uwsgi with flags:
```
--protocol uwsgi --socket 0.0.0.0:5000
```
So this appears to have been introduced in https://github.com/ckan/ckan/commit/9a41f5a791bbc551959d3608103340ce545785c0
@amercader I'm confused as to why this url would be hardcoded like this? In our particular setup it almost works since we have our ckan container as a named route in the docker-compose file and we're running on port 5000, but since it bypasses the nginx proxy it is trying to talk http to uwsgi socket. Looking at the master branch it seems to be still in the same format as prior to your commit, `h.url_for('/', qualified=True)`.
| 2020-05-16T12:46:45 |
||
ckan/ckan | 5,406 | ckan__ckan-5406 | [
"4802"
] | 5153c52e2d245c35e3ef68cdd3a92d0606ba9220 | diff --git a/doc/conf.py b/doc/conf.py
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -50,6 +50,7 @@
.. |test_datastore| replace:: datastore_test
.. |apache_config_file| replace:: /etc/apache2/sites-available/ckan_default.conf
.. |apache.wsgi| replace:: |config_dir|/apache.wsgi
+.. |wsgi.py| replace:: |config_dir|/wsgi.py
.. |data_dir| replace:: |config_dir|/data
.. |sstore| replace:: |config_dir|/sstore
.. |storage_parent_dir| replace:: /var/lib/ckan
@@ -67,7 +68,8 @@
.. |javascript| replace:: JavaScript
.. |apache| replace:: Apache
.. |nginx_config_file| replace:: /etc/nginx/sites-available/ckan
-.. |restart_nginx| replace:: sudo systemctl restart nginx
+.. |reload_nginx| replace:: sudo service nginx reload
+.. |restart_nginx| replace:: sudo service nginx restart
.. |jquery| replace:: jQuery
.. |nodejs| replace:: Node.js
diff --git a/wsgi.py b/wsgi.py
new file mode 100644
--- /dev/null
+++ b/wsgi.py
@@ -0,0 +1,12 @@
+# -*- coding: utf-8 -*-
+
+import os
+from ckan.config.middleware import make_app
+from ckan.cli import CKANConfigLoader
+from logging.config import fileConfig as loggingFileConfig
+config_filepath = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), u'ckan.ini')
+abspath = os.path.join(os.path.dirname(os.path.abspath(__file__)))
+loggingFileConfig(config_filepath)
+config = CKANConfigLoader(config_filepath).get_config()
+application = make_app(config)
| Update the WSGI entrypoint to not use paste.deploy
TODO
paste.deploy loadapp
#### Approach
#### Story points
| We want to get rid of PasteDeploy's `loadapp` and instead use Werkzeug.
It looks like @JGulic has done this for the Profile command - https://github.com/ckan/ckan/pull/5244.
The heart of this ticket is to change the .wsgi file we use to deploy CKAN into production: https://github.com/ckan/ckan/blob/master/doc/maintaining/installing/deployment.rst#4-create-the-wsgi-script-file
A basic Werkzeug .wsgi is documented here: https://werkzeug.palletsprojects.com/en/1.0.x/deployment/mod_wsgi/#creating-a-wsgi-file
Our [make_app()](https://github.com/ckan/ckan/blob/master/ckan/config/middleware/__init__.py#L50) also needs a config parameter. So I guess we need to do: CKANConfigLoader(filename).get_config()
(whereas loadapp we just passed in the filename)
The existing apache.wsgi also configures logging:
```
from paste.script.util.logging_config import fileConfig
fileConfig(config_filepath)
```
We want to get rid of PasteScript in py3 requirements. Logging is not configured from the ini when running tests or the click cli, so this is a new thing to ckan. It looks the built-in python3 logging module has what we want: [logging.config.fileConfig](https://docs.python.org/3.5/library/logging.config.html#logging.config.fileConfig)
☝️ I wrote this with a bit of research - I'd appreciate @amercader or @smotornyuk checking this is right. And if it is then it should be easier for whoever gets there first to contribute a PR and test it out with Apache.
I will also be able to test the new (Werkzeug) .wsgi file with the new uWSGI and gunicorn "servers/entrypoints" as I have now finished these new configurations. They both work with the PasteDeploy loadapp file. I'm guessing Apache will still be around for CKAN 2.9 however I could add these 2 new configs to the CKAN 2.9 documentation. I guess we will be phasing out Apache completely by CKAN 3.0...
@kowh-ai I'm very happy to see https://github.com/ckan/ckan/issues/4991 progressing 👍
When we have a PR for this issue, it doesn't really matter which server it is tested against - I just said Apache as it was the current default - so I'm also very happy to see your offer of testing it 🙏 | 2020-05-24T12:14:19 |
|
ckan/ckan | 5,417 | ckan__ckan-5417 | [
"5416"
] | d0b504bce9985b4e3f083778b208f07277bc8c62 | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -1647,13 +1647,14 @@ def date_str_to_datetime(date_str):
# Extract seconds and microseconds
if len(time_tuple) >= 6:
- m = re.match(r'(?P<seconds>\d{2})(\.(?P<microseconds>\d{6}))?$',
+ m = re.match(r'(?P<seconds>\d{2})(\.(?P<microseconds>\d+))?$',
time_tuple[5])
if not m:
raise ValueError('Unable to parse %s as seconds.microseconds' %
time_tuple[5])
seconds = int(m.groupdict().get('seconds'))
- microseconds = int(m.groupdict(0).get('microseconds'))
+ microseconds = int((str(m.groupdict(0).get('microseconds')) +
+ '00000')[0:6])
time_tuple = time_tuple[:5] + [seconds, microseconds]
return datetime.datetime(*list(int(item) for item in time_tuple))
| diff --git a/ckan/tests/legacy/lib/test_helpers.py b/ckan/tests/legacy/lib/test_helpers.py
--- a/ckan/tests/legacy/lib/test_helpers.py
+++ b/ckan/tests/legacy/lib/test_helpers.py
@@ -52,8 +52,8 @@ def test_date_str_to_datetime_with_garbage_on_end(self):
h.date_str_to_datetime("2008-04-13T20:40:20foobar")
def test_date_str_to_datetime_with_ambiguous_microseconds(self):
- with pytest.raises(ValueError):
- h.date_str_to_datetime("2008-04-13T20:40:20.500")
+ res = h.date_str_to_datetime("2008-04-13T20:40:20.1234")
+ assert res == datetime.datetime(2008, 4, 13, 20, 40, 20, 123400)
def test_gravatar(self):
email = "[email protected]"
| Parsing dates with strict date formats
### Please describe the expected behaviour
When converting a date string to `datetime` , ckan accepts dates with either no decimal seconds or with full 6 decimal seconds as microseconds (e.g 30.374826 seconds).
However, some generated date strings may contain more or less than 6 digits, like milliseconds with 3 digits, that we still want to use by converting them to the 6 digit microseconds.
### Please describe the actual behaviour
The `date_str_to_datetime` helper function only parses dates that have 6 decimal seconds (for microseconds) or non. It is failing when a date string has less or more than 6 decimal seconds, like 3 for milliseconds.
### What steps can be taken to reproduce the issue?
In the `date_str_to_datetime` helper function, allow room to have more or less than 6 decimal seconds and then convert them into 6 digit microseconds.
| 2020-06-03T13:28:07 |
|
ckan/ckan | 5,439 | ckan__ckan-5439 | [
"5380"
] | d44cf12f2facf98d4f51202178f58bb1b1ba07d0 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -250,4 +250,8 @@ def parse_version(s):
'Programming Language :: Python :: 2 :: Only',
'Programming Language :: Python :: 2.7',
],
+ # this is used to fix an incompatiblity with readthedocs dependencies
+ extras_require={
+ "readthedocs": ["Jinja2>=2.3"],
+ }
)
| docs.ckan.org for 2.6, 2.7 and 2.8 haven't been updated since 2018
### Please describe the expected behaviour
https://docs.ckan.org/en/2.8/, https://docs.ckan.org/en/2.7/ and https://docs.ckan.org/en/2.6/ should have latest docs for each version.
### Please describe the actual behaviour
The docs are generated for 2.8.2, 2.7.5 and 2.6.7
| Yes, unfortunately our old Jinja2 versions conflict with the ones used by RTD: https://github.com/readthedocs/readthedocs.org/issues/6894
The problem is that because of the way we generate the docstrings we need a full install of CKAN. At the end of the linked issue there is a suggested library that would avoid that.
Related: https://github.com/ckan/ckan/issues/4892 | 2020-06-12T14:53:27 |
|
ckan/ckan | 5,440 | ckan__ckan-5440 | [
"5435"
] | c0927e90dec5bf30ce5509cc935ea67ca41b24f5 | diff --git a/ckan/lib/extract.py b/ckan/lib/extract.py
--- a/ckan/lib/extract.py
+++ b/ckan/lib/extract.py
@@ -1,15 +1,23 @@
# encoding: utf-8
from jinja2.ext import babel_extract
+from ckan.lib.jinja_extensions import _get_extensions
-# It's no longer needed but all the extensions are using this
-# function. Let's keep it, just in case we need to extract messages in
-# some special way in future
def extract_ckan(fileobj, *args, **kw):
+ extensions = [
+ ':'.join([ext.__module__, ext.__name__])
+ if isinstance(ext, type)
+ else ext
+ for ext in _get_extensions()
+ ]
if 'options' not in kw:
kw['options'] = {}
if 'trimmed' not in kw['options']:
kw['options']['trimmed'] = 'True'
+ if 'silent' not in kw['options']:
+ kw['options']['silent'] = 'False'
+ if 'extensions' not in kw['options']:
+ kw['options']['extensions'] = ','.join(extensions)
return babel_extract(fileobj, *args, **kw)
diff --git a/ckan/lib/jinja_extensions.py b/ckan/lib/jinja_extensions.py
--- a/ckan/lib/jinja_extensions.py
+++ b/ckan/lib/jinja_extensions.py
@@ -23,19 +23,23 @@
log = logging.getLogger(__name__)
+def _get_extensions():
+ return ['jinja2.ext.do', 'jinja2.ext.with_',
+ SnippetExtension,
+ CkanExtend,
+ CkanInternationalizationExtension,
+ LinkForExtension,
+ ResourceExtension,
+ UrlForStaticExtension,
+ UrlForExtension,
+ AssetExtension]
+
+
def get_jinja_env_options():
return dict(
loader=CkanFileSystemLoader(config['computed_template_paths']),
autoescape=True,
- extensions=['jinja2.ext.do', 'jinja2.ext.with_',
- SnippetExtension,
- CkanExtend,
- CkanInternationalizationExtension,
- LinkForExtension,
- ResourceExtension,
- UrlForStaticExtension,
- UrlForExtension,
- AssetExtension],
+ extensions=_get_extensions(),
)
| Message extraction ignores jinja extensions.
### CKAN Version if known (or site URL)
master
### Please describe the expected behaviour
All translations should be extracted to ckan.pot when running python setup.py extract_messages.
### Please describe the actual behaviour
Templates that use [link_for](https://github.com/ckan/ckan/blob/master/ckan/lib/jinja_extensions.py#L302) extension are ignored in the message extraction. This is apparent as [ckan.pot](https://github.com/ckan/ckan/blob/master/ckan/i18n/ckan.pot) doens't have translations from [request_reset.html](https://github.com/ckan/ckan/blob/master/ckan/templates/user/request_reset.html) which uses link_for tag. If the tag is removed from the template, messages are extracted correctly. This is likely regression from https://github.com/ckan/ckan/pull/5339 as 2.8 still extracts them.
### What steps can be taken to reproduce the issue?
Run python setup.py extract_messages
ckan.pot should have messages from request_reset.html but it doesn't.
| 2020-06-13T11:06:39 |
||
ckan/ckan | 5,444 | ckan__ckan-5444 | [
"5443"
] | c0927e90dec5bf30ce5509cc935ea67ca41b24f5 | diff --git a/ckan/lib/navl/dictization_functions.py b/ckan/lib/navl/dictization_functions.py
--- a/ckan/lib/navl/dictization_functions.py
+++ b/ckan/lib/navl/dictization_functions.py
@@ -410,24 +410,19 @@ def unflatten(data):
for flattend_key in sorted(data.keys(), key=flattened_order_key):
current_pos = unflattened
- if (len(flattend_key) > 1
- and not flattend_key[0] in convert_to_list
- and not flattend_key[0] in unflattened):
- convert_to_list.append(flattend_key[0])
-
for key in flattend_key[:-1]:
try:
current_pos = current_pos[key]
- except KeyError:
+ except IndexError:
new_pos = {}
+ current_pos.append(new_pos)
+ current_pos = new_pos
+ except KeyError:
+ new_pos = []
current_pos[key] = new_pos
current_pos = new_pos
current_pos[flattend_key[-1]] = data[flattend_key]
- for key in convert_to_list:
- unflattened[key] = [unflattened[key][s]
- for s in sorted(unflattened[key])]
-
return unflattened
| diff --git a/ckan/tests/legacy/lib/test_navl.py b/ckan/tests/legacy/lib/test_navl.py
--- a/ckan/tests/legacy/lib/test_navl.py
+++ b/ckan/tests/legacy/lib/test_navl.py
@@ -251,6 +251,27 @@ def test_flatten():
assert data == unflatten(flatten_dict(data))
+def test_flatten_deeper():
+ data = {
+ u"resources": [
+ {
+ u"subfields": [
+ {
+ u"test": u"hello",
+ },
+ ],
+ },
+ ],
+ }
+
+ assert flatten_dict(data) == {
+ ("resources", 0, u"subfields", 0, u"test"): u"hello",
+ }, pformat(flatten_dict(data))
+
+ assert data == unflatten(flatten_dict(data)), pformat(
+ unflatten(flatten_dict(data)))
+
+
def test_simple():
schema = {
"name": [not_empty],
| Make unflatten match flatten_dict > 1 level deep
### CKAN Version if known (or site URL)
all
### Please describe the expected behaviour
`unflatten(flatten_dict(x)) == x` for any `x` with more than 1 level of dict/list/dict nesting
### Please describe the actual behaviour
unflatten returns dict with numeric keys past one level instead of lists
### What steps can be taken to reproduce the issue?
see test in PR
| 2020-06-16T21:24:52 |
|
ckan/ckan | 5,449 | ckan__ckan-5449 | [
"5436"
] | 5153c52e2d245c35e3ef68cdd3a92d0606ba9220 | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -30,6 +30,7 @@
from ckan.lib import helpers
from ckan.lib import jinja_extensions
from ckan.lib import uploader
+from ckan.lib import i18n
from ckan.common import config, g, request, ungettext
from ckan.config.middleware.common_middleware import TrackingMiddleware
import ckan.lib.app_globals as app_globals
@@ -207,7 +208,11 @@ def ungettext_alias():
return dict(ungettext=ungettext)
# Babel
- pairs = [(os.path.join(root, u'i18n'), 'ckan')] + [
+ _ckan_i18n_dir = i18n.get_ckan_i18n_dir()
+
+ pairs = [
+ (_ckan_i18n_dir, u'ckan')
+ ] + [
(p.i18n_directory(), p.i18n_domain())
for p in PluginImplementations(ITranslation)
]
diff --git a/ckan/lib/i18n.py b/ckan/lib/i18n.py
--- a/ckan/lib/i18n.py
+++ b/ckan/lib/i18n.py
@@ -73,6 +73,15 @@
_JS_TRANSLATIONS_DIR = os.path.join(_CKAN_DIR, u'public', u'base', u'i18n')
+def get_ckan_i18n_dir():
+ path = config.get(
+ u'ckan.i18n_directory', os.path.join(_CKAN_DIR, u'i18n'))
+ if os.path.isdir(os.path.join(path, u'i18n')):
+ path = os.path.join(path, u'i18n')
+
+ return path
+
+
def get_locales_from_config():
''' despite the name of this function it gets the locales defined by
the config AND also the locals available subject to the config. '''
@@ -101,11 +110,7 @@ def _get_locales():
locale_order = config.get('ckan.locale_order', '').split()
locales = ['en']
- if config.get('ckan.i18n_directory'):
- i18n_path = os.path.join(config.get('ckan.i18n_directory'), 'i18n')
- else:
- i18n_path = os.path.dirname(ckan.i18n.__file__)
-
+ i18n_path = get_ckan_i18n_dir()
# For every file in the ckan i18n directory see if babel can understand
# the locale. If yes, add it to the available locales
for locale in os.listdir(i18n_path):
@@ -224,9 +229,11 @@ def _set_lang(lang):
sets the Pylons root path to desired i18n_directory.
This is needed as Pylons will only look for an i18n directory in
the application root.'''
- if config.get('ckan.i18n_directory'):
- fake_config = {'pylons.paths': {'root': config['ckan.i18n_directory']},
- 'pylons.package': config['pylons.package']}
+ i18n_dir = get_ckan_i18n_dir()
+ if i18n_dir:
+ fake_config = {'pylons.paths': {
+ 'root': os.path.dirname(i18n_dir.rstrip('/'))
+ }, 'pylons.package': config['pylons.package']}
pylons_i18n.set_lang(
lang, pylons_config=fake_config, class_=Translations)
else:
@@ -359,9 +366,7 @@ def build_js_translations():
strings that are actually used in JS files.
'''
log.debug(u'Generating JavaScript translations')
- ckan_i18n_dir = config.get(u'ckan.i18n_directory',
- os.path.join(_CKAN_DIR, u'i18n'))
-
+ ckan_i18n_dir = get_ckan_i18n_dir()
# Collect all language codes (an extension might add support for a
# language that isn't supported by CKAN core, yet).
langs = set()
| diff --git a/ckan/tests/lib/_i18n_dummy_es/i18n/es/LC_MESSAGES/ckan.mo b/ckan/tests/lib/_i18n_dummy_es/i18n/es/LC_MESSAGES/ckan.mo
new file mode 100644
Binary files /dev/null and b/ckan/tests/lib/_i18n_dummy_es/i18n/es/LC_MESSAGES/ckan.mo differ
diff --git a/ckan/tests/lib/_i18n_dummy_es/i18n/es/LC_MESSAGES/ckan.po b/ckan/tests/lib/_i18n_dummy_es/i18n/es/LC_MESSAGES/ckan.po
new file mode 100644
--- /dev/null
+++ b/ckan/tests/lib/_i18n_dummy_es/i18n/es/LC_MESSAGES/ckan.po
@@ -0,0 +1,36 @@
+# Translations template for ckan.
+# Copyright (C) 2020 ORGANIZATION
+# This file is distributed under the same license as the ckan project.
+# FIRST AUTHOR <EMAIL@ADDRESS>, 2020.
+#
+# Translators:
+# Mihai Pantazi <[email protected]>, 2018
+# Isabel M Ruiz Mellado <[email protected]>, 2018
+# David Portoles <[email protected]>, 2018
+# Adrià Mercader <[email protected]>, 2018
+#
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: ckan 2.8.4b0\n"
+"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
+"POT-Creation-Date: 2020-03-31 17:05+0200\n"
+"PO-Revision-Date: 2018-03-27 14:15+0000\n"
+"Last-Translator: Nobody\n"
+"Language-Team: Spanish (https://www.transifex.com/okfn/teams/11162/es/)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Language: es\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+"Generated-By: Babel 2.5.3\n"
+
+#: ckan/logic/converters.py:148 ckan/logic/validators.py:151
+#: ckan/logic/validators.py:193 ckan/templates/package/read_base.html:19
+#: ckan/tests/config/test_middleware.py:619
+#: ckanext/stats/templates/ckanext/stats/index.html:89
+msgid "Dataset"
+msgstr "Foo baz 123"
+
+msgid "Groups"
+msgstr "Bar Buz 321"
diff --git a/ckan/tests/lib/test_i18n.py b/ckan/tests/lib/test_i18n.py
--- a/ckan/tests/lib/test_i18n.py
+++ b/ckan/tests/lib/test_i18n.py
@@ -19,6 +19,7 @@
HERE = os.path.abspath(os.path.dirname(__file__))
I18N_DIR = os.path.join(HERE, u"_i18n_build_js_translations")
+I18N_DUMMY_DIR = os.path.join(HERE, u"_i18n_dummy_es")
class TestJSTranslationsPlugin(plugins.SingletonPlugin, DefaultTranslation):
@@ -153,3 +154,18 @@ def test_translation_works_on_flask_and_pylons(self, app):
resp = app.get(u"/es/pylons_translated")
assert six.ensure_text(resp.data) == six.text_type(u"Grupos")
+
+ @pytest.mark.ckan_config(u"ckan.i18n_directory", I18N_DUMMY_DIR)
+ def test_config_i18n_directory(self, app):
+ resp = app.get(u"/flask_translated")
+ assert six.ensure_text(resp.data) == six.text_type(u"Dataset")
+
+ resp = app.get(u"/es/flask_translated")
+ assert six.ensure_text(resp.data) == six.text_type(u"Foo baz 123")
+
+ if six.PY2:
+ resp = app.get(u"/pylons_translated")
+ assert six.ensure_text(resp.data) == six.text_type(u"Groups")
+
+ resp = app.get(u"/es/pylons_translated")
+ assert six.ensure_text(resp.data) == six.text_type(u"Bar Buz 321")
| i18n: add test of ckan.i18n_directory config option
I'm presenting this issue as a "pull request" to give me a more convenient way to illustrate my suspicions that the `ckan.i18n_directory` config option is broken on `master`.
What I think _should_ happen is the dummy `es` translation should override the real one and result in the dummy strings being produced, but I can't get it to have any effect on any of my systems.
Coming up: a similar test for 2.8, showing it passing for pylons views but not flask views.
| 2020-06-17T16:13:38 |
|
ckan/ckan | 5,453 | ckan__ckan-5453 | [
"5452"
] | 968c9f22c849aec7c36748822cd8d00604f4f392 | diff --git a/ckan/lib/dictization/model_save.py b/ckan/lib/dictization/model_save.py
--- a/ckan/lib/dictization/model_save.py
+++ b/ckan/lib/dictization/model_save.py
@@ -41,8 +41,6 @@ def resource_dict_save(res_dict, context):
new_extras = {}
has_changed = False
for key, value in six.iteritems(res_dict):
- if isinstance(value, list):
- continue
if key in ('extras', 'revision_timestamp', 'tracking_summary'):
continue
if key in fields:
diff --git a/ckan/logic/schema.py b/ckan/logic/schema.py
--- a/ckan/logic/schema.py
+++ b/ckan/logic/schema.py
@@ -29,7 +29,7 @@ def wrapper():
def default_resource_schema(
ignore_empty, unicode_safe, ignore, ignore_missing,
remove_whitespace, if_empty_guess_format, clean_format, isodate,
- int_validator, extras_unicode_convert, keep_extras):
+ int_validator, extras_valid_json, keep_extras):
return {
'id': [ignore_empty, unicode_safe],
'package_id': [ignore],
@@ -52,7 +52,7 @@ def default_resource_schema(
'cache_last_updated': [ignore_missing, isodate],
'tracking_summary': [ignore_missing],
'datastore_active': [ignore_missing],
- '__extras': [ignore_missing, extras_unicode_convert, keep_extras],
+ '__extras': [ignore_missing, extras_valid_json, keep_extras],
}
diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py
--- a/ckan/logic/validators.py
+++ b/ckan/logic/validators.py
@@ -9,7 +9,7 @@
import string
import json
-from six import string_types
+from six import string_types, iteritems
from six.moves.urllib.parse import urlparse
import ckan.lib.navl.dictization_functions as df
@@ -902,3 +902,13 @@ def json_object(value):
raise Invalid(_('Could not parse the value as a valid JSON object'))
return value
+
+
+def extras_valid_json(extras, context):
+ try:
+ for extra, value in iteritems(extras):
+ json.dumps(value)
+ except ValueError as e:
+ raise Invalid(_(u'Could not parse extra \'{name}\' as valid JSON').
+ format(name=extra))
+ return extras
| diff --git a/ckan/tests/logic/action/test_create.py b/ckan/tests/logic/action/test_create.py
--- a/ckan/tests/logic/action/test_create.py
+++ b/ckan/tests/logic/action/test_create.py
@@ -630,6 +630,8 @@ def test_extras(self):
package_id=dataset["id"],
somekey="somevalue", # this is how to do resource extras
extras={u"someotherkey": u"alt234"}, # this isnt
+ subobject={u'hello': u'there'}, # JSON objects supported
+ sublist=[1, 2, 3], # JSON lists suppoted
format=u"plain text",
url=u"http://datahub.io/download/",
)
@@ -637,12 +639,16 @@ def test_extras(self):
assert resource["somekey"] == "somevalue"
assert "extras" not in resource
assert "someotherkey" not in resource
+ assert resource["subobject"] == {u"hello": u"there"}
+ assert resource["sublist"] == [1, 2, 3]
resource = helpers.call_action("package_show", id=dataset["id"])[
"resources"
][0]
assert resource["somekey"] == "somevalue"
assert "extras" not in resource
assert "someotherkey" not in resource
+ assert resource["subobject"] == {u"hello": u"there"}
+ assert resource["sublist"] == [1, 2, 3]
@freeze_time('2020-02-25 12:00:00')
def test_metadata_modified_is_set_to_utcnow_when_created(self):
| lists not allowed as resource extras
### CKAN Version if known (or site URL)
all
### Please describe the expected behaviour
Resource extras are very liberal, almost any key may be used and complex nested JSON is supported as values natively.
### Please describe the actual behaviour
Resource extras with almost any JSON type are supported, but list values are silently removed .
### What steps can be taken to reproduce the issue?
Pass an extra with a list value to the `resource_create` API.
| 2020-06-18T22:53:53 |
|
ckan/ckan | 5,475 | ckan__ckan-5475 | [
"5472"
] | 9bc885a163c4cf064cfe30737516217f46913ce4 | diff --git a/ckan/lib/navl/dictization_functions.py b/ckan/lib/navl/dictization_functions.py
--- a/ckan/lib/navl/dictization_functions.py
+++ b/ckan/lib/navl/dictization_functions.py
@@ -524,7 +524,7 @@ def resolve_string_key(data, string_key):
try:
index = int(k)
- if index < 0 or index >= len(current):
+ if index < -len(current) or index >= len(current):
raise ValueError
except ValueError:
raise DataError('Unmatched key %s' % '__'.join(
diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py
--- a/ckan/logic/action/update.py
+++ b/ckan/logic/action/update.py
@@ -373,28 +373,28 @@ def package_revise(context, data_dict):
is not "big.csv".
:type match: dict
:param filter: a list of string patterns of fields to remove from the
- current dataset. e.g. ``["-resources__1"]`` would remove the
- second resource, ``["+title", "+resources", "-*"]`` would
+ current dataset. e.g. ``"-resources__1"`` would remove the
+ second resource, ``"+title, +resources, -*"`` would
remove all fields at the dataset level except title and
all resources (default: ``[]``)
- :type filter: list of string patterns
+ :type filter: comma-separated string patterns or list of string patterns
:param update: a dict with values to update/create after filtering
e.g. ``{"resources": [{"description": "file here"}]}`` would
update the description for the first resource
:type update: dict
:param include: a list of string pattern of fields to include in response
- e.g. ``["-*"]`` to return nothing (default: ``[]`` all
+ e.g. ``"-*"`` to return nothing (default: ``[]`` all
fields returned)
- :type include: list of string patterns
+ :type include: comma-separated-string patterns or list of string patterns
- ``match`` and ``update`` parameters may also be passed as path keys, using
+ ``match`` and ``update`` parameters may also be passed as "flattened keys", using
either the item numeric index or its unique id (with a minimum of 5 characters), e.g.
- ``update__resource__1f9ab__description="file here"`` would set the
- description of the resource with id starting with "1f9ab" to "file here", and
- ``update__resource__1__description="file here"`` would do the same
- on the second resource in the dataset.
+ ``update__resource__1f9ab__description="guidebook"`` would set the
+ description of the resource with id starting with "1f9ab" to "guidebook", and
+ ``update__resource__-1__description="guidebook"`` would do the same
+ on the last resource in the dataset.
- The ``extend`` key can also be used on the update parameter to add
+ The ``extend`` suffix can also be used on the update parameter to add
a new item to a list, e.g. ``update__resources__extend=[{"name": "new resource", "url": "https://example.com"}]``
will add a new resource to the dataset with the provided ``name`` and ``url``.
@@ -407,9 +407,9 @@ def package_revise(context, data_dict):
* Identical to above, but using flattened keys::
- match__name "xyz"
- match__notes "old notes"
- update__notes "new notes"
+ match__name="xyz"
+ match__notes="old notes"
+ update__notes="new notes"
* Replace all fields at dataset level only, keep resources (note: dataset id
and type fields can't be deleted) ::
@@ -440,7 +440,7 @@ def package_revise(context, data_dict):
update__resources__1492a={"name": "edits here", "url": "http://example.com"}
- :returns: the updated dataset with fields filtered by include parameter
+ :returns: a dict containing 'package':the updated dataset with fields filtered by include parameter
:rtype: dictionary
'''
@@ -496,8 +496,16 @@ def package_revise(context, data_dict):
model.Session.rollback()
raise ValidationError([{'update': [de.error]}])
- for k, v in sorted(data['update__'].items()):
- dfunc.update_merge_string_key(orig, k, v)
+ # update __extend keys before __#__* so that files may be
+ # attached to newly added resources in the same call
+ try:
+ for k, v in sorted(
+ data['update__'].items(),
+ key=lambda s: s[0][-6] if s[0].endswith('extend') else s[0]):
+ dfunc.update_merge_string_key(orig, k, v)
+ except dfunc.DataError as de:
+ model.Session.rollback()
+ raise ValidationError([{k: [de.error]}])
_check_access('package_revise', context, orig)
diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py
--- a/ckan/logic/validators.py
+++ b/ckan/logic/validators.py
@@ -783,6 +783,8 @@ def if_empty_guess_format(key, data, errors, context):
# if resource_id then an update
if (not value or value is Missing) and not resource_id:
url = data.get(key[:-1] + ('url',), '')
+ if not url:
+ return
mimetype, encoding = mimetypes.guess_type(url)
if mimetype:
data[key] = mimetype
| Improvements to package_revise
**CKAN version**
master
**Describe the bug**
description captured here https://github.com/ckan/ckan/pull/4618#issuecomment-650226686
**Steps to reproduce**
see above
**Expected behavior**
ckan doesn't crash
| 2020-06-29T22:27:01 |
||
ckan/ckan | 5,478 | ckan__ckan-5478 | [
"5476"
] | 0f87337fd937a15545ed761367b5d27d888e3803 | diff --git a/ckan/config/routing.py b/ckan/config/routing.py
--- a/ckan/config/routing.py
+++ b/ckan/config/routing.py
@@ -3,7 +3,7 @@
The more specific and detailed routes should be defined first so they
may take precedent over the more generic routes. For more information
-refer to the routes manual at http://routes.groovie.org/docs/
+refer to the routes manual at https://routes.readthedocs.io/en/latest/
"""
import re
| routes manual reference URL in comment is broken
**CKAN version**
latest
**Describe the bug**
The url in [comment ](https://github.com/ckan/ckan/blob/0f87337fd937a15545ed761367b5d27d888e3803/ckan/config/routing.py#L6) is broken.
**Steps to reproduce**
Steps to reproduce the behavior:
Open a browser and go to "http://routes.groovie.org/docs/"

**Expected behavior**
A valid documentation reference.
| 2020-06-30T07:53:56 |
||
ckan/ckan | 5,482 | ckan__ckan-5482 | [
"5479",
"5479"
] | e60719fcbebe8edcde8e35cd78e7ecafcd3a2d75 | diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py
--- a/ckan/logic/action/update.py
+++ b/ckan/logic/action/update.py
@@ -1202,6 +1202,17 @@ def _bulk_update_dataset(context, data_dict, update_dict):
.filter(model.Package.owner_org == org_id) \
.update(update_dict, synchronize_session=False)
+ # Handle Activity Stream for Bulk Operations
+ user = context['user']
+ user_obj = model.User.by_name(user)
+ if user_obj:
+ user_id = user_obj.id
+ else:
+ user_id = 'not logged in'
+ for dataset in datasets:
+ entity = model.Package.get(dataset)
+ activity = entity.activity_stream_item('changed', user_id)
+ model.Session.add(activity)
model.Session.commit()
# solr update here
| diff --git a/ckan/tests/logic/action/test_update.py b/ckan/tests/logic/action/test_update.py
--- a/ckan/tests/logic/action/test_update.py
+++ b/ckan/tests/logic/action/test_update.py
@@ -1688,6 +1688,10 @@ def test_bulk_make_public(self):
)
for dataset in datasets:
assert not (dataset.private)
+ activities = helpers.call_action(
+ "organization_activity_list", id=org["id"]
+ )
+ assert activities[0]['activity_type'] == 'changed package'
def test_bulk_delete(self):
@@ -1719,6 +1723,11 @@ def test_bulk_delete(self):
for dataset in datasets:
assert dataset.state == "deleted"
+ activities = helpers.call_action(
+ "organization_activity_list", id=org["id"]
+ )
+ assert activities[0]['activity_type'] == 'deleted package'
+
@pytest.mark.usefixtures("clean_db", "with_request_context")
class TestDashboardMarkActivitiesOld(object):
| Update events not captured in activity stream when using the dataset grid view in the organization
**CKAN version**
master
**Describe the bug**
Delete events not captured in activity stream when using the dataset grid view
**Steps to reproduce**
1. Login with Admin
2. Go to Organization
3. Click on Manage
4. Go to Datasets Tab
5. Select the multiple Datasets
6. Delete
<img width="1440" alt="Screenshot 2020-07-01 at 12 04 53 PM" src="https://user-images.githubusercontent.com/25545982/86211021-44f95900-bb93-11ea-9a87-d84c17b17ee0.png">
<img width="1438" alt="Screenshot 2020-07-01 at 1 18 43 PM" src="https://user-images.githubusercontent.com/25545982/86217767-93135a00-bb9d-11ea-9979-3d44fc968d68.png">
**Expected behavior**
There should be logging in activity stream when we use bulk delete of datasets
Update events not captured in activity stream when using the dataset grid view in the organization
**CKAN version**
master
**Describe the bug**
Delete events not captured in activity stream when using the dataset grid view
**Steps to reproduce**
1. Login with Admin
2. Go to Organization
3. Click on Manage
4. Go to Datasets Tab
5. Select the multiple Datasets
6. Delete
<img width="1440" alt="Screenshot 2020-07-01 at 12 04 53 PM" src="https://user-images.githubusercontent.com/25545982/86211021-44f95900-bb93-11ea-9a87-d84c17b17ee0.png">
<img width="1438" alt="Screenshot 2020-07-01 at 1 18 43 PM" src="https://user-images.githubusercontent.com/25545982/86217767-93135a00-bb9d-11ea-9979-3d44fc968d68.png">
**Expected behavior**
There should be logging in activity stream when we use bulk delete of datasets
| 2020-07-02T09:18:53 |
|
ckan/ckan | 5,502 | ckan__ckan-5502 | [
"5501"
] | c85561189b1bb88d9c8cf80809aa8bcd08912a5f | diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py
--- a/ckan/logic/validators.py
+++ b/ckan/logic/validators.py
@@ -937,9 +937,8 @@ def email_is_unique(key, data, errors, context):
return
raise Invalid(
- _('The email address \'{email}\' \
- belongs to a registered user.').
- format(email=data[key]))
+ _('The email address \'{email}\' belongs to a registered user.').format(email=data[key]))
+
def one_of(list_of_value):
''' Checks if the provided value is present in a list '''
| Fix line breaks in translatable strings
I've got reports of confusing strings from translators, eg:

There is a line break and extra spaces in the middle of the source string (`msgid`) and it's unclear to users if they should keep it in their translations.
This is how the `msgid` looks like:
```
#: ckan/templates/snippets/changes/extension_fields.html:3
msgid ""
"Changed value of field <q>{key}</q> to <q>{value}</q> in\n"
" {pkg_link}"
msgstr ""
```
The source file contains a line break probably created by an overzealous code formatter:
```
{{ _('Changed value of field <q>{key}</q> to <q>{value}</q> in
{pkg_link}')
```
Most if not all the strings seemed to be part of the snippets added in the `changes` folder on https://github.com/ckan/ckan/pull/4929 so I think it's ok if for now we manually fix the strings in the snippets, extract them and update the msgids on the po files using the `ckan translation sync-msgids` command we introduced in #5339
| 2020-07-16T08:53:49 |
||
ckan/ckan | 5,503 | ckan__ckan-5503 | [
"5494"
] | dc345470054a098c285edba7b6a25eba63f5e300 | diff --git a/ckan/cli/less.py b/ckan/cli/less.py
--- a/ckan/cli/less.py
+++ b/ckan/cli/less.py
@@ -10,45 +10,6 @@
from ckan.cli import error_shout
-_custom_css = {
- u'fuchsia': u'''
- @layoutLinkColor: #E73892;
- @footerTextColor: mix(#FFF, @layoutLinkColor, 60%);
- @footerLinkColor: @footerTextColor;
- @mastheadBackgroundColor: @layoutLinkColor;
- @btnPrimaryBackground: lighten(@layoutLinkColor, 10%);
- @btnPrimaryBackgroundHighlight: @layoutLinkColor;
- ''',
-
- u'green': u'''
- @layoutLinkColor: #2F9B45;
- @footerTextColor: mix(#FFF, @layoutLinkColor, 60%);
- @footerLinkColor: @footerTextColor;
- @mastheadBackgroundColor: @layoutLinkColor;
- @btnPrimaryBackground: lighten(@layoutLinkColor, 10%);
- @btnPrimaryBackgroundHighlight: @layoutLinkColor;
- ''',
-
- u'red': u'''
- @layoutLinkColor: #C14531;
- @footerTextColor: mix(#FFF, @layoutLinkColor, 60%);
- @footerLinkColor: @footerTextColor;
- @mastheadBackgroundColor: @layoutLinkColor;
- @btnPrimaryBackground: lighten(@layoutLinkColor, 10%);
- @btnPrimaryBackgroundHighlight: @layoutLinkColor;
- ''',
-
- u'maroon': u'''
- @layoutLinkColor: #810606;
- @footerTextColor: mix(#FFF, @layoutLinkColor, 60%);
- @footerLinkColor: @footerTextColor;
- @mastheadBackgroundColor: @layoutLinkColor;
- @btnPrimaryBackground: lighten(@layoutLinkColor, 10%);
- @btnPrimaryBackgroundHighlight: @layoutLinkColor;
- ''',
-}
-
-
@click.command(
name=u'less',
short_help=u'Compile all root less documents into their CSS counterparts')
@@ -59,16 +20,6 @@ def less():
root = os.path.join(os.path.dirname(__file__), u'..', public, u'base')
root = os.path.abspath(root)
- custom_less = os.path.join(root, u'less', u'custom.less')
- for color in _custom_css:
- f = open(custom_less, u'w')
- f.write(_custom_css[color])
- f.close()
- _compile_less(root, command, color)
- f = open(custom_less, u'w')
- f.write(u'// This file is needed in order for `gulp build` to '
- u'compile in less 1.3.1+\n')
- f.close()
_compile_less(root, command, u'main')
diff --git a/ckan/lib/app_globals.py b/ckan/lib/app_globals.py
--- a/ckan/lib/app_globals.py
+++ b/ckan/lib/app_globals.py
@@ -17,6 +17,8 @@
log = logging.getLogger(__name__)
+DEFAULT_MAIN_CSS_FILE = '/base/css/main.css'
+
# mappings translate between config settings and globals because our naming
# conventions are not well defined and/or implemented
mappings = {
@@ -168,7 +170,8 @@ def get_config_value(key, default=''):
get_config_value(key)
# custom styling
- main_css = get_config_value('ckan.main_css', '/base/css/main.css')
+ main_css = get_config_value(
+ 'ckan.main_css', DEFAULT_MAIN_CSS_FILE) or DEFAULT_MAIN_CSS_FILE
set_main_css(main_css)
if app_globals.site_logo:
diff --git a/ckan/views/admin.py b/ckan/views/admin.py
--- a/ckan/views/admin.py
+++ b/ckan/views/admin.py
@@ -26,23 +26,6 @@ def _get_sysadmins():
def _get_config_options():
- styles = [{
- u'text': u'Default',
- u'value': u'/base/css/main.css'
- }, {
- u'text': u'Red',
- u'value': u'/base/css/red.css'
- }, {
- u'text': u'Green',
- u'value': u'/base/css/green.css'
- }, {
- u'text': u'Maroon',
- u'value': u'/base/css/maroon.css'
- }, {
- u'text': u'Fuchsia',
- u'value': u'/base/css/fuchsia.css'
- }]
-
homepages = [{
u'value': u'1',
u'text': (u'Introductory area, search, featured'
@@ -56,7 +39,7 @@ def _get_config_options():
u'text': u'Search, introductory area and stats'
}]
- return dict(styles=styles, homepages=homepages)
+ return dict(homepages=homepages)
def _get_config_items():
| diff --git a/ckan/tests/controllers/test_admin.py b/ckan/tests/controllers/test_admin.py
--- a/ckan/tests/controllers/test_admin.py
+++ b/ckan/tests/controllers/test_admin.py
@@ -49,22 +49,8 @@ def test_site_title(self, app, sysadmin_env):
reset_index_response = app.get("/")
assert "Welcome - CKAN" in reset_index_response
- def test_main_css_list(self, app, sysadmin_env):
- """Style list contains pre-configured styles"""
-
- STYLE_NAMES = ["Default", "Red", "Green", "Maroon", "Fuchsia"]
-
- url = url_for(u"admin.config")
- config_response = app.get(url, environ_overrides=sysadmin_env)
- config_response_html = BeautifulSoup(config_response.body)
- style_select_options = config_response_html.select(
- "#field-ckan-main-css option"
- )
- for option in style_select_options:
- assert option.string in STYLE_NAMES
-
def test_main_css(self, app, sysadmin_env):
- """Select a colour style"""
+ """Define a custom css file"""
# current style
index_response = app.get("/")
@@ -72,10 +58,10 @@ def test_main_css(self, app, sysadmin_env):
url = url_for(u"admin.config")
# set new style css
- form = {"ckan.main_css": "/base/css/red.css", "save": ""}
+ form = {"ckan.main_css": "/base/css/main-rtl.css", "save": ""}
resp = app.post(url, data=form, environ_overrides=sysadmin_env)
- assert "red.css" in resp or "red.min.css" in resp
+ assert "main-rtl.css" in resp or "main-rtl.min.css" in resp
assert not helpers.body_contains(resp, "main.min.css")
def test_tag_line(self, app, sysadmin_env):
| Remove built-in color themes
It's unclear how valuable they are for users, and they have created issues on the past (eg #4202, #2099). The last one I found was when running the `less` command with upgraded versions:
```
Missing argument value: gulpfile
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `gulp build "-fuchsia"`
npm ERR! Exit status 1
```
Yes, this can be fixed in our command code, but it's just an example of a feature that causes problems and doesn't have clear value.
I have a PR ready if people is happy.
| 2020-07-16T09:09:18 |
|
ckan/ckan | 5,546 | ckan__ckan-5546 | [
"5537"
] | b383cebd7e002fcb618210619672fc87348c3a90 | diff --git a/ckan/logic/converters.py b/ckan/logic/converters.py
--- a/ckan/logic/converters.py
+++ b/ckan/logic/converters.py
@@ -26,14 +26,24 @@ def convert_to_extras(key, data, errors, context):
def convert_from_extras(key, data, errors, context):
- def remove_from_extras(data, key):
- to_remove = []
- for data_key, data_value in six.iteritems(data):
- if (data_key[0] == 'extras'
- and data_key[1] == key):
- to_remove.append(data_key)
- for item in to_remove:
- del data[item]
+ def remove_from_extras(data, idx):
+ for key in sorted(data):
+ if key[0] != 'extras' or key[1] < idx:
+ continue
+ if key[1] == idx:
+ del data[key]
+
+ # Following block required for unflattening extras with
+ # "gaps" created sometimes by `convert_from_extra`
+ # validator :
+ #
+ # {
+ # ('extras', 0, 'key'): 'x',
+ # ('extras', 2, 'key): 'y'
+ # }
+ if key[1] > idx:
+ new_key = (key[0], key[1] - 1) + key[2:]
+ data[new_key] = data.pop(key)
for data_key, data_value in six.iteritems(data):
if (data_key[0] == 'extras'
diff --git a/ckanext/example_idatasetform/plugin_v5.py b/ckanext/example_idatasetform/plugin_v5.py
--- a/ckanext/example_idatasetform/plugin_v5.py
+++ b/ckanext/example_idatasetform/plugin_v5.py
@@ -30,7 +30,9 @@ def show_package_schema(self):
schema = super(ExampleIDatasetFormPlugin, self).show_package_schema()
schema.update({
u'custom_text': [tk.get_converter(u'convert_from_extras'),
- tk.get_validator(u'ignore_missing')]
+ tk.get_validator(u'ignore_missing')],
+ u'custom_text_2': [tk.get_converter(u'convert_from_extras'),
+ tk.get_validator(u'ignore_missing')],
})
return schema
| diff --git a/ckanext/example_idatasetform/tests/test_example_idatasetform.py b/ckanext/example_idatasetform/tests/test_example_idatasetform.py
--- a/ckanext/example_idatasetform/tests/test_example_idatasetform.py
+++ b/ckanext/example_idatasetform/tests/test_example_idatasetform.py
@@ -79,6 +79,40 @@ def test_custom_package_type_urls(self):
url_for("fancy_type.edit", id="check") == "/fancy_type/edit/check"
)
+ def test_custom_field_with_extras(self):
+ dataset = factories.Dataset(
+ type='fancy_type',
+ name='test-dataset',
+ custom_text='custom-text',
+ extras=[
+ {'key': 'key1', 'value': 'value1'},
+ {'key': 'key2', 'value': 'value2'},
+ ]
+ )
+ assert dataset['custom_text'] == 'custom-text'
+ assert dataset['extras'] == [
+ {'key': 'key1', 'value': 'value1'},
+ {'key': 'key2', 'value': 'value2'},
+ ]
+
+ def test_mixed_extras(self):
+ dataset = factories.Dataset(
+ type='fancy_type',
+ name='test-dataset',
+ custom_text='custom-text',
+ extras=[
+ {'key': 'key1', 'value': 'value1'},
+ {'key': 'custom_text_2', 'value': 'custom-text-2'},
+ {'key': 'key2', 'value': 'value2'},
+ ],
+ )
+ assert dataset['custom_text'] == 'custom-text'
+ assert dataset['custom_text_2'] == 'custom-text-2'
+ assert dataset['extras'] == [
+ {'key': 'key1', 'value': 'value1'},
+ {'key': 'key2', 'value': 'value2'},
+ ]
+
@pytest.mark.ckan_config("ckan.plugins", u"example_idatasetform_v5")
@pytest.mark.ckan_config("package_edit_return_url", None)
| KeyError: 'key' after Patch Update to 2.8.5
**CKAN version**
2.8.5
**Describe the bug**
After Patch Update to 2.8.5 my CKAN catalog is showing an internal server error when I´m trying to open a dataset list or dataset.
The ckan_default.error.log is showing KeyErrors
**Steps to reproduce**
Trying to do the latest patch update from CKAN version 2.8.4 to 2.8.5 on a ubuntu 18.04 instance. Because my CKAN installation is from source I tried following steps:
`. /usr/lib/ckan/default/bin/activate`
`cd /usr/lib/ckan/default/src/ckan`
`git fetch`
`git checkout ckan-2.8.5`
`pip install --upgrade -r requirements.txt`
`paster search-index rebuild -r --config=/etc/ckan/default/production.ini`
`sudo service apache2 restart `
**Expected behavior**
I should be able to open any dataset-list or dataset via browser in the CKAN catalog
**Additional details**
full Error from ckan_default.error.log:
```
Error - <type 'exceptions.KeyError'>: 'key'
URL: http://apgc.awi.de/group/1fad2eb2-9ee5-4030-80f1-4563a803525c?organization=pangaea&res_format=FileGDB
File '/usr/lib/ckan/default/lib/python2.7/site-packages/weberror/errormiddleware.py', line 171 in __call__
app_iter = self.application(environ, sr_checker)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/fanstatic/publisher.py', line 234 in __call__
return request.get_response(self.app)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
application, catch_exc_info=False)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
app_iter = application(self.environ, start_response)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/fanstatic/injector.py', line 54 in __call__
response = request.get_response(self.app)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
application, catch_exc_info=False)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
app_iter = application(self.environ, start_response)
File '/usr/lib/ckan/default/src/ckan/ckan/config/middleware/pylons_app.py', line 264 in inner
result = application(environ, start_response)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/beaker/middleware.py', line 73 in __call__
return self.app(environ, start_response)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/beaker/middleware.py', line 156 in __call__
return self.wrap_app(environ, session_start_response)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/routes/middleware.py', line 131 in __call__
response = self.app(environ, start_response)
File '/usr/lib/ckan/default/src/ckan/ckan/config/middleware/common_middleware.py', line 33 in __call__
return self.app(environ, start_response)
File '/usr/lib/ckan/default/src/ckan/ckan/config/middleware/common_middleware.py', line 59 in __call__
return self.app(environ, start_response)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/pylons/wsgiapp.py', line 125 in __call__
response = self.dispatch(controller, environ, start_response)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/pylons/wsgiapp.py', line 324 in dispatch
return controller(environ, start_response)
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 242 in __call__
res = WSGIController.__call__(self, environ, start_response)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/pylons/controllers/core.py', line 221 in __call__
response = self._dispatch_call()
File '/usr/lib/ckan/default/lib/python2.7/site-packages/pylons/controllers/core.py', line 172 in _dispatch_call
response = self._inspect_call(func)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/pylons/controllers/core.py', line 107 in _inspect_call
result = self._perform_call(func, args)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/pylons/controllers/core.py', line 60 in _perform_call
return func(**args)
File '/usr/lib/ckan/default/src/ckan/ckan/controllers/group.py', line 230 in read
extra_vars={'group_type': group_type})
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 127 in render
return cached_template(template_name, renderer)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/pylons/templating.py', line 249 in cached_template
return render_func()
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 164 in render_template
return render_jinja2(template_name, globs)
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 96 in render_jinja2
return template.render(**extra_vars)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/jinja2/environment.py', line 989 in render
return self.environment.handle_exception(exc_info, True)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/jinja2/environment.py', line 754 in handle_exception
reraise(exc_type, exc_value, tb)
File '/usr/lib/ckan/default/src/ckan/ckan/templates/group/read.html', line 1 in top-level template code
{% extends "group/read_base.html" %}
File '/usr/lib/ckan/default/src/ckanext-apgc_theme/ckanext/apgc_theme/templates/group/read_base.html', line 1 in top-level template code
{% ckan_extends %}
File '/usr/lib/ckan/default/src/ckan/ckan/templates/group/read_base.html', line 1 in top-level template code
{% extends "page.html" %}
File '/usr/lib/ckan/default/src/ckan/ckan/templates/page.html', line 1 in top-level template code
{% extends "base.html" %}
File '/usr/lib/ckan/default/lib/python2.7/site-packages/ckanext/geoview/templates/base.html', line 1 in top-level template code
{% ckan_extends %}
File '/usr/lib/ckan/default/src/ckanext-pages/ckanext/pages/theme/templates_main/base.html', line 1 in top-level template code
{% ckan_extends %}
File '/usr/lib/ckan/default/src/ckanext-apgc_theme/ckanext/apgc_theme/templates/base.html', line 1 in top-level template code
{% ckan_extends %}
File '/usr/lib/ckan/default/src/ckan/ckan/templates/base.html', line 101 in top-level template code
{%- block page %}{% endblock -%}
File '/usr/lib/ckan/default/src/ckan/ckan/templates/page.html', line 19 in block "page"
{%- block content %}
File '/usr/lib/ckan/default/src/ckan/ckan/templates/page.html', line 22 in block "content"
{% block main_content %}
File '/usr/lib/ckan/default/src/ckan/ckan/templates/page.html', line 74 in block "main_content"
{% block primary %}
File '/usr/lib/ckan/default/src/ckan/ckan/templates/page.html', line 87 in block "primary"
{% block primary_content %}
File '/usr/lib/ckan/default/src/ckan/ckan/templates/page.html', line 107 in block "primary_content"
{% block primary_content_inner %}
File '/usr/lib/ckan/default/src/ckan/ckan/templates/group/read.html', line 21 in block "primary_content_inner"
{% block packages_list %}
File '/usr/lib/ckan/default/src/ckan/ckan/templates/group/read.html', line 23 in block "packages_list"
{{ h.snippet('snippets/package_list.html', packages=c.page.items) }}
File '/usr/lib/ckan/default/src/ckan/ckan/lib/helpers.py', line 1709 in snippet
return base.render_snippet(template_name, **kw)
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 86 in render_snippet
output = render(template_name, extra_vars=kw)
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 127 in render
return cached_template(template_name, renderer)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/pylons/templating.py', line 249 in cached_template
return render_func()
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 164 in render_template
return render_jinja2(template_name, globs)
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 96 in render_jinja2
return template.render(**extra_vars)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/jinja2/environment.py', line 989 in render
return self.environment.handle_exception(exc_info, True)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/jinja2/environment.py', line 754 in handle_exception
reraise(exc_type, exc_value, tb)
File '/usr/lib/ckan/default/src/ckanext-apgc_theme/ckanext/apgc_theme/templates/snippets/package_list.html', line 17 in top-level template code
{% block package_list %}
File '/usr/lib/ckan/default/src/ckanext-apgc_theme/ckanext/apgc_theme/templates/snippets/package_list.html', line 20 in block "package_list"
{% block package_list_inner %}
File '/usr/lib/ckan/default/src/ckanext-apgc_theme/ckanext/apgc_theme/templates/snippets/package_list.html', line 22 in block "package_list_inner"
{% snippet 'snippets/package_item.html', package=package, item_class=item_class, hide_resources=hide_resources, banner=banner, truncate=truncate , truncate_title=120%}
File '/usr/lib/ckan/default/src/ckan/ckan/lib/jinja_extensions.py', line 268 in _call
return base.render_snippet(args[0], **kwargs)
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 86 in render_snippet
output = render(template_name, extra_vars=kw)
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 127 in render
return cached_template(template_name, renderer)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/pylons/templating.py', line 249 in cached_template
return render_func()
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 164 in render_template
return render_jinja2(template_name, globs)
File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 96 in render_jinja2
return template.render(**extra_vars)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/jinja2/environment.py', line 989 in render
return self.environment.handle_exception(exc_info, True)
File '/usr/lib/ckan/default/lib/python2.7/site-packages/jinja2/environment.py', line 754 in handle_exception
reraise(exc_type, exc_value, tb)
File '/usr/lib/ckan/default/src/ckanext-apgc_theme/ckanext/apgc_theme/templates/snippets/package_item.html', line 39 in top-level template code
{% block package_item %}
File '/usr/lib/ckan/default/src/ckanext-apgc_theme/ckanext/apgc_theme/templates/snippets/package_item.html', line 41 in block "package_item"
{% block content %}
File '/usr/lib/ckan/default/src/ckanext-apgc_theme/ckanext/apgc_theme/templates/snippets/package_item.html', line 81 in block "content"
{% for key, value in h.sorted_extras(package.extras) %}
File '/usr/lib/ckan/default/src/ckan/ckan/lib/helpers.py', line 1135 in sorted_extras
for extra in sorted(package_extras, key=lambda x: x['key']):
File '/usr/lib/ckan/default/src/ckan/ckan/lib/helpers.py', line 1135 in <lambda>
for extra in sorted(package_extras, key=lambda x: x['key']):
KeyError: 'key'
```
| 2020-08-16T21:35:01 |
|
ckan/ckan | 5,573 | ckan__ckan-5573 | [
"5562"
] | 6d3453396359c9fc401e4f60383ee1b7f9e05885 | diff --git a/ckan/lib/changes.py b/ckan/lib/changes.py
--- a/ckan/lib/changes.py
+++ b/ckan/lib/changes.py
@@ -67,12 +67,12 @@ def check_resource_changes(change_list, old, new, old_activity_id):
new_resource_set = set()
new_resource_dict = {}
- for resource in old['resources']:
+ for resource in old.get(u'resources'):
old_resource_set.add(resource['id'])
old_resource_dict[resource['id']] = {
key: value for (key, value) in resource.items() if key != u'id'}
- for resource in new['resources']:
+ for resource in new.get(u'resources'):
new_resource_set.add(resource['id'])
new_resource_dict[resource['id']] = {
key: value for (key, value) in resource.items() if key != u'id'}
@@ -82,9 +82,9 @@ def check_resource_changes(change_list, old, new, old_activity_id):
for resource_id in new_resources:
change_list.append({u'type': u'new_resource',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_name':
- new_resource_dict[resource_id]['name'],
+ new_resource_dict[resource_id].get(u'name'),
u'resource_id': resource_id})
# get the IDs of resources that have been deleted between versions
@@ -92,10 +92,10 @@ def check_resource_changes(change_list, old, new, old_activity_id):
for resource_id in deleted_resources:
change_list.append({u'type': u'delete_resource',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- old_resource_dict[resource_id]['name'],
+ old_resource_dict[resource_id].get(u'name'),
u'old_activity_id': old_activity_id})
# now check the resources that are in both and see if any
@@ -105,93 +105,94 @@ def check_resource_changes(change_list, old, new, old_activity_id):
old_metadata = old_resource_dict[resource_id]
new_metadata = new_resource_dict[resource_id]
- if old_metadata['name'] != new_metadata['name']:
+ if old_metadata.get(u'name') != new_metadata.get(u'name'):
change_list.append({u'type': u'resource_name',
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'old_pkg_id': old['id'],
u'new_pkg_id': new['id'],
u'resource_id': resource_id,
u'old_resource_name':
- old_resource_dict[resource_id]['name'],
+ old_resource_dict[resource_id].get(u'name'),
u'new_resource_name':
- new_resource_dict[resource_id]['name'],
+ new_resource_dict[resource_id].get(u'name'),
u'old_activity_id': old_activity_id})
# you can't remove a format, but if a resource's format isn't
# recognized, it won't have one set
# if a format was not originally set and the user set one
- if not old_metadata['format'] and new_metadata['format']:
+ if not old_metadata.get(u'format') and new_metadata.get(u'format'):
change_list.append({u'type': u'resource_format',
u'method': u'add',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_resource_dict[resource_id]['name'],
- u'org_id': new['organization']['id']
- if new['organization'] else u'',
- u'format': new_metadata['format']})
+ new_resource_dict[resource_id].get(u'name'),
+ u'org_id': new.get(u'organization')['id']
+ if new.get(u'organization') else u'',
+ u'format': new_metadata.get(u'format')})
# if both versions have a format but the format changed
- elif old_metadata['format'] != new_metadata['format']:
+ elif old_metadata.get(u'format') != new_metadata.get(u'format'):
change_list.append({u'type': u'resource_format',
u'method': u'change',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_resource_dict[resource_id]['name'],
- u'org_id': new['organization']['id']
- if new['organization'] else u'',
- u'old_format': old_metadata['format'],
- u'new_format': new_metadata['format']})
+ new_resource_dict[resource_id].get(u'name'),
+ u'org_id': new.get(u'organization')['id']
+ if new.get(u'organization') else u'',
+ u'old_format': old_metadata.get(u'format'),
+ u'new_format': new_metadata.get(u'format')})
# if the description changed
- if not old_metadata['description'] and \
- new_metadata['description']:
+ if not old_metadata.get(u'description') and \
+ new_metadata.get(u'description'):
change_list.append({u'type': u'resource_desc',
u'method': u'add',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_resource_dict[resource_id]['name'],
- u'new_desc': new_metadata['description']})
+ new_resource_dict[resource_id].get(u'name'),
+ u'new_desc': new_metadata.get(u'description')})
# if there was a description but the user removed it
- elif old_metadata['description'] and \
- not new_metadata['description']:
+ elif old_metadata.get(u'description') and \
+ not new_metadata.get(u'description'):
change_list.append({u'type': u'resource_desc',
u'method': u'remove',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_resource_dict[resource_id]['name']})
+ new_resource_dict[resource_id].get(u'name')})
# if both have descriptions but they are different
- elif old_metadata['description'] != new_metadata['description']:
+ elif old_metadata.get(u'description') \
+ != new_metadata.get(u'description'):
change_list.append({u'type': u'resource_desc',
u'method': u'change',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_resource_dict[resource_id]['name'],
- u'new_desc': new_metadata['description'],
- u'old_desc': old_metadata['description']})
+ new_resource_dict[resource_id].get(u'name'),
+ u'new_desc': new_metadata.get(u'description'),
+ u'old_desc': old_metadata.get(u'description')})
# check if the url changes (e.g. user uploaded a new file)
# TODO: use regular expressions to determine the actual name of the
# new and old files
- if old_metadata['url'] != new_metadata['url']:
+ if old_metadata.get(u'url') != new_metadata.get(u'url'):
change_list.append({u'type': u'new_file',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_metadata['name']})
+ new_metadata.get(u'name')})
# check any extra fields in the resource
# remove default fields from these sets to make sure we only check
@@ -208,29 +209,29 @@ def check_resource_changes(change_list, old, new, old_activity_id):
change_list.append({u'type': u'resource_extras',
u'method': u'add_one_value',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_metadata['name'],
+ new_metadata.get(u'name'),
u'key': new_fields[0],
u'value': new_metadata[new_fields[0]]})
else:
change_list.append({u'type': u'resource_extras',
u'method': u'add_one_no_value',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_metadata['name'],
+ new_metadata.get(u'name'),
u'key': new_fields[0]})
elif len(new_fields) > 1:
change_list.append({u'type': u'resource_extras',
u'method': u'add_multiple',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_metadata['name'],
+ new_metadata.get(u'name'),
u'key_list': new_fields,
u'value_list':
[new_metadata[field] for field in new_fields]})
@@ -241,19 +242,19 @@ def check_resource_changes(change_list, old, new, old_activity_id):
change_list.append({u'type': u'resource_extras',
u'method': u'remove_one',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_metadata['name'],
+ new_metadata.get(u'name'),
u'key': deleted_fields[0]})
elif len(deleted_fields) > 1:
change_list.append({u'type': u'resource_extras',
u'method': u'remove_multiple',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_metadata['name'],
+ new_metadata.get(u'name'),
u'key_list': deleted_fields})
# determine if any extra fields have been changed
@@ -267,10 +268,10 @@ def check_resource_changes(change_list, old, new, old_activity_id):
change_list.append({u'type': u'resource_extras',
u'method': u'change_value_with_old',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_metadata['name'],
+ new_metadata.get(u'name'),
u'key': field,
u'old_value': old_metadata[field],
u'new_value': new_metadata[field]})
@@ -278,20 +279,20 @@ def check_resource_changes(change_list, old, new, old_activity_id):
change_list.append({u'type': u'resource_extras',
u'method': u'change_value_no_old',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_metadata['name'],
+ new_metadata.get(u'name'),
u'key': field,
u'new_value': new_metadata[field]})
elif not new_metadata[field]:
change_list.append({u'type': u'resource_extras',
u'method': u'change_value_no_new',
u'pkg_id': new['id'],
- u'title': new['title'],
+ u'title': new.get(u'title'),
u'resource_id': resource_id,
u'resource_name':
- new_metadata['name'],
+ new_metadata.get(u'name'),
u'key': field})
@@ -301,65 +302,65 @@ def check_metadata_changes(change_list, old, new):
(excluding resources) in change_list.
'''
# if the title has changed
- if old['title'] != new['title']:
+ if old.get(u'title') != new.get(u'title'):
_title_change(change_list, old, new)
# if the owner organization changed
- if old['owner_org'] != new['owner_org']:
+ if old.get(u'owner_org') != new.get(u'owner_org'):
_org_change(change_list, old, new)
# if the maintainer of the dataset changed
- if old['maintainer'] != new['maintainer']:
+ if old.get(u'maintainer') != new.get(u'maintainer'):
_maintainer_change(change_list, old, new)
# if the maintainer email of the dataset changed
- if old['maintainer_email'] != new['maintainer_email']:
+ if old.get(u'maintainer_email') != new.get(u'maintainer_email'):
_maintainer_email_change(change_list, old, new)
# if the author of the dataset changed
- if old['author'] != new['author']:
+ if old.get(u'author') != new.get(u'author'):
_author_change(change_list, old, new)
# if the author email of the dataset changed
- if old['author_email'] != new['author_email']:
+ if old.get(u'author_email') != new.get(u'author_email'):
_author_email_change(change_list, old, new)
# if the visibility of the dataset changed
- if old['private'] != new['private']:
- change_list.append({u'type': u'private', u'pkg_id': new['id'],
- u'title': new['title'],
+ if old.get(u'private') != new.get(u'private'):
+ change_list.append({u'type': u'private', u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'new':
- u'Private' if bool(new['private'])
+ u'Private' if bool(new.get(u'private'))
else u'Public'})
# if the description of the dataset changed
- if old['notes'] != new['notes']:
+ if old.get(u'notes') != new.get(u'notes'):
_notes_change(change_list, old, new)
# make sets out of the tags for each dataset
- old_tags = {tag['name'] for tag in old['tags']}
- new_tags = {tag['name'] for tag in new['tags']}
+ old_tags = {tag.get(u'name') for tag in old.get(u'tags', [])}
+ new_tags = {tag.get(u'name') for tag in new.get(u'tags', [])}
# if the tags have changed
if old_tags != new_tags:
_tag_change(change_list, new_tags, old_tags, new)
# if the license has changed
- if old['license_title'] != new['license_title']:
+ if old.get(u'license_title') != new.get(u'license_title'):
_license_change(change_list, old, new)
# if the name of the dataset has changed
# this is only visible to the user via the dataset's URL,
# so display the change using that
- if old['name'] != new['name']:
+ if old.get(u'name') != new.get(u'name'):
_name_change(change_list, old, new)
# if the source URL (metadata value, not the actual URL of the dataset)
# has changed
- if old['url'] != new['url']:
+ if old.get(u'url') != new.get(u'url'):
_url_change(change_list, old, new)
# if the user-provided version has changed
- if old['version'] != new['version']:
+ if old.get(u'version') != new.get(u'version'):
_version_change(change_list, old, new)
# check whether fields added by extensions or custom fields
@@ -374,9 +375,9 @@ def _title_change(change_list, old, new):
Appends a summary of a change to a dataset's title between two versions
(old and new) to change_list.
'''
- change_list.append({u'type': u'title', u'id': new['name'],
- u'new_title': new['title'],
- u'old_title': old['title']})
+ change_list.append({u'type': u'title', u'id': new.get(u'name'),
+ u'new_title': new.get(u'title'),
+ u'old_title': old.get(u'title')})
def _org_change(change_list, old, new):
@@ -386,34 +387,35 @@ def _org_change(change_list, old, new):
'''
# if both versions belong to an organization
- if old['owner_org'] and new['owner_org']:
+ if old.get(u'owner_org') and new.get(u'owner_org'):
change_list.append({u'type': u'org',
u'method': u'change',
- u'pkg_id': new['id'],
- u'title': new['title'],
- u'old_org_id': old['organization']['id'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
+ u'old_org_id': old.get(u'organization').get(u'id'),
u'old_org_title':
- old['organization']['title'],
- u'new_org_id': new['organization']['id'],
- u'new_org_title': new['organization']['title']})
+ old.get(u'organization').get(u'title'),
+ u'new_org_id': new.get(u'organization').get(u'id'),
+ u'new_org_title':
+ new.get(u'organization').get(u'title')})
# if the dataset was not in an organization before and it is now
- elif not old['owner_org'] and new['owner_org']:
+ elif not old.get(u'owner_org') and new.get(u'owner_org'):
change_list.append({u'type': u'org',
u'method': u'add',
- u'pkg_id': new['id'],
- u'title': new['title'],
- u'new_org_id': new['organization']['id'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
+ u'new_org_id': new.get(u'organization').get(u'id'),
u'new_org_title':
- new['organization']['title']})
+ new.get(u'organization').get(u'title')})
# if the user removed the organization
else:
change_list.append({u'type': u'org',
u'method': u'remove',
- u'pkg_id': new['id'],
- u'title': new['title'],
- u'old_org_id': old['organization']['id'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
+ u'old_org_id': old.get(u'organization').get(u'id'),
u'old_org_title':
- old['organization']['title']})
+ old.get(u'organization').get(u'title')})
def _maintainer_change(change_list, old, new):
@@ -422,22 +424,22 @@ def _maintainer_change(change_list, old, new):
versions (old and new) to change_list.
'''
# if the old dataset had a maintainer
- if old['maintainer'] and new['maintainer']:
+ if old.get(u'maintainer') and new.get(u'maintainer'):
change_list.append({u'type': u'maintainer', u'method': u'change',
- u'pkg_id': new['id'],
- u'title': new['title'], u'new_maintainer':
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'), u'new_maintainer':
new['maintainer'], u'old_maintainer':
old['maintainer']})
# if they removed the maintainer
- elif not new['maintainer']:
+ elif not new.get(u'maintainer'):
change_list.append({u'type': u'maintainer', u'pkg_id':
- new['id'], u'title': new['title'],
+ new.get(u'id'), u'title': new.get(u'title'),
u'method': u'remove'})
# if there wasn't one there before
else:
change_list.append({u'type': u'maintainer', u'pkg_id':
- new['id'], u'title': new['title'],
- u'new_maintainer': new['maintainer'],
+ new.get(u'id'), u'title': new.get(u'title'),
+ u'new_maintainer': new.get(u'maintainer'),
u'method': u'add'})
@@ -447,23 +449,25 @@ def _maintainer_email_change(change_list, old, new):
field between two versions (old and new) to change_list.
'''
# if the old dataset had a maintainer email
- if old['maintainer_email'] and new['maintainer_email']:
+ if old.get(u'maintainer_email') and new.get(u'maintainer_email'):
change_list.append({u'type': u'maintainer_email', u'pkg_id':
- new['id'], u'title': new['title'],
- u'new_maintainer_email': new['maintainer_email'],
+ new.get(u'id'), u'title': new.get(u'title'),
+ u'new_maintainer_email':
+ new.get(u'maintainer_email'),
u'old_maintainer_email':
- old['maintainer_email'],
+ old.get(u'maintainer_email'),
u'method': u'change'})
# if they removed the maintainer email
- elif not new['maintainer_email']:
+ elif not new.get(u'maintainer_email'):
change_list.append({u'type': u'maintainer_email', u'pkg_id':
- new['id'], u'title': new['title'],
+ new.get(u'id'), u'title': new.get(u'title'),
u'method': u'remove'})
# if there wasn't one there before e
else:
change_list.append({u'type': u'maintainer_email', u'pkg_id':
- new['id'], u'title': new['title'],
- u'new_maintainer_email': new['maintainer_email'],
+ new.get(u'id'), u'title': new.get(u'title'),
+ u'new_maintainer_email':
+ new.get(u'maintainer_email'),
u'method': u'add'})
@@ -473,20 +477,21 @@ def _author_change(change_list, old, new):
versions (old and new) to change_list.
'''
# if the old dataset had an author
- if old['author'] and new['author']:
- change_list.append({u'type': u'author', u'pkg_id': new['id'],
- u'title': new['title'], u'new_author':
- new['author'], u'old_author': old['author'],
+ if old.get(u'author') and new.get(u'author'):
+ change_list.append({u'type': u'author', u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'), u'new_author':
+ new.get(u'author'), u'old_author':
+ old.get(u'author'),
u'method': u'change'})
# if they removed the author
- elif not new['author']:
- change_list.append({u'type': u'author', u'pkg_id': new['id'],
- u'title': new['title'], u'method': u'remove'})
+ elif not new.get(u'author'):
+ change_list.append({u'type': u'author', u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'), u'method': u'remove'})
# if there wasn't one there before
else:
- change_list.append({u'type': u'author', u'pkg_id': new['id'],
- u'title': new['title'], u'new_author':
- new['author'], u'method': u'add'})
+ change_list.append({u'type': u'author', u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'), u'new_author':
+ new.get(u'author'), u'method': u'add'})
def _author_email_change(change_list, old, new):
@@ -494,22 +499,22 @@ def _author_email_change(change_list, old, new):
Appends a summary of a change to a dataset's author e-mail address field
between two versions (old and new) to change_list.
'''
- if old['author_email'] and new['author_email']:
+ if old.get(u'author_email') and new.get(u'author_email'):
change_list.append({u'type': u'author_email', u'pkg_id':
- new['id'], u'title': new['title'],
- u'new_author_email': new['author_email'],
- u'old_author_email': old['author_email'],
+ new.get(u'id'), u'title': new.get(u'title'),
+ u'new_author_email': new.get(u'author_email'),
+ u'old_author_email': old.get(u'author_email'),
u'method': u'change'})
# if they removed the author
- elif not new['author_email']:
+ elif not new.get(u'author_email'):
change_list.append({u'type': u'author_email', u'pkg_id':
- new['id'], u'title': new['title'],
+ new.get(u'id'), u'title': new.get(u'title'),
u'method': u'remove'})
# if there wasn't one there before
else:
change_list.append({u'type': u'author_email', u'pkg_id':
- new['id'], u'title': new['title'],
- u'new_author_email': new['author_email'],
+ new.get(u'id'), u'title': new.get(u'title'),
+ u'new_author_email': new.get(u'author_email'),
u'method': u'add'})
@@ -519,20 +524,21 @@ def _notes_change(change_list, old, new):
versions (old and new) to change_list.
'''
# if the old dataset had a description
- if old['notes'] and new['notes']:
+ if old.get(u'notes') and new.get(u'notes'):
change_list.append({u'type': u'notes', u'pkg_id':
- new['id'], u'title': new['title'],
- u'new_notes': new['notes'],
- u'old_notes': old['notes'],
+ new.get(u'id'), u'title': new.get(u'title'),
+ u'new_notes': new.get(u'notes'),
+ u'old_notes': old.get(u'notes'),
u'method': u'change'})
- elif not new['notes']:
+ elif not new.get(u'notes'):
change_list.append({u'type': u'notes', u'pkg_id':
- new['id'], u'title': new['title'],
+ new.get(u'id'), u'title': new.get(u'title'),
u'method': u'remove'})
else:
change_list.append({u'type': u'notes', u'pkg_id':
- new['id'], u'title': new['title'],
- u'new_notes': new['notes'], u'method': u'add'})
+ new.get(u'id'), u'title': new.get(u'title'),
+ u'new_notes': new.get(u'notes'),
+ u'method': u'add'})
def _tag_change(change_list, new_tags, old_tags, new):
@@ -544,25 +550,25 @@ def _tag_change(change_list, new_tags, old_tags, new):
deleted_tags_list = list(deleted_tags)
if len(deleted_tags) == 1:
change_list.append({u'type': u'tags', u'method': u'remove_one',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'tag': deleted_tags_list[0]})
elif len(deleted_tags) > 1:
change_list.append({u'type': u'tags', u'method': u'remove_multiple',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'tags': deleted_tags_list})
added_tags = new_tags - old_tags
added_tags_list = list(added_tags)
if len(added_tags) == 1:
change_list.append({u'type': u'tags', u'method': u'add_one', u'pkg_id':
- new['id'], u'title': new['title'],
+ new.get(u'id'), u'title': new.get(u'title'),
u'tag': added_tags_list[0]})
elif len(added_tags) > 1:
change_list.append({u'type': u'tags', u'method': u'add_multiple',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'tags': added_tags_list})
@@ -578,12 +584,12 @@ def _license_change(change_list, old, new):
old_license_url = old['license_url']
if u'license_url' in new and new['license_url']:
new_license_url = new['license_url']
- change_list.append({u'type': u'license', u'pkg_id': new['id'],
- u'title': new['title'],
+ change_list.append({u'type': u'license', u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'old_url': old_license_url,
u'new_url': new_license_url, u'new_title':
- new['license_title'], u'old_title':
- old['license_title']})
+ new.get(u'license_title'), u'old_title':
+ old.get(u'license_title')})
def _name_change(change_list, old, new):
@@ -592,9 +598,9 @@ def _name_change(change_list, old, new):
can be accessed at) between two versions (old and new) to
change_list.
'''
- change_list.append({u'type': u'name', u'pkg_id': new['id'],
- u'title': new['title'], u'old_name':
- old['name'], u'new_name': new['name']})
+ change_list.append({u'type': u'name', u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'), u'old_name':
+ old.get(u'name'), u'new_name': new.get(u'name')})
def _url_change(change_list, old, new):
@@ -604,23 +610,23 @@ def _url_change(change_list, old, new):
new) to change_list.
'''
# if both old and new versions have source URLs
- if old['url'] and new['url']:
+ if old.get(u'url') and new.get(u'url'):
change_list.append({u'type': u'url', u'method': u'change',
- u'pkg_id': new['id'], u'title':
- new['title'], u'new_url': new['url'],
- u'old_url': old['url']})
+ u'pkg_id': new.get(u'id'), u'title':
+ new.get(u'title'), u'new_url': new.get(u'url'),
+ u'old_url': old.get(u'url')})
# if the user removed the source URL
- elif not new['url']:
+ elif not new.get(u'url'):
change_list.append({u'type': u'url', u'method': u'remove',
- u'pkg_id': new['id'],
- u'title': new['title'],
- u'old_url': old['url']})
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
+ u'old_url': old.get(u'url')})
# if there wasn't one there before
else:
change_list.append({u'type': u'url', u'method': u'add',
- u'pkg_id': new['id'],
- u'title': new['title'],
- u'new_url': new['url']})
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
+ u'new_url': new.get(u'url')})
def _version_change(change_list, old, new):
@@ -630,23 +636,24 @@ def _version_change(change_list, old, new):
and new) to change_list.
'''
# if both old and new versions have version numbers
- if old['version'] and new['version']:
+ if old.get(u'version') and new.get(u'version'):
change_list.append({u'type': u'version', u'method': u'change',
- u'pkg_id': new['id'], u'title':
- new['title'], u'old_version':
- old['version'], u'new_version':
- new['version']})
+ u'pkg_id': new.get(u'id'), u'title':
+ new.get(u'title'), u'old_version':
+ old.get(u'version'), u'new_version':
+ new.get(u'version')})
# if the user removed the version number
- elif not new['version']:
+ elif not new.get(u'version'):
change_list.append({u'type': u'version', u'method': u'remove',
- u'pkg_id': new['id'],
- u'title': new['title']})
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
+ u'old_version': old.get(u'version')})
# if there wasn't one there before
else:
change_list.append({u'type': u'version', u'method': u'add',
- u'pkg_id': new['id'],
- u'title': new['title'],
- u'new_version': new['version']})
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
+ u'new_version': new.get(u'version')})
def _extension_fields(change_list, old, new):
@@ -694,12 +701,12 @@ def _extension_fields(change_list, old, new):
# if additional fields have been changed
addl_fields_list = list(addl_fields)
for field in addl_fields_list:
- if old[field] != new[field]:
+ if old.get(field) != new.get(field):
change_list.append({u'type': u'extension_fields',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key': field,
- u'value': new[field]})
+ u'value': new.get(field)})
def _extra_fields(change_list, old, new):
@@ -709,13 +716,13 @@ def _extra_fields(change_list, old, new):
change_list.
'''
if u'extras' in new:
- extra_fields_new = _extras_to_dict(new['extras'])
+ extra_fields_new = _extras_to_dict(new.get(u'extras'))
extra_new_set = set(extra_fields_new.keys())
# if the old version has extra fields, we need
# to compare the new version's extras to the old ones
if u'extras' in old:
- extra_fields_old = _extras_to_dict(old['extras'])
+ extra_fields_old = _extras_to_dict(old.get(u'extras'))
extra_old_set = set(extra_fields_old.keys())
# if some fields were added
@@ -724,22 +731,22 @@ def _extra_fields(change_list, old, new):
if extra_fields_new[new_fields[0]]:
change_list.append({u'type': u'extra_fields',
u'method': u'add_one_value',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key': new_fields[0],
u'value':
extra_fields_new[new_fields[0]]})
else:
change_list.append({u'type': u'extra_fields',
u'method': u'add_one_no_value',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key': new_fields[0]})
elif len(new_fields) > 1:
change_list.append({u'type': u'extra_fields',
u'method': u'add_multiple',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key_list': new_fields,
u'value_list': extra_fields_new})
@@ -748,14 +755,14 @@ def _extra_fields(change_list, old, new):
if len(deleted_fields) == 1:
change_list.append({u'type': u'extra_fields',
u'method': u'remove_one',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key': deleted_fields[0]})
elif len(deleted_fields) > 1:
change_list.append({u'type': u'extra_fields',
u'method': u'remove_multiple',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key_list': deleted_fields})
# if some existing fields were changed
@@ -767,8 +774,8 @@ def _extra_fields(change_list, old, new):
change_list.append({u'type': u'extra_fields',
u'method':
u'change_with_old_value',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key': field,
u'old_value':
extra_fields_old[field],
@@ -777,8 +784,8 @@ def _extra_fields(change_list, old, new):
else:
change_list.append({u'type': u'extra_fields',
u'method': u'change_no_old_value',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key': field,
u'new_value':
extra_fields_new[field]})
@@ -791,23 +798,23 @@ def _extra_fields(change_list, old, new):
if extra_fields_new[new_fields[0]]:
change_list.append({u'type': u'extra_fields',
u'method': u'add_one_value',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key': new_fields[0],
u'value':
extra_fields_new[new_fields[0]]})
else:
change_list.append({u'type': u'extra_fields',
u'method': u'add_one_no_value',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key': new_fields[0]})
elif len(new_fields) > 1:
change_list.append({u'type': u'extra_fields',
u'method': u'add_multiple',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key_list': new_fields,
u'value_list': extra_fields_new})
@@ -816,12 +823,12 @@ def _extra_fields(change_list, old, new):
if len(deleted_fields) == 1:
change_list.append({u'type': u'extra_fields',
u'method': u'remove_one',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key': deleted_fields[0]})
elif len(deleted_fields) > 1:
change_list.append({u'type': u'extra_fields',
u'method': u'remove_multiple',
- u'pkg_id': new['id'],
- u'title': new['title'],
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
u'key_list': deleted_fields})
| diff --git a/ckan/tests/lib/test_changes.py b/ckan/tests/lib/test_changes.py
--- a/ckan/tests/lib/test_changes.py
+++ b/ckan/tests/lib/test_changes.py
@@ -816,3 +816,414 @@ def test_delete_multiple_resources(self):
else:
assert changes[0]["resource_name"] == u"Image 2"
assert changes[1]["resource_name"] == u"Image 1"
+
+
+class TestChangesWithSingleAttributes(object):
+
+ def test_title_added_when_it_does_not_exist(self):
+ changes = []
+ original = {}
+ new = {u'title': u"new title"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"title"
+ assert changes[0]["old_title"] is None
+ assert changes[0]["new_title"] == u"new title"
+
+ def test_title_changed(self):
+ changes = []
+ original = {u'title': u'old title'}
+ new = {u'title': u"new title"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"title"
+ assert changes[0]["old_title"] == u"old title"
+ assert changes[0]["new_title"] == u"new title"
+
+ def test_title_removed_with_non_existing(self):
+ changes = []
+ original = {u'title': u'old title'}
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"title"
+ assert changes[0]["old_title"] == u'old title'
+ assert changes[0]["new_title"] is None
+
+ def test_owner_org_added_when_it_does_not_exist(self):
+ changes = []
+ original = {}
+ new_org = {u'id': u'new_org_id'}
+ new = {u'owner_org': new_org['id'], u'organization': new_org}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"org"
+ assert changes[0]["method"] == u"add"
+ assert changes[0]["new_org_id"] == new_org['id']
+
+ def test_owner_org_changed(self):
+ changes = []
+ old_org = {u'id': u'old_org_id'}
+ original = {u'owner_org': old_org['id'], u'organization': old_org}
+ new_org = {u'id': u'new_org_id'}
+ new = {u'owner_org': new_org['id'], u'organization': new_org}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"org"
+ assert changes[0]["method"] == u"change"
+ assert changes[0]["old_org_id"] == old_org['id']
+ assert changes[0]["new_org_id"] == new_org['id']
+
+ def test_owner_org_removed_with_non_existing(self):
+ changes = []
+ old_org = {u'id': u'org_id'}
+ original = {u'owner_org': old_org['id'], u'organization': old_org}
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"org"
+ assert changes[0]["method"] == u"remove"
+ assert changes[0]["old_org_id"] == old_org['id']
+
+ def test_maintainer_added_when_it_does_not_exist(self):
+ changes = []
+ original = {}
+ new = {u'maintainer': u"new maintainer"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"maintainer"
+ assert changes[0]["method"] == u"add"
+ assert changes[0]["new_maintainer"] == u"new maintainer"
+
+ def test_maintainer_changed(self):
+ changes = []
+ original = {u'maintainer': u"old maintainer"}
+ new = {u'maintainer': u"new maintainer"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"maintainer"
+ assert changes[0]["method"] == u"change"
+ assert changes[0]["new_maintainer"] == u"new maintainer"
+ assert changes[0]["old_maintainer"] == u"old maintainer"
+
+ def test_maintainer_removed_with_non_existing(self):
+ changes = []
+ original = {u'maintainer': u"old maintainer"}
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"maintainer"
+ assert changes[0]["method"] == u"remove"
+
+ def test_maintainer_email_added_when_it_does_not_exist(self):
+ changes = []
+ original = {}
+ new = {u'maintainer_email': u"[email protected]"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"maintainer_email"
+ assert changes[0]["method"] == u"add"
+ assert changes[0]["new_maintainer_email"] == u"[email protected]"
+
+ def test_maintainer_email_changed(self):
+ changes = []
+ original = {u'maintainer_email': u"[email protected]"}
+ new = {u'maintainer_email': u"[email protected]"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"maintainer_email"
+ assert changes[0]["method"] == u"change"
+ assert changes[0]["new_maintainer_email"] == u"[email protected]"
+ assert changes[0]["old_maintainer_email"] == u"[email protected]"
+
+ def test_maintainer_email_removed_with_non_existing(self):
+ changes = []
+ original = {u'maintainer_email': u"[email protected]"}
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"maintainer_email"
+ assert changes[0]["method"] == u"remove"
+
+ def test_author_added_when_it_does_not_exist(self):
+ changes = []
+ original = {}
+ new = {u'author': u"new author"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"author"
+ assert changes[0]["method"] == u"add"
+ assert changes[0]["new_author"] == u"new author"
+
+ def test_author_changed(self):
+ changes = []
+ original = {u'author': u"old author"}
+ new = {u'author': u"new author"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"author"
+ assert changes[0]["method"] == u"change"
+ assert changes[0]["new_author"] == u"new author"
+ assert changes[0]["old_author"] == u"old author"
+
+ def test_author_removed_with_non_existing(self):
+ changes = []
+ original = {u'author': u"old author"}
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"author"
+ assert changes[0]["method"] == u"remove"
+
+ def test_author_email_added_when_it_does_not_exist(self):
+ changes = []
+ original = {}
+ new = {u'author_email': u"[email protected]"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"author_email"
+ assert changes[0]["method"] == u"add"
+ assert changes[0]["new_author_email"] == u"[email protected]"
+
+ def test_author_email_changed(self):
+ changes = []
+ original = {u'author_email': u"[email protected]"}
+ new = {u'author_email': u"[email protected]"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"author_email"
+ assert changes[0]["method"] == u"change"
+ assert changes[0]["new_author_email"] == u"[email protected]"
+ assert changes[0]["old_author_email"] == u"[email protected]"
+
+ def test_author_email_removed_with_non_existing(self):
+ changes = []
+ original = {u'author_email': u"[email protected]"}
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"author_email"
+ assert changes[0]["method"] == u"remove"
+
+ def test_notes_added_when_it_does_not_exist(self):
+ changes = []
+ original = {}
+ new = {u'notes': u'new notes'}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"notes"
+ assert changes[0]["method"] == u"add"
+ assert changes[0]["new_notes"] == u"new notes"
+
+ def test_notes_changed(self):
+ changes = []
+ original = {u'notes': u'old notes'}
+ new = {u'notes': u'new notes'}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"notes"
+ assert changes[0]["method"] == u"change"
+ assert changes[0]["new_notes"] == u"new notes"
+ assert changes[0]["old_notes"] == u"old notes"
+
+ def test_notes_removed_with_non_existing(self):
+ changes = []
+ original = {u'notes': u'old notes'}
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert changes[0]["type"] == u"notes"
+ assert changes[0]["method"] == u"remove"
+
+ def test_tag_added_when_it_does_not_exist(self):
+ changes = []
+ original = {}
+ new = {u"tags": [{u"name": u"rivers"}]}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"tags"
+ assert changes[0]["method"] == u"add_one"
+ assert changes[0]["tag"] == u"rivers"
+
+ def test_multiple_tags_added_when_it_does_not_exist(self):
+ changes = []
+ original = {u"tags": [{u"name": u"rivers"}]}
+ new = {u"tags": [
+ {u"name": u"rivers"},
+ {u"name": u"oceans"},
+ {u"name": u"streams"},
+ ]}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"tags"
+ assert changes[0]["method"] == u"add_multiple"
+ assert set(changes[0]["tags"]) == set((u"oceans", u"streams"))
+
+ def test_tag_removed_with_non_existing(self):
+ changes = []
+ original = {u"tags": [{u"name": u"oceans"}]}
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"tags"
+ assert changes[0]["method"] == u"remove_one"
+ assert changes[0]["tag"] == u"oceans"
+
+ def test_multiple_tags_removed_with_non_existing(self):
+ changes = []
+ original = {u"tags": [
+ {u"name": u"rivers"},
+ {u"name": u"oceans"},
+ {u"name": u"streams"},
+ ]}
+
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"tags"
+ assert changes[0]["method"] == u"remove_multiple"
+ assert set(changes[0]["tags"]) == set((u"rivers", u"oceans", u"streams"))
+
+ def test_license_title_added_when_it_does_not_exist(self):
+ changes = []
+ original = {}
+ new = {u"license_title": u"new license"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"license"
+ assert changes[0]["new_title"] == u"new license"
+
+ def test_license_title_changed(self):
+ changes = []
+ original = {u"license_title": u"old license"}
+ new = {u"license_title": u"new license"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"license"
+ assert changes[0]["old_title"] == u"old license"
+ assert changes[0]["new_title"] == u"new license"
+
+ def test_license_title_removed_with_non_existing(self):
+ changes = []
+ original = {u"license_title": u"old license"}
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"license"
+ assert changes[0]["old_title"] == u"old license"
+ assert changes[0]["new_title"] is None
+
+ def test_url_added_when_it_does_not_exist(self):
+ changes = []
+ original = {}
+ new = {u'url': u'http://example.com'}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"url"
+ assert changes[0]["method"] == u"add"
+ assert changes[0]["new_url"] == u'http://example.com'
+
+ def test_url_changed(self):
+ changes = []
+ original = {u"url": u"http://example.com"}
+ new = {u"url": u"http://example.com/new"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"url"
+ assert changes[0]["method"] == u"change"
+ assert changes[0]["old_url"] == u"http://example.com"
+ assert changes[0]["new_url"] == u"http://example.com/new"
+
+ def test_url_removed_with_non_existing(self):
+ changes = []
+ original = {u"url": u"http://example.com"}
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"url"
+ assert changes[0]["method"] == u"remove"
+ assert changes[0]["old_url"] == u"http://example.com"
+
+ def test_version_added_when_it_does_not_exist(self):
+ changes = []
+ original = {}
+ new = {u'version': u'1'}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"version"
+ assert changes[0]["method"] == u"add"
+ assert changes[0]["new_version"] == u'1'
+
+ def test_version_changed(self):
+ changes = []
+ original = {u"version": u"1"}
+ new = {u"version": u"2"}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"version"
+ assert changes[0]["method"] == u"change"
+ assert changes[0]["old_version"] == u"1"
+ assert changes[0]["new_version"] == u"2"
+
+ def test_version_removed_with_non_existing(self):
+ changes = []
+ original = {u"version": u"1"}
+ new = {}
+
+ check_metadata_changes(changes, original, new)
+
+ assert len(changes) == 1, changes
+ assert changes[0]["type"] == u"version"
+ assert changes[0]["method"] == u"remove"
+ assert changes[0]["old_version"] == u"1"
| check_metadata_changes error when viewing changes
**CKAN version**
2.9
**Describe the bug**
`check_metadata_changes` errors out when trying to compare old values that do not exist for the old package when trying to view changes.
It assumes that several keys always have old values (e.g. owner_org, maintainer, maintainer_email, author, author_email, etc).
https://github.com/ckan/ckan/blob/6d3453396359c9fc401e4f60383ee1b7f9e05885/ckan/lib/changes.py#L298
**Steps to reproduce**
1. Create a minimal package using `package_create`, specifying just the required fields.
2. Update the package using the CKAN UI.
3. Try to view changes in Activity stream
**Expected behavior**
`check_metadata_changes` should handle `KeyErrors` gracefully when old values do not exist.
**Additional details**
```
2020-08-27 06:00:08,776 DEBUG [ckan.logic] check access OK - user_show user=jqnatividad
2020-08-27 06:00:08,779 DEBUG [ckan.logic] check access OK - dashboard_new_activities_count user=jqnatividad
2020-08-27 06:00:08,779 DEBUG [ckan.logic] check access OK - dashboard_activity_list user=jqnatividad
2020-08-27 06:00:08,829 DEBUG [ckan.logic] check access OK - user_show user=jqnatividad
2020-08-27 06:00:08,832 ERROR [ckan.config.middleware.flask_app] 'maintainer'
Traceback (most recent call last):
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/lib/ckan/default/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/views/dataset.py", line 1153, in changes
u'dataset_type': current_pkg_dict[u'type'],
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/lib/base.py", line 151, in render
return flask_render_template(template_name, **extra_vars)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/flask/templating.py", line 140, in render_template
ctx.app,
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/flask/templating.py", line 120, in _render
rv = template.render(context)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/jinja2/environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/templates/package/changes.html", line 1, in top-level template code
{% extends "package/base.html" %}
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/templates/package/base.html", line 4, in top-level template code
{% set dataset_type = dataset_type or pkg.type or 'dataset' %}
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/templates/page.html", line 1, in top-level template code
{% extends "base.html" %}
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/templates/base.html", line 106, in top-level template code
{%- block page %}{% endblock -%}
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/templates/page.html", line 19, in block "page"
{%- block content %}
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/templates/page.html", line 22, in block "content"
{% block main_content %}
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/templates/page.html", line 74, in block "main_content"
{% block primary %}
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/templates/package/changes.html", line 43, in block "primary"
{% snippet "package/snippets/change_item.html", activity_diff=activity_diffs[i], pkg_dict=pkg_dict %}
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/lib/jinja_extensions.py", line 274, in _call
return base.render_snippet(*args, **kwargs)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/lib/base.py", line 95, in render_snippet
output = render(template_name, extra_vars=kw)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/lib/base.py", line 151, in render
return flask_render_template(template_name, **extra_vars)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/flask/templating.py", line 140, in render_template
ctx.app,
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/flask/templating.py", line 120, in _render
rv = template.render(context)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/jinja2/environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/templates/package/snippets/change_item.html", line 3, in top-level template code
{% set changes = h.compare_pkg_dicts(activity_diff.activities[0].data.package, activity_diff.activities[1].data.package, activity_diff.activities[0].id) %}
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/lib/helpers.py", line 2849, in compare_pkg_dicts
check_metadata_changes(change_list, old, new)
File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/ckan-2.9.0-py2.7.egg/ckan/lib/changes.py", line 312, in check_metadata_changes
if old['maintainer'] != new['maintainer']:
KeyError: 'maintainer'
```
| **WORKAROUND:**
Was originally calling ``package_create`` using the ``ckanapi`` with the following parameters:
```
package=catalogSite.action.package_create(
name=tableName,
owner_org='test-org',
groups=[{'name': 'testgroup'}]
)
```
Got around the problem by setting optional parameters to an empty string:
```
package=catalogSite.action.package_create(
name=tableName,
maintainer='databot',
maintainer_email='',
owner_org='test-org',
groups=[{'name': 'testgroup'}],
notes='',
author='',
author_email='',
url=''
)
```
Minimum fix for these would be to change all indexes to get call so it would not fail to KeyError. Proper fix should contain handling for all the custom schemas as the developer might have added or removed fields from the schema. There is handling for extra fields but I'm not completely sure if the parameters are in extra fields after validation in custom schema
Hi @Zharktas, Just wanted to confirm that I was using a custom schema using scheming. For now, doing the minimum fix would be great! | 2020-09-01T17:02:48 |
ckan/ckan | 5,587 | ckan__ckan-5587 | [
"5586",
"5586"
] | 821c73cebc09689c4f68826ff61b22eaedec4366 | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -2840,7 +2840,7 @@ def license_options(existing_license_id=None):
license_ids.insert(0, existing_license_id)
return [
(license_id,
- register[license_id].title if license_id in register else license_id)
+ _(register[license_id].title) if license_id in register else license_id)
for license_id in license_ids]
diff --git a/ckan/model/license.py b/ckan/model/license.py
--- a/ckan/model/license.py
+++ b/ckan/model/license.py
@@ -141,8 +141,6 @@ def load_licenses(self, license_url):
for license in license_data:
if isinstance(license, string_types):
license = license_data[license]
- if license.get('title'):
- license['title'] = _(license['title'])
self._create_license_list(license_data, license_url)
def _create_license_list(self, license_data, license_url=''):
| Incorrectly Cached License Translations
**CKAN version**
2.8.5->master.
Probably introduced in #4594.
**Describe the bug**
ckan.models.license:LicenseRegister.load_licenses translates the license text, which is then cached as a classmember in the package class. (as called from ckan.lib.helpers.license_options)
This cache is for the lifetime of uwsgi process, not the request.
The license options should be translated at the helper or the template level, and not cached between multiple requests, unless the cache is keyed to the request language.
**Steps to reproduce**
On a site with multiple localizations, restart ckan to clear any caches, then request `/[lang]/dataset/edit/[name]` several times to make sure all wsgi processes have loaded the licenses.
Then visit ` `/en/dataset/edit/[name]` and the licenses will be in the previous localization.
**Expected behavior**
Each license popup would be rendered in the correct localization.
Incorrectly Cached License Translations
**CKAN version**
2.8.5->master.
Probably introduced in #4594.
**Describe the bug**
ckan.models.license:LicenseRegister.load_licenses translates the license text, which is then cached as a classmember in the package class. (as called from ckan.lib.helpers.license_options)
This cache is for the lifetime of uwsgi process, not the request.
The license options should be translated at the helper or the template level, and not cached between multiple requests, unless the cache is keyed to the request language.
**Steps to reproduce**
On a site with multiple localizations, restart ckan to clear any caches, then request `/[lang]/dataset/edit/[name]` several times to make sure all wsgi processes have loaded the licenses.
Then visit ` `/en/dataset/edit/[name]` and the licenses will be in the previous localization.
**Expected behavior**
Each license popup would be rendered in the correct localization.
| 2020-09-07T14:57:36 |
||
ckan/ckan | 5,591 | ckan__ckan-5591 | [
"5588"
] | 878dbf6bf2a058de4efa0d8fce9b66e2ef5b7fa3 | diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py
--- a/ckan/logic/validators.py
+++ b/ckan/logic/validators.py
@@ -124,7 +124,7 @@ def natural_number_validator(value, context):
def is_positive_integer(value, context):
value = int_validator(value, context)
if value < 1:
- raise Invalid(_('Must be a postive integer'))
+ raise Invalid(_('Must be a positive integer'))
return value
def boolean_validator(value, context):
| Typo in is_positive_integer validator
**CKAN version**
2.9
**Describe the bug**
The validation error message is "Must be a postive integer"
https://github.com/ckan/ckan/blob/16164bd50d5f97225125d2af07b4331d2f3daa40/ckan/logic/validators.py#L127
**Expected behavior**
The error should read "Must be a positive integer"
| 2020-09-09T04:28:12 |
||
ckan/ckan | 5,604 | ckan__ckan-5604 | [
"5578"
] | 318966892a8cc1973940c0361f58b273b47531c9 | diff --git a/ckanext/datatablesview/blueprint.py b/ckanext/datatablesview/blueprint.py
--- a/ckanext/datatablesview/blueprint.py
+++ b/ckanext/datatablesview/blueprint.py
@@ -100,7 +100,7 @@ def ajax(resource_view_id):
def filtered_download(resource_view_id):
- params = json.loads(request.params[u'params'])
+ params = json.loads(request.form[u'params'])
resource_view = get_action(u'resource_view_show'
)(None, {
u'id': resource_view_id
@@ -132,14 +132,14 @@ def filtered_download(resource_view_id):
cols = [c for (c, v) in zip(cols, params[u'visible']) if v]
- h.redirect_to(
+ return h.redirect_to(
h.
url_for(u'datastore.dump', resource_id=resource_view[u'resource_id']) +
u'?' + urlencode({
u'q': search_text,
u'sort': u','.join(sort_list),
u'filters': json.dumps(filters),
- u'format': request.params[u'format'],
+ u'format': request.form[u'format'],
u'fields': u','.join(cols),
})
)
@@ -151,5 +151,5 @@ def filtered_download(resource_view_id):
datatablesview.add_url_rule(
u'/datatables/filtered-download/<resource_view_id>',
- view_func=filtered_download
+ view_func=filtered_download, methods=[u'POST']
)
| Download options in Datatables_view do not work
**CKAN version**
2.9
**Describe the bug**
Using datatables_view as a default resource view, which works well. Apart from the nicer UI and pagination, one benefit of the view is that you can download a filtered version of the resource (https://github.com/ckan/ckan/pull/4497). However, none of the datatables_view download buttons work to download the filtered data.
**Steps to reproduce**
1. Add a CSV resource to a dataset
2. Create a datatables resource view (labeled 'Table' in the resource view picklist)
3. Go to resource view and try to use the Download button for any format type
4. A 404 error page replaces the datatables control
| This sounds like a regression related to the URL generation for these endpoints since the move to flask. https://github.com/ckan/ckan/blob/878dbf6bf2a058de4efa0d8fce9b66e2ef5b7fa3/ckanext/datatablesview/templates/datatables/datatables_view.html#L48-L50 would be the place I would start looking. | 2020-09-15T15:22:27 |
|
ckan/ckan | 5,611 | ckan__ckan-5611 | [
"5602",
"5546"
] | 318966892a8cc1973940c0361f58b273b47531c9 | diff --git a/ckan/lib/navl/dictization_functions.py b/ckan/lib/navl/dictization_functions.py
--- a/ckan/lib/navl/dictization_functions.py
+++ b/ckan/lib/navl/dictization_functions.py
@@ -405,7 +405,7 @@ def unflatten(data):
'''
unflattened = {}
- convert_to_list = []
+ clean_lists = {}
for flattend_key in sorted(data.keys(), key=flattened_order_key):
current_pos = unflattened
@@ -414,8 +414,13 @@ def unflatten(data):
try:
current_pos = current_pos[key]
except IndexError:
- new_pos = {}
- current_pos.append(new_pos)
+ while True:
+ new_pos = {}
+ current_pos.append(new_pos)
+ if key < len(current_pos):
+ break
+ # skipped list indexes need to be removed before returning
+ clean_lists[id(current_pos)] = current_pos
current_pos = new_pos
except KeyError:
new_pos = []
@@ -423,6 +428,9 @@ def unflatten(data):
current_pos = new_pos
current_pos[flattend_key[-1]] = data[flattend_key]
+ for cl in clean_lists.values():
+ cl[:] = [i for i in cl if i]
+
return unflattened
diff --git a/ckan/logic/converters.py b/ckan/logic/converters.py
--- a/ckan/logic/converters.py
+++ b/ckan/logic/converters.py
@@ -26,24 +26,14 @@ def convert_to_extras(key, data, errors, context):
def convert_from_extras(key, data, errors, context):
- def remove_from_extras(data, idx):
- for key in sorted(data):
- if key[0] != 'extras' or key[1] < idx:
- continue
- if key[1] == idx:
- del data[key]
-
- # Following block required for unflattening extras with
- # "gaps" created sometimes by `convert_from_extra`
- # validator :
- #
- # {
- # ('extras', 0, 'key'): 'x',
- # ('extras', 2, 'key): 'y'
- # }
- if key[1] > idx:
- new_key = (key[0], key[1] - 1) + key[2:]
- data[new_key] = data.pop(key)
+ def remove_from_extras(data, key):
+ to_remove = []
+ for data_key, data_value in six.iteritems(data):
+ if (data_key[0] == 'extras'
+ and data_key[1] == key):
+ to_remove.append(data_key)
+ for item in to_remove:
+ del data[item]
for data_key, data_value in six.iteritems(data):
if (data_key[0] == 'extras'
| diff --git a/ckan/tests/legacy/lib/test_navl.py b/ckan/tests/legacy/lib/test_navl.py
--- a/ckan/tests/legacy/lib/test_navl.py
+++ b/ckan/tests/legacy/lib/test_navl.py
@@ -272,6 +272,22 @@ def test_flatten_deeper():
unflatten(flatten_dict(data)))
+def test_unflatten_regression():
+ fdata = {
+ (u"items", 0, u"name"): u"first",
+ (u"items", 0, u"value"): u"v1",
+ (u"items", 3, u"name"): u"second",
+ (u"items", 3, u"value"): u"v2",
+ }
+ expected = {
+ u"items": [
+ {u"name": u"first", u"value": u"v1"},
+ {u"name": u"second", u"value": u"v2"},
+ ],
+ }
+ assert unflatten(fdata) == expected, pformat(unflatten(fdata))
+
+
def test_simple():
schema = {
"name": [not_empty],
| Data Dictionary Update Bug
**CKAN version**
2.8
**Describe the bug**
Data dictionary not updating properly.
**Steps to reproduce**
Example of inputting labels and descriptions:

Output:

The description from the first field is being inputted into the description in the second field.
Which code is the logic of the editing of the field inputs? The front end code seems fine...
In addition, where in the postgresql database are the label and description being stored? I can't seem to find them.
Correctly unflatten extras
Fixes #5537 . Some degree of luck required for getting this error
One need `convert_from_extras` in order to reproduce it. Imagine dataset, created with following extras:
```python
package_create({..., extras=[
{'key': 'a', 'value': '1'},
{'key': 'b', 'value': '2'},
{'key': 'c', 'value': '3'},
], ...}).
```
After flattening it looks like
```python
{ ...,
('extras', 0, 'key'): 'a', ('extras', 0, 'value'): 1,
('extras', 1, 'key'): 'b', ('extras', 1, 'value'): 2,
('extras', 2, 'key'): 'c', ('extras', 2, 'value'): 3,
...}
```
If **only** `b` field have `convert_from_extras`, it will be converted to the following form with "gap" between **0** and **2**:
```python
{ ...,
('b',): 2,
('extras', 0, 'key'): 'a', ('extras', 0, 'value'): 1,
('extras', 2, 'key'): 'c', ('extras', 2, 'value'): 3,
...}
```
Afterward, [because of these lines](https://github.com/ckan/ckan/blob/master/ckan/lib/navl/dictization_functions.py#L416-L419) extra **2** will be unflattened into a broken form:
```python
{...,
"b": 2,
"extras": [
{'key': 'a', 'value': '1'},
{'key': 'c'},
{'value': '3'},
],
...}
```
Fixing this issue during unflattening will turn into an unnecessary complex block of code with a number of contradictory places, so I suggest "realigning" extras when they are updated by `convert_from_extras`. The example above will be converted to the following form when **b** property extracted from extras(the gap is fixed by shifting all the extras that follow this gap one position back):
```python
{ ...,
('b',): 2,
('extras', 0, 'key'): 'a', ('extras', 0, 'value'): 1,
('extras', 1, 'key'): 'c', ('extras', 1, 'value'): 3,
...}
```
| I found that its got to do with the way the data_dict is being stored. In /ckan/lib/default/src/ckan/ckanext/datastore/dictionary.html, under the dictionary method, I printed out the info, fields and data variables and found that the structure is slightly off.



As you can see, for the first 2 elements in the tuple, it will always have 1 missing label/notes sub element. I think the first two elements should be merged. Where can I change the structure of this tuple?
I think I am nearing the solution... I found out its due to the extra variable _id that always appear in a data table. How do I remove it?

This would help to fix the bug in Data Dictionary! Please advise :)
Resolved it. Added the following code lines to /ckan/lib/default/src/ckan/ckanext/datastore/controller.py

@debbielee1996 thank you for this, are you using 2.8.5? There was a change to unflatten in this release that might have caused this to break. we have a patch that works around the issue for extras https://github.com/ckan/ckan/pull/5546/files but this sounds like we should fix unflatten instead of chasing the bugs created in other parts of the code.
Hi wardi, I installed CKAN 2.8.5. Will the patch you mentioned resolve the unflatten issue? Additionally, do you know where I can view the stored data dictionary in the postgresql database? I can't seem to find it.
| 2020-09-21T18:51:23 |
ckan/ckan | 5,635 | ckan__ckan-5635 | [
"5595"
] | 933993ca2359e06c14d2fec3c83ee9dc59cd6939 | diff --git a/ckan/lib/mailer.py b/ckan/lib/mailer.py
--- a/ckan/lib/mailer.py
+++ b/ckan/lib/mailer.py
@@ -56,15 +56,13 @@ def _mail_recipient(recipient_name, recipient_email,
subject = Header(subject.encode('utf-8'), 'utf-8')
msg['Subject'] = subject
msg['From'] = _("%s <%s>") % (sender_name, mail_from)
- recipient = u"%s <%s>" % (recipient_name, recipient_email)
- msg['To'] = Header(recipient, 'utf-8')
+ msg['To'] = u"%s <%s>" % (recipient_name, recipient_email)
msg['Date'] = utils.formatdate(time())
msg['X-Mailer'] = "CKAN %s" % ckan.__version__
if reply_to and reply_to != '':
msg['Reply-to'] = reply_to
# Send the email using Python's smtplib.
- smtp_connection = smtplib.SMTP()
if 'smtp.test_server' in config:
# If 'smtp.test_server' is configured we assume we're running tests,
# and don't use the smtp.server, starttls, user, password etc. options.
@@ -80,11 +78,12 @@ def _mail_recipient(recipient_name, recipient_email,
smtp_password = config.get('smtp.password')
try:
- smtp_connection.connect(smtp_server)
- except socket.error as e:
+ smtp_connection = smtplib.SMTP(smtp_server)
+ except (socket.error, smtplib.SMTPConnectError) as e:
log.exception(e)
raise MailerException('SMTP server could not be connected to: "%s" %s'
% (smtp_server, e))
+
try:
# Identify ourselves and prompt the server for supported features.
smtp_connection.ehlo()
| mailer python 3.8.5 issue.
**CKAN version**
2.9.0
**Describe the bug**
This bug appears when trying to use mailer with tls protocol turned on in python 3.8.5. All I'm trying to use the mailer package to email something in the background worker. It seems to be an issue related to smtplib build into python where the connect does not set the object variable _host in teh SMTP class. We need to do this right at the instantiation in order to set this variable in order for the starttls function to work. This doesn't seem to be an issue with Python 2.7 but is an issue in Python 3.8.5
**Steps to reproduce**
Steps to reproduce the behavior:
my module has similar to following
import ckan.lib.mailer as mailer
try:
# send email
email = {'recipient_name': recipient['display_name'],
'recipient_email': recipient['email'],
'subject': email_dict['subject'],
'body': email_dict['body'],
# 'headers': {'header1': 'value1'}
}
mailer.mail_recipient(**email)
except mailer.MailerException as e:
raise
I recommend we simply move line 68 to line 84 on file ckan/lib/mailer.py, but pass the first argument as the host name right there. Also to catch SMTPConnectError as well.
**Expected behavior**
A clear and concise description of what you expected to happen.
I expected to successfully start tls and run the code above.
**Additional details**
Traceback (most recent call last):
File "/Users/shasan/PycharmProjects/ckan/ckan/lib/mailer.py", line 97, in _mail_recipient
smtp_connection.starttls()
File "/Users/shasan/.pyenv/versions/3.8.5/lib/python3.8/smtplib.py", line 774, in starttls
self.sock = context.wrap_socket(self.sock,
File "/Users/shasan/.pyenv/versions/3.8.5/lib/python3.8/ssl.py", line 500, in wrap_socket
return self.sslsocket_class._create(
File "/Users/shasan/.pyenv/versions/3.8.5/lib/python3.8/ssl.py", line 1031, in _create
self._sslobj = self._context._wrap_socket(
ValueError: server_hostname cannot be an empty string or start with a leading dot.
| Also the line "msg['To'] = Header(recipient, 'utf-8') causes issues as the to address is urlencoded in python 3.8.5. I used the line right above as the value instead as a fix. | 2020-10-01T16:51:27 |
|
ckan/ckan | 5,639 | ckan__ckan-5639 | [
"5632"
] | 2e8f8f9c7342d7239a023f16cd1b43c12ff1e2cc | diff --git a/ckan/cli/server.py b/ckan/cli/server.py
--- a/ckan/cli/server.py
+++ b/ckan/cli/server.py
@@ -5,8 +5,8 @@
import click
from werkzeug.serving import run_simple
-from ckan.common import config
import ckan.plugins.toolkit as tk
+from ckan.common import config
log = logging.getLogger(__name__)
@@ -14,7 +14,8 @@
@click.command(u"run", short_help=u"Start development server")
@click.option(u"-H", u"--host", default=u"localhost", help=u"Set host")
@click.option(u"-p", u"--port", default=5000, help=u"Set port")
[email protected](u"-r", u"--reloader", default=True, help=u"Use reloader")
[email protected](u"-r", u"--disable-reloader", is_flag=True,
+ help=u"Disable reloader")
@click.option(
u"-t", u"--threaded", is_flag=True,
help=u"Handle each request in a separate thread"
@@ -25,8 +26,9 @@
help=u"Maximum number of concurrent processes"
)
@click.pass_context
-def run(ctx, host, port, reloader, threaded, extra_files, processes):
+def run(ctx, host, port, disable_reloader, threaded, extra_files, processes):
u"""Runs the Werkzeug development server"""
+ use_reloader = not disable_reloader
threaded = threaded or tk.asbool(config.get(u"ckan.devserver.threaded"))
processes = processes or tk.asint(
config.get(u"ckan.devserver.multiprocess", 1)
@@ -48,7 +50,7 @@ def run(ctx, host, port, reloader, threaded, extra_files, processes):
host,
port,
ctx.obj.app,
- use_reloader=reloader,
+ use_reloader=use_reloader,
use_evalex=True,
threaded=threaded,
processes=processes,
| No way to disable reloader when starting the development server
**CKAN version**
2.9.0
**Describe the bug**
When trying to start the development server without a reloader i encountered problems with the `--reloader` argument.
The reloader option requires a TEXT argument, therefore i expected that --reloader False disables the reloader.
**Steps to reproduce**
Start ckan with following command:
`ckan -c [PATH_TO_CONFIG] run --host 0.0.0.0 --reloader False`
**Expected behavior**
Server starts without reloader
**Additional details**
Currently the `reloader` option is passed as string and if it's not provided it defaults to the boolean value `True`
So we have two cases when the `run_simple` method is called:
1. `--reloader` argument is not provided --> reloader=True
2. `--reloader` argument is provided --> some string is passed as reloader argument to the `run_simple` method, which evaluates to true in the if statement distinguishing whether the reloader should be used or not.
So the `--reloader` argument does not affect anything.
_My suggestion:_ rename the argument to `disable-reloader` and turn it into a boolean flag. This enables the user to disable the reloader and the default behaviour (i.e. the dev server starts with a reloader) stays the same.
| 2020-10-02T09:27:47 |
||
ckan/ckan | 5,643 | ckan__ckan-5643 | [
"5565"
] | 2e8f8f9c7342d7239a023f16cd1b43c12ff1e2cc | diff --git a/ckanext/example_theme_docs/v16_initialize_a_javascript_module/plugin.py b/ckanext/example_theme_docs/v16_initialize_a_javascript_module/plugin.py
--- a/ckanext/example_theme_docs/v16_initialize_a_javascript_module/plugin.py
+++ b/ckanext/example_theme_docs/v16_initialize_a_javascript_module/plugin.py
@@ -13,4 +13,4 @@ class ExampleThemePlugin(plugins.SingletonPlugin):
def update_config(self, config):
toolkit.add_template_directory(config, 'templates')
- toolkit.add_resource('fanstatic', 'example_theme')
+ toolkit.add_resource('assets', 'example_theme')
diff --git a/ckanext/example_theme_docs/v22_fanstatic_and_webassets/plugin.py b/ckanext/example_theme_docs/v22_fanstatic_and_webassets/plugin.py
--- a/ckanext/example_theme_docs/v22_fanstatic_and_webassets/plugin.py
+++ b/ckanext/example_theme_docs/v22_fanstatic_and_webassets/plugin.py
@@ -37,12 +37,12 @@ def update_config(self, config):
# that CKAN will use this plugin's custom static files.
toolkit.add_public_directory(config, u'public')
- # Register this plugin's fanstatic directory with CKAN.
- # Here, 'fanstatic' is the path to the fanstatic directory
+ # Register this plugin's assets directory with CKAN.
+ # Here, 'assets' is the path to the webassets directory
# (relative to this plugin.py file), and 'example_theme' is the name
# that we'll use to refer to this fanstatic directory from CKAN
# templates.
- toolkit.add_resource(u'fanstatic', u'example_theme')
+ toolkit.add_resource(u'assets', u'example_theme')
def get_helpers(self):
u'''Register the most_popular_groups() function above as a template
diff --git a/contrib/cookiecutter/ckan_extension/{{cookiecutter.project}}/ckanext/{{cookiecutter.project_shortname}}/plugin.py b/contrib/cookiecutter/ckan_extension/{{cookiecutter.project}}/ckanext/{{cookiecutter.project_shortname}}/plugin.py
--- a/contrib/cookiecutter/ckan_extension/{{cookiecutter.project}}/ckanext/{{cookiecutter.project_shortname}}/plugin.py
+++ b/contrib/cookiecutter/ckan_extension/{{cookiecutter.project}}/ckanext/{{cookiecutter.project_shortname}}/plugin.py
@@ -10,5 +10,5 @@ class {{ cookiecutter.plugin_class_name }}(plugins.SingletonPlugin):
def update_config(self, config_):
toolkit.add_template_directory(config_, 'templates')
toolkit.add_public_directory(config_, 'public')
- toolkit.add_resource('fanstatic',
+ toolkit.add_resource('assets',
'{{ cookiecutter.project_shortname }}')
| cookiecutter template "fanstatic" should be "assets"
**CKAN version**
2.9
**Describe the bug**
When creating a new extension using ``ckan generate extension``, a "fanstatic" directory is created.
**Expected behavior**
According to https://docs.ckan.org/en/2.9/theming/webassets.html, it should be "assets".
A fix would be to rename the "fanstatic" directory in https://github.com/ckan/ckan/tree/master/contrib/cookiecutter/ckan_extension/%7B%7Bcookiecutter.project%7D%7D/ckanext/%7B%7Bcookiecutter.project_shortname%7D%7D
| Also, the "assets" directory should probably contain an empty "webassets.yml" (took me some time to figure out this file is needed in CKAN 2.9).
@paulmueller @Zharktas @amercader , I have analyze this issue. When executing the command "ckan generate extension" , a new extension is created with "Fanstatic "directory is created in it. While the document https://docs.ckan.org/en/2.9/theming/webassets.html is for adding CSS and JavaScript to themes using Webassets in which "assets" directory is to be created by user as mentioned in step 1 and step 2 is for registering "assets" directory with CKAN. Please confirm my understanding.
@Gauravp-NEC I can confirm this.
Also, the Manifest.in file should have a *.yml in it, otherwise the assets will not be read by CKAN when the extension is installed with pip.
@paulmueller , I understood that Manifest.in file should have a *.yml in it. I am confused why "Fanstatic" should be "assets"? Fanstatic directory is created by CLI command "ckan generate extension" when creating a new extension while assets directory is to be created by user when adding CSS and JavaScript to themes using Webassets as mentioned in https://docs.ckan.org/en/2.9/theming/webassets.html .
As far as I understood it, webassets is the successor of fanstatic (compare to https://docs.ckan.org/en/2.8/theming/fanstatic.html).
Yes, fanstatic was replaced by webassets in ckan 2.9 as part of the effort of modernizing the codebase.
@paulmueller , I think fix to rename "fanstatic" directory is required in following locations as well:
1) https://github.com/ckan/ckan/tree/master/ckanext/example_theme_docs/v16_initialize_a_javascript_module
2) https://github.com/ckan/ckan/tree/master/ckanext/example_theme_docs/v17_popover
3) https://github.com/ckan/ckan/tree/master/ckanext/example_theme_docs/v18_snippet_api
4) https://github.com/ckan/ckan/tree/master/ckanext/example_theme_docs/v19_01_error
5) https://github.com/ckan/ckan/tree/master/ckanext/example_theme_docs/v19_02_error_handling
6) https://github.com/ckan/ckan/tree/master/ckanext/example_theme_docs/v20_pubsub
7) https://github.com/ckan/ckan/tree/master/ckanext/example_theme_docs/v21_custom_jquery_plugin
8) https://github.com/ckan/ckan/tree/master/ckanext/example_theme_docs/v22_fanstatic_and_webassets
Please let me know your opinion
@Zharktas I agree. These plugins have already been migrated to webassets in https://github.com/ckan/ckan/commit/645828f1385f282e8c6ff782fa1bcbec75c51447.
But renaming the "fanstatic" directories and updating the ``add_resource`` entries in the plugin.py files would put these examples in line with the current documentation.
@paulmueller , Directories can be rename by using the terminal. Below are the steps:
1) Clone your repository that you website is hosted on.
2) cd “repositoryname”
3) git mv “directoryname” “newdirectoryname”
4) git add .
5) git commit -m “message”
6) git push | 2020-10-05T05:34:53 |
|
ckan/ckan | 5,644 | ckan__ckan-5644 | [
"5620"
] | 2e8f8f9c7342d7239a023f16cd1b43c12ff1e2cc | diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py
--- a/ckan/logic/validators.py
+++ b/ckan/logic/validators.py
@@ -44,6 +44,8 @@ def owner_org_validator(key, data, errors, context):
model = context['model']
user = context['user']
user = model.User.get(user)
+ package = context.get('package')
+
if value == '':
if not authz.check_config_permission('create_unowned_dataset'):
raise Invalid(_('An organization must be provided'))
@@ -52,7 +54,6 @@ def owner_org_validator(key, data, errors, context):
if (authz.check_config_permission('allow_dataset_collaborators')
and not authz.check_config_permission('allow_collaborators_to_change_owner_org')):
- package = context.get('package')
if package and user and not user.sysadmin:
is_collaborator = authz.user_is_collaborator_on_dataset(
user.id, package.id, ['admin', 'editor'])
@@ -70,10 +71,14 @@ def owner_org_validator(key, data, errors, context):
if not group:
raise Invalid(_('Organization does not exist'))
group_id = group.id
- if not context.get(u'ignore_auth', False) and not(user.sysadmin or
- authz.has_user_permission_for_group_or_org(
- group_id, user.name, 'create_dataset')):
- raise Invalid(_('You cannot add a dataset to this organization'))
+
+ if not package or (package and package.owner_org != group_id):
+ # This is a new dataset or we are changing the organization
+ if not context.get(u'ignore_auth', False) and not(user.sysadmin or
+ authz.has_user_permission_for_group_or_org(
+ group_id, user.name, 'create_dataset')):
+ raise Invalid(_('You cannot add a dataset to this organization'))
+
data[key] = group_id
| diff --git a/ckan/tests/logic/action/test_create.py b/ckan/tests/logic/action/test_create.py
--- a/ckan/tests/logic/action/test_create.py
+++ b/ckan/tests/logic/action/test_create.py
@@ -588,6 +588,35 @@ def test_metadata_modified_is_set_to_utcnow_when_created(self):
assert (result['metadata_modified'] ==
datetime.datetime.utcnow().isoformat())
+ @pytest.mark.ckan_config('ckan.auth.allow_dataset_collaborators', True)
+ @pytest.mark.ckan_config('ckan.auth.allow_admin_collaborators', True)
+ @pytest.mark.parametrize('role', ['admin', 'editor'])
+ def test_collaborators_can_create_resources(self, role):
+
+ org1 = factories.Organization()
+ dataset = factories.Dataset(owner_org=org1['id'])
+
+ user = factories.User()
+
+ helpers.call_action(
+ 'package_collaborator_create',
+ id=dataset['id'], user_id=user['id'], capacity=role)
+
+ context = {
+ 'user': user['name'],
+ 'ignore_auth': False,
+
+ }
+
+ created_resource = helpers.call_action(
+ 'resource_create',
+ context=context,
+ package_id=dataset['id'],
+ name='created by collaborator',
+ url='https://example.com')
+
+ assert created_resource['name'] == 'created by collaborator'
+
@pytest.mark.usefixtures("clean_db", "with_request_context")
class TestMemberCreate(object):
diff --git a/ckan/tests/logic/action/test_delete.py b/ckan/tests/logic/action/test_delete.py
--- a/ckan/tests/logic/action/test_delete.py
+++ b/ckan/tests/logic/action/test_delete.py
@@ -35,6 +35,32 @@ def test_resource_delete(self):
res_obj = model.Resource.get(resource["id"])
assert res_obj.state == "deleted"
+ @pytest.mark.ckan_config('ckan.auth.allow_dataset_collaborators', True)
+ @pytest.mark.ckan_config('ckan.auth.allow_admin_collaborators', True)
+ @pytest.mark.parametrize('role', ['admin', 'editor'])
+ def test_collaborators_can_delete_resources(self, role):
+
+ org1 = factories.Organization()
+ dataset = factories.Dataset(owner_org=org1['id'])
+ resource = factories.Resource(package_id=dataset['id'])
+
+ user = factories.User()
+
+ helpers.call_action(
+ 'package_collaborator_create',
+ id=dataset['id'], user_id=user['id'], capacity=role)
+
+ context = {
+ 'user': user['name'],
+ 'ignore_auth': False,
+
+ }
+
+ created_resource = helpers.call_action(
+ 'resource_delete',
+ context=context,
+ id=resource['id'])
+
@pytest.mark.ckan_config("ckan.plugins", "image_view")
@pytest.mark.usefixtures("clean_db", "with_plugins", "with_request_context")
diff --git a/ckan/tests/logic/action/test_update.py b/ckan/tests/logic/action/test_update.py
--- a/ckan/tests/logic/action/test_update.py
+++ b/ckan/tests/logic/action/test_update.py
@@ -1694,6 +1694,34 @@ def test_mark_as_old_some_activities_by_a_followed_user(self):
@pytest.mark.ckan_config('ckan.auth.allow_dataset_collaborators', True)
class TestCollaboratorsUpdate(object):
+ @pytest.mark.ckan_config('ckan.auth.allow_admin_collaborators', True)
+ @pytest.mark.parametrize('role', ['admin', 'editor'])
+ def test_collaborators_can_update_resources(self, role):
+
+ org1 = factories.Organization()
+ dataset = factories.Dataset(owner_org=org1['id'])
+ resource = factories.Resource(package_id=dataset['id'])
+
+ user = factories.User()
+
+ helpers.call_action(
+ 'package_collaborator_create',
+ id=dataset['id'], user_id=user['id'], capacity=role)
+
+ context = {
+ 'user': user['name'],
+ 'ignore_auth': False,
+
+ }
+
+ updated_resource = helpers.call_action(
+ 'resource_update',
+ context=context,
+ id=resource['id'],
+ description='updated')
+
+ assert updated_resource['description'] == 'updated'
+
def test_collaborators_can_not_change_owner_org_by_default(self):
org1 = factories.Organization()
| Unable to add resource as a collaborator
**CKAN version**
2.9
**Describe the bug**
If a user is a collaborator on a dataset they cannot add resources to it
**Steps to reproduce**
As user A:
Create an organization owned dataset as user A
Add User B as a collaborator with editor access
As user B:
Try to add a resource to the dataset
**Expected behavior**
User B should be able to add / upload a resource to the dataset
**Observed behavior**
The action fails with message:
Owner org: You cannot add a dataset to this organization
**Additional details**
I dug into the error a bit and it appears to come from the owner_org_validator function. Looking at it, there is logic for collaborators in the function, but it only covers changing organizations. I also wonder if there is a reason much of this logic duplicates the package auth functions, and if by doing so it encumbers extensions that might desire to override auth functionality.
| 2020-10-05T10:18:25 |
|
ckan/ckan | 5,647 | ckan__ckan-5647 | [
"5568"
] | 2e8f8f9c7342d7239a023f16cd1b43c12ff1e2cc | diff --git a/ckan/cli/cli.py b/ckan/cli/cli.py
--- a/ckan/cli/cli.py
+++ b/ckan/cli/cli.py
@@ -36,6 +36,12 @@
log = logging.getLogger(__name__)
+_no_config_commands = [
+ [u'config-tool'],
+ [u'generate', u'config'],
+ [u'generate', u'extension'],
+]
+
class CkanCommand(object):
@@ -83,18 +89,20 @@ def _get_commands_from_entry_point(entry_point=u'ckan.click_command'):
def _init_ckan_config(ctx, param, value):
is_help = u'--help' in sys.argv
- no_config = len(sys.argv) > 1 and sys.argv[1] in (
- u'generate', u'config-tool')
+ no_config = False
+ if len(sys.argv) > 1:
+ for cmd in _no_config_commands:
+ if sys.argv[1:len(cmd) + 1] == cmd:
+ no_config = True
+ break
+ if no_config or is_help:
+ return
try:
ctx.obj = CkanCommand(value)
except CkanConfigurationException as e:
- # Some commands don't require the config loaded
- if no_config or is_help:
- return
- else:
- p.toolkit.error_shout(e)
- raise click.Abort()
+ p.toolkit.error_shout(e)
+ raise click.Abort()
if six.PY2:
ctx.meta["flask_app"] = ctx.obj.app.apps["flask_app"]._wsgi_app
| [Regression-2.9] Ckan Generate Config
**CKAN version**
2.9
**Describe the bug**
In ckan 2.9, ckan generate config does not make a config file that can then be immediately edited.
**Steps to reproduce**
In Ckan <= 2.8.5,
```
"$CKAN_HOME"/bin/paster make-config ckan "$CONFIG"
"$CKAN_HOME"/bin/paster --plugin=ckan config-tool "$CONFIG" \
"sqlalchemy.url = ${DATABASE_URL}" \
"solr_url = ${SOLR_URL}" \
"ckan.site_url = ${SITE_SCHEME}${SITE_HOST}" \
"ckan.redis.url = ${REDIS_URL}" \
...
```
worked, regardless of the database url.
In ckan 2.9:
```
"$CKAN_HOME"/bin/ckan generate config "$CONFIG"
"$CKAN_HOME"/bin/ckan config-tool "$CONFIG" \
"ckan.storage_path = /var/lib/ckan" \
"sqlalchemy.url = ${CKAN_DB_URL}"\
```
This fails, because the database is not reachable (and potentially the site url is not defined, IIRC)
**Expected behavior**
Either:
* Ckan generate config should provide the basic parameters required to run config-tool
* config-tool should be able to edit an incomplete ckan.ini file, by not attempting to contact the database, redis, or solr servers.
```
ckan generate config $CKAN_INI
ckan config-tool $CKAN_INI \
[options]
```
should work.
**Additional details**
If possible, please provide the full stack trace of the error raised, or add screenshots to help explain your problem.
This is my current work-around, which is ugly:
```
if [ ! -e "$CONFIG" ]; then
"$CKAN_HOME"/bin/ckan generate config "$CONFIG"
# site url can't be set with the config tool
perl -pi -e "s|^(ckan.site_url =)$|\1 ${SITE_SCHEME}${SITE_HOST}|;" $CONFIG
perl -pi -e "s|^#?(solr_url =).*$|\1 ${SOLR_URL}|;" $CONFIG
perl -pi -e "s|^#?(ckan.redis.url =).*|\1 ${REDIS_URL}|;" $CONFIG
# perl has issues with @db in the replacement
sed -i -e "s|^sqlalchemy.url =.*$|sqlalchemy.url = ${CKAN_DB_URL}|;" $CONFIG
fi
"$CKAN_HOME"/bin/ckan config-tool "$CONFIG" \
"ckan.storage_path = /var/lib/ckan" \
"sqlalchemy.url = ${CKAN_DB_URL}"\
"ckan.site_url = ${SITE_SCHEME}${SITE_HOST}" \
"solr_url = ${SOLR_URL}" \
```
| 2020-10-06T11:23:15 |
||
ckan/ckan | 5,654 | ckan__ckan-5654 | [
"5637"
] | 86e2529a764f3cf292c02742f0f259647a038e2a | diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py
--- a/ckan/logic/action/update.py
+++ b/ckan/logic/action/update.py
@@ -507,7 +507,7 @@ def package_revise(context, data_dict):
model.Session.rollback()
raise ValidationError([{k: [de.error]}])
- _check_access('package_revise', context, orig)
+ _check_access('package_revise', context, {"update": orig})
# future-proof return dict by putting package data under
# "package". We will want to return activity info
| diff --git a/ckan/tests/logic/action/test_update.py b/ckan/tests/logic/action/test_update.py
--- a/ckan/tests/logic/action/test_update.py
+++ b/ckan/tests/logic/action/test_update.py
@@ -1893,6 +1893,20 @@ def test_revise_resource_replace_all(self):
assert response['package']['resources'][0]['name'] == 'new name'
assert response['package']['resources'][0]['url'] == ''
+ def test_revise_normal_user(self):
+ user = factories.User()
+ org = factories.Organization(users=[{'name': user['id'], 'capacity': 'admin'}])
+ # make sure normal users can use package_revise
+ context = {'user': user['name'], 'ignore_auth': False}
+ ds = factories.Dataset(owner_org=org['id'])
+ response = helpers.call_action(
+ 'package_revise',
+ match={'id': ds['id']},
+ update={'notes': 'new notes'},
+ context=context,
+ )
+ assert response['package']['notes'] == 'new notes'
+
@pytest.mark.usefixtures("clean_db")
class TestUserPluginExtras(object):
| action package_revise does not properly call its auth function
**CKAN version**
2.9
**Describe the bug**
``package_revise`` via the CKAN API does not work (``INTERNAL SERVER ERROR``) if authorization is checked (as admin it works).
**Steps to reproduce**
Call ``package_revise`` from the API. I have no time to set up a minimal example. But I used python requests library.
**Expected behavior**
It works.
**Additional details**
The UWSGI server log says
```
2020-10-01 20:50:46,735 ERROR [ckan.views.api] 'update'
Traceback (most recent call last):
File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/../../views/api.py", line 291, in action
result = function(context, request_data)
File "/usr/lib/ckan/default/src/ckan/ckan/logic/__init__.py", line 473, in wrapped
result = _action(context, data_dict, **kw)
File "/usr/lib/ckan/default/src/ckan/ckan/logic/action/update.py", line 510, in package_revise
_check_access('package_revise', context, orig)
File "/usr/lib/ckan/default/src/ckan/ckan/logic/__init__.py", line 309, in check_access
logic_authorization = authz.is_authorized(action, context,
File "/usr/lib/ckan/default/src/ckan/ckan/authz.py", line 221, in is_authorized
return auth_function(context, data_dict)
File "/usr/lib/ckan/default/src/ckan/ckan/logic/auth/update.py", line 63, in package_revise
return authz.is_authorized('package_update', context, data_dict['update'])
KeyError: 'update'
```
**Proposed fix**
Changing this line: https://github.com/ckan/ckan/blob/2.9/ckan/logic/action/update.py#L510
```python
_check_access('package_revise', context, orig)
```
to
```python
_check_access('package_revise', context, {"update": orig})
```
resolves the issue for me. The problem is that the auth function expects the "update" key: https://github.com/ckan/ckan/blob/2.9/ckan/logic/auth/update.py#L63
I can create a PR unless you need further proof.
| 2020-10-07T15:58:02 |
|
ckan/ckan | 5,659 | ckan__ckan-5659 | [
"5638"
] | 06f959df41581d25b5b922987144c12e9bbd9b5d | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -18,12 +18,11 @@
import functools
from collections import defaultdict
-from paste.deploy import converters
import dominate.tags as dom_tags
from markdown import markdown
from bleach import clean as bleach_clean, ALLOWED_TAGS, ALLOWED_ATTRIBUTES
-from ckan.common import config, is_flask_request
+from ckan.common import asbool, config, is_flask_request
from flask import redirect as _flask_redirect
from flask import _request_ctx_stack
from flask import url_for as _flask_default_url_for
@@ -2892,7 +2891,7 @@ def clean_html(html):
core_helper(i18n.get_locales_dict)
core_helper(literal)
# Useful additions from the paste library.
-core_helper(converters.asbool)
+core_helper(asbool)
# Useful additions from the stdlib.
core_helper(urlencode)
core_helper(include_asset)
| diff --git a/ckan/tests/model/test_user.py b/ckan/tests/model/test_user.py
--- a/ckan/tests/model/test_user.py
+++ b/ckan/tests/model/test_user.py
@@ -82,9 +82,9 @@ def test_upgrade_from_sha_with_wrong_password_fails_to_upgrade(self):
def test_upgrade_from_pbkdf2_with_less_rounds(self):
"""set up a pbkdf key with less than the default rounds
- If the number of default_rounds is increased in a later version of
- passlib, ckan should upgrade the password hashes for people without
- involvement from users"""
+ If the number of default_rounds is increased in a later version of
+ passlib, ckan should upgrade the password hashes for people without
+ involvement from users"""
user = factories.User()
password = u"testpassword"
user_obj = model.User.by_name(user["name"])
| [Snyk] Security upgrade urllib3 from 1.25.8 to 1.25.9
<h3>Snyk has created this PR to fix one or more vulnerable packages in the `pip` dependencies of this project.</h3>
#### Changes included in this PR
- Changes to the following files to upgrade the vulnerable dependencies to a fixed version:
- requirements.txt
#### Vulnerabilities that will be fixed
##### By pinning:
Severity | Priority Score (*) | Issue | Upgrade | Breaking Change | Exploit Maturity
:-------------------------:|-------------------------|:-------------------------|:-------------------------|:-------------------------|:-------------------------
 | **671/1000** <br/> **Why?** Recently disclosed, Has a fix available, CVSS 7.7 | HTTP Header Injection <br/>[SNYK-PYTHON-URLLIB3-1014645](https://snyk.io/vuln/SNYK-PYTHON-URLLIB3-1014645) | `urllib3:` <br> `1.25.8 -> 1.25.9` <br> | No | No Known Exploit
(*) Note that the real score may have changed since the PR was raised.
Some vulnerabilities couldn't be fully fixed and so Snyk will still find them when the project is tested again. This may be because the vulnerability existed within more than one direct dependency, but not all of the effected dependencies could be upgraded.
Check the changes in this PR to ensure they won't cause issues with your project.
------------
**Note:** *You are seeing this because you or someone else with access to this repository has authorized Snyk to open fix PRs.*
For more information: <img src="https://api.segment.io/v1/pixel/track?data=eyJ3cml0ZUtleSI6InJyWmxZcEdHY2RyTHZsb0lYd0dUcVg4WkFRTnNCOUEwIiwiYW5vbnltb3VzSWQiOiIzYmUwODlhMy1iNTQ0LTRiMTktOTViNi05NGY5NTFiYmUzYzAiLCJldmVudCI6IlBSIHZpZXdlZCIsInByb3BlcnRpZXMiOnsicHJJZCI6IjNiZTA4OWEzLWI1NDQtNGIxOS05NWI2LTk0Zjk1MWJiZTNjMCJ9fQ==" width="0" height="0"/>
🧐 [View latest project report](https://app.snyk.io/org/wardi/project/7696de9f-5904-4fe5-8767-91ee8e4d2b04)
🛠 [Adjust project settings](https://app.snyk.io/org/wardi/project/7696de9f-5904-4fe5-8767-91ee8e4d2b04/settings)
📚 [Read more about Snyk's upgrade and patch logic](https://support.snyk.io/hc/en-us/articles/360003891078-Snyk-patches-to-fix-vulnerabilities)
[//]: # (snyk:metadata:{"prId":"3be089a3-b544-4b19-95b6-94f951bbe3c0","dependencies":[{"name":"urllib3","from":"1.25.8","to":"1.25.9"}],"packageManager":"pip","projectPublicId":"7696de9f-5904-4fe5-8767-91ee8e4d2b04","projectUrl":"https://app.snyk.io/org/wardi/project/7696de9f-5904-4fe5-8767-91ee8e4d2b04?utm_source=github&utm_medium=fix-pr","type":"auto","patch":[],"vulns":["SNYK-PYTHON-URLLIB3-1014645"],"upgrade":[],"isBreakingChange":false,"env":"prod","prType":"fix","templateVariants":["updated-fix-title","priorityScore"],"priorityScoreList":[671]})
| @pdelboca as `urllib3` is a `requests` requirement, let see if we can upgrade requests instead to a version that will bump urllib3.
The way we normally handle requirements update is:
1. Update the version on `requirements.in`
2. Run `pip-compile requirements.in -o requirements.txt` (you need to `pip install pip-tools` first)
3. Repeat the same process for `requirements.py2.in` and `requirements-py2.txt` (we'll get rid of these soon, but best to keep things consistent)
If the requests upgrade does not upgrade the urrlib3 version we'll update the `.txt` files directly but I don't think it will be necessary. | 2020-10-09T12:24:01 |
ckan/ckan | 5,668 | ckan__ckan-5668 | [
"5667"
] | 33b69235ab86e87ded07372dc3a93a76ef9a44c1 | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -881,6 +881,9 @@ def user_list(context, data_dict):
else_=model.User.fullname
)
)
+ elif order_by_field == 'number_created_packages' or order_by_field == 'fullname' \
+ or order_by_field == 'about' or order_by_field == 'sysadmin':
+ query = query.order_by(order_by_field, model.User.name)
else:
query = query.order_by(order_by_field)
| User list sorting by number_created_packages is not stable
**CKAN version**
master / python3
**Describe the bug**
Sometimes python3 builds fail on error when sorted user list is on different order than expected list, for example here https://app.circleci.com/pipelines/github/ckan/ckan/949/workflows/440c43de-7e94-4bc7-83b9-8c73903318dc/jobs/8525
If the build is rerun, it probably passes.
| It was agreed that there should be secondary sorting by user name, so it would be stable even with when package count is the same. | 2020-10-13T16:22:16 |
|
ckan/ckan | 5,699 | ckan__ckan-5699 | [
"5698"
] | ccc582d048b1e2d7ea602884c2d974ff363afce7 | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -53,23 +53,6 @@
_text = sqlalchemy.text
-def _filter_activity_by_user(activity_list, users=[]):
- '''
- Return the given ``activity_list`` but with activities from the specified
- users removed. The users parameters should be a list of ids.
-
- A *new* filtered list is returned, the given ``activity_list`` itself is
- not modified.
- '''
- if not len(users):
- return activity_list
- new_list = []
- for activity in activity_list:
- if activity.user_id not in users:
- new_list.append(activity)
- return new_list
-
-
def _activity_stream_get_filtered_users():
'''
Get the list of users from the :ref:`ckan.hide_activity_from_users` config
@@ -2499,10 +2482,8 @@ def user_activity_list(context, data_dict):
offset = data_dict.get('offset', 0)
limit = data_dict['limit'] # defaulted, limited & made an int by schema
- _activity_objects = model.activity.user_activity_list(
+ activity_objects = model.activity.user_activity_list(
user.id, limit=limit, offset=offset)
- activity_objects = _filter_activity_by_user(
- _activity_objects, _activity_stream_get_filtered_users())
return model_dictize.activity_list_dictize(
activity_objects, context,
@@ -2553,13 +2534,10 @@ def package_activity_list(context, data_dict):
offset = int(data_dict.get('offset', 0))
limit = data_dict['limit'] # defaulted, limited & made an int by schema
- _activity_objects = model.activity.package_activity_list(
- package.id, limit=limit, offset=offset)
- if not include_hidden_activity:
- activity_objects = _filter_activity_by_user(
- _activity_objects, _activity_stream_get_filtered_users())
- else:
- activity_objects = _activity_objects
+ activity_objects = model.activity.package_activity_list(
+ package.id, limit=limit, offset=offset,
+ include_hidden_activity=include_hidden_activity,
+ )
return model_dictize.activity_list_dictize(
activity_objects, context, include_data=data_dict['include_data'])
@@ -2608,13 +2586,10 @@ def group_activity_list(context, data_dict):
group_show = logic.get_action('group_show')
group_id = group_show(context, {'id': group_id})['id']
- _activity_objects = model.activity.group_activity_list(
- group_id, limit=limit, offset=offset)
- if not include_hidden_activity:
- activity_objects = _filter_activity_by_user(
- _activity_objects, _activity_stream_get_filtered_users())
- else:
- activity_objects = _activity_objects
+ activity_objects = model.activity.group_activity_list(
+ group_id, limit=limit, offset=offset,
+ include_hidden_activity=include_hidden_activity,
+ )
return model_dictize.activity_list_dictize(
activity_objects, context,
@@ -2662,13 +2637,10 @@ def organization_activity_list(context, data_dict):
org_show = logic.get_action('organization_show')
org_id = org_show(context, {'id': org_id})['id']
- _activity_objects = model.activity.organization_activity_list(
- org_id, limit=limit, offset=offset)
- if not include_hidden_activity:
- activity_objects = _filter_activity_by_user(
- _activity_objects, _activity_stream_get_filtered_users())
- else:
- activity_objects = _activity_objects
+ activity_objects = model.activity.organization_activity_list(
+ org_id, limit=limit, offset=offset,
+ include_hidden_activity=include_hidden_activity,
+ )
return model_dictize.activity_list_dictize(
activity_objects, context,
@@ -2698,12 +2670,9 @@ def recently_changed_packages_activity_list(context, data_dict):
data_dict['include_data'] = False
limit = data_dict['limit'] # defaulted, limited & made an int by schema
- _activity_objects = \
+ activity_objects = \
model.activity.recently_changed_packages_activity_list(
limit=limit, offset=offset)
- activity_objects = _filter_activity_by_user(
- _activity_objects,
- _activity_stream_get_filtered_users())
return model_dictize.activity_list_dictize(
activity_objects, context,
@@ -3216,13 +3185,11 @@ def dashboard_activity_list(context, data_dict):
# FIXME: Filter out activities whose subject or object the user is not
# authorized to read.
- _activity_tuple_objects = model.activity.dashboard_activity_list(
+ activity_objects = model.activity.dashboard_activity_list(
user_id, limit=limit, offset=offset)
- activity_tuple_list = _filter_activity_by_user(
- _activity_tuple_objects, _activity_stream_get_filtered_users())
activity_dicts = model_dictize.activity_list_dictize(
- activity_tuple_list, context)
+ activity_objects, context)
# Mark the new (not yet seen by user) activities.
strptime = datetime.datetime.strptime
diff --git a/ckan/model/activity.py b/ckan/model/activity.py
--- a/ckan/model/activity.py
+++ b/ckan/model/activity.py
@@ -15,6 +15,7 @@
text,
)
+from ckan.common import config
import ckan.model
from ckan.model import meta
from ckan.model import domain_object, types as _types
@@ -164,6 +165,9 @@ def user_activity_list(user_id, limit, offset):
'''
q = _user_activity_query(user_id, limit + offset)
+
+ q = _filter_activitites_from_users(q)
+
return _activities_at_offset(q, limit, offset)
@@ -177,7 +181,8 @@ def _package_activity_query(package_id):
return q
-def package_activity_list(package_id, limit, offset):
+def package_activity_list(
+ package_id, limit, offset, include_hidden_activity=False):
'''Return the given dataset (package)'s public activity stream.
Returns all activities about the given dataset, i.e. where the given
@@ -189,10 +194,14 @@ def package_activity_list(package_id, limit, offset):
'''
q = _package_activity_query(package_id)
+
+ if not include_hidden_activity:
+ q = _filter_activitites_from_users(q)
+
return _activities_at_offset(q, limit, offset)
-def _group_activity_query(group_id):
+def _group_activity_query(group_id, include_hidden_activity=False):
'''Return an SQLAlchemy query for all activities about group_id.
Returns a query for all activities whose object is either the group itself
@@ -242,10 +251,13 @@ def _group_activity_query(group_id):
)
)
+ if not include_hidden_activity:
+ q = _filter_activitites_from_users(q)
+
return q
-def _organization_activity_query(org_id):
+def _organization_activity_query(org_id, include_hidden_activity=False):
'''Return an SQLAlchemy query for all activities about org_id.
Returns a query for all activities whose object is either the org itself
@@ -278,11 +290,14 @@ def _organization_activity_query(org_id):
model.Activity.object_id == org_id
)
)
+ if not include_hidden_activity:
+ q = _filter_activitites_from_users(q)
return q
-def group_activity_list(group_id, limit, offset):
+def group_activity_list(group_id, limit, offset, include_hidden_activity=False):
+
'''Return the given group's public activity stream.
Returns activities where the given group or one of its datasets is the
@@ -293,11 +308,12 @@ def group_activity_list(group_id, limit, offset):
etc.
'''
- q = _group_activity_query(group_id)
+ q = _group_activity_query(group_id, include_hidden_activity)
return _activities_at_offset(q, limit, offset)
-def organization_activity_list(group_id, limit, offset):
+def organization_activity_list(
+ group_id, limit, offset, include_hidden_activity=False):
'''Return the given org's public activity stream.
Returns activities where the given org or one of its datasets is the
@@ -308,7 +324,7 @@ def organization_activity_list(group_id, limit, offset):
etc.
'''
- q = _organization_activity_query(group_id)
+ q = _organization_activity_query(group_id, include_hidden_activity)
return _activities_at_offset(q, limit, offset)
@@ -402,8 +418,12 @@ def dashboard_activity_list(user_id, limit, offset):
'''
q = _dashboard_activity_query(user_id, limit + offset)
+
+ q = _filter_activitites_from_users(q)
+
return _activities_at_offset(q, limit, offset)
+
def _changed_packages_activity_query():
'''Return an SQLAlchemy query for all changed package activities.
@@ -425,4 +445,37 @@ def recently_changed_packages_activity_list(limit, offset):
'''
q = _changed_packages_activity_query()
+
+ q = _filter_activitites_from_users(q)
+
return _activities_at_offset(q, limit, offset)
+
+
+def _filter_activitites_from_users(q):
+ '''
+ Adds a filter to an existing query object ot avoid activities from users
+ defined in :ref:`ckan.hide_activity_from_users` (defaults to the site user)
+ '''
+ users_to_avoid = _activity_stream_get_filtered_users()
+ if users_to_avoid:
+ q = q.filter(ckan.model.Activity.user_id.notin_(users_to_avoid))
+
+ return q
+
+
+def _activity_stream_get_filtered_users():
+ '''
+ Get the list of users from the :ref:`ckan.hide_activity_from_users` config
+ option and return a list of their ids. If the config is not specified,
+ returns the id of the site user.
+ '''
+ users = config.get('ckan.hide_activity_from_users')
+ if users:
+ users_list = users.split()
+ else:
+ from ckan.logic import get_action
+ context = {'ignore_auth': True}
+ site_user = get_action('get_site_user')(context)
+ users_list = [site_user.get('name')]
+
+ return ckan.model.User.user_ids_for_name_or_id(users_list)
| diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py
--- a/ckan/tests/controllers/test_package.py
+++ b/ckan/tests/controllers/test_package.py
@@ -1864,7 +1864,8 @@ def test_redirect_when_given_id(self, app):
assert response.headers['location'] == expected_url
def test_redirect_also_with_activity_parameter(self, app):
- dataset = factories.Dataset()
+ user = factories.User()
+ dataset = factories.Dataset(user=user)
activity = activity_model.package_activity_list(
dataset["id"], limit=1, offset=0
)[0]
diff --git a/ckan/tests/logic/action/test_get.py b/ckan/tests/logic/action/test_get.py
--- a/ckan/tests/logic/action/test_get.py
+++ b/ckan/tests/logic/action/test_get.py
@@ -3164,9 +3164,11 @@ def _create_bulk_package_activities(self, count):
dataset = factories.Dataset()
from ckan import model
+ user = factories.User()
+
objs = [
model.Activity(
- user_id=None,
+ user_id=user['id'],
object_id=dataset["id"],
activity_type=None,
data=None,
@@ -3396,9 +3398,10 @@ def test_delete_org_by_updating_state(self):
assert activities[0]["data"]["group"]["title"] == org["title"]
def _create_bulk_user_activities(self, count):
- user = factories.User()
from ckan import model
+ user = factories.User()
+
objs = [
model.Activity(
user_id=user["id"],
@@ -3613,9 +3616,11 @@ def _create_bulk_group_activities(self, count):
group = factories.Group()
from ckan import model
+ user = factories.User()
+
objs = [
model.Activity(
- user_id=None,
+ user_id=user['id'],
object_id=group["id"],
activity_type=None,
data=None,
@@ -3844,9 +3849,11 @@ def _create_bulk_org_activities(self, count):
org = factories.Organization()
from ckan import model
+ user = factories.User()
+
objs = [
model.Activity(
- user_id=None,
+ user_id=user['id'],
object_id=org["id"],
activity_type=None,
data=None,
@@ -4013,9 +4020,11 @@ def test_delete_dataset(self):
def _create_bulk_package_activities(self, count):
from ckan import model
+ user = factories.User()
+
objs = [
model.Activity(
- user_id=None,
+ user_id=user['id'],
object_id=None,
activity_type="new_package",
data=None,
| Activities dissappear from UI when internal processes are run by ignored users
**CKAN version**
2.0 onwards
**Describe the bug**
Activities shown on the organization or dashboard activity feed can suddenly disappear and show an empty list, eg:

to

Apparently the user didn't change anything on the frontend, and if you check the database, the activities are there.
The problem is how we handle the [`ckan.hide-activity-from-users`](https://docs.ckan.org/en/latest/maintaining/configuration.html#ckan-hide-activity-from-users) configuration option. This allows you to define the users that you don't want to show activities from. It defaults to the internal site user as this is generally used to perform bulk internal processes like harvesting and you don't want to flood the activity stream with their operations.
The problem is that we first get the relevant activities from the database and *then* filter these activities in Python based on the users in the config option:
https://github.com/ckan/ckan/blob/ccc582d048b1e2d7ea602884c2d974ff363afce7/ckan/logic/action/get.py#L2665-L2671
The default limit is 31 so if we had 6 initial activities that were visible and at some point the site user goes and eg imports 50 datasets, we will get the most recent 31 activities by the site user from the database, and filter them all out so the none will be shown in the UI.
I could not find any reason for this filter to not be applied at the database query level, which is going to be more performant anyway.
**Steps to reproduce**
Steps to reproduce the behavior:
* Create an organization
* Perform some actions, eg update the org, create a dataset
* Run a harvester, or create more than 30 datasets using the site user API key (or the key of a user listed in `ckan.hide-activity-from-users`)
**Expected behavior**
Activities should not disappear
| 2020-10-28T14:49:04 |
|
ckan/ckan | 5,707 | ckan__ckan-5707 | [
"5705"
] | c44096e64e4ff0c98c79c9ad445b48c0750c331e | diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py
--- a/ckan/logic/action/update.py
+++ b/ckan/logic/action/update.py
@@ -655,7 +655,7 @@ def _group_or_org_update(context, data_dict, is_org=False):
except AttributeError:
schema = group_plugin.form_to_db_schema()
- upload = uploader.get_uploader('group', group.image_url)
+ upload = uploader.get_uploader('group')
upload.update_data_dict(data_dict, 'image_url',
'image_upload', 'clear_upload')
| diff --git a/ckan/tests/logic/action/test_update.py b/ckan/tests/logic/action/test_update.py
--- a/ckan/tests/logic/action/test_update.py
+++ b/ckan/tests/logic/action/test_update.py
@@ -467,25 +467,6 @@ def test_update_organization_cant_change_type(self):
== "organization"
)
- def test_update_group_cant_change_type(self):
- user = factories.User()
- context = {"user": user["name"]}
- group = factories.Group(type="group", name="unchanging", user=user)
-
- group = helpers.call_action(
- "group_update",
- context=context,
- id=group["id"],
- name="unchanging",
- type="favouritecolour",
- )
-
- assert group["type"] == "group"
- assert (
- helpers.call_action("group_show", id="unchanging")["type"]
- == "group"
- )
-
@pytest.mark.usefixtures("clean_db", "with_request_context")
class TestDatasetUpdate(object):
@@ -1481,6 +1462,62 @@ def test_user_create_password_hash_not_for_normal_users(self):
user_obj = model.User.get(user["id"])
assert user_obj.password != "pretend-this-is-a-valid-hash"
+ def test_user_update_image_url(self):
+ user = factories.User(image_url='user_image.jpg')
+ context = {"user": user["name"]}
+
+ user = helpers.call_action(
+ "user_update",
+ context=context,
+ id=user["name"],
+ email="[email protected]",
+ image_url="new_image_url.jpg",
+ )
+
+ assert user["image_url"] == "new_image_url.jpg"
+
+
[email protected]("clean_db", "with_request_context")
+class TestGroupUpdate(object):
+ def test_group_update_image_url_field(self):
+ user = factories.User()
+ context = {"user": user["name"]}
+ group = factories.Group(
+ type="group",
+ name="testing",
+ user=user,
+ image_url='group_image.jpg')
+
+ group = helpers.call_action(
+ "group_update",
+ context=context,
+ id=group["id"],
+ name=group["name"],
+ type=group["type"],
+ image_url="new_image_url.jpg"
+ )
+
+ assert group["image_url"] == "new_image_url.jpg"
+
+ def test_group_update_cant_change_type(self):
+ user = factories.User()
+ context = {"user": user["name"]}
+ group = factories.Group(type="group", name="unchanging", user=user)
+
+ group = helpers.call_action(
+ "group_update",
+ context=context,
+ id=group["id"],
+ name="unchanging",
+ type="favouritecolour",
+ )
+
+ assert group["type"] == "group"
+ assert (
+ helpers.call_action("group_show", id="unchanging")["type"]
+ == "group"
+ )
+
@pytest.mark.usefixtures("clean_db", "with_request_context")
class TestPackageOwnerOrgUpdate(object):
| group_update is not updating 'image_url' field
**CKAN version**
master
2.8.5
**Describe the bug**
Executing `group_update` or `group_patch` with a new `image_url` doesn't have any effect. In the following command I'm trying to change the value to `new_image.jpg` but it is not working.
```
curl -X POST -H "Authorization: blablabla" -H "Content-Type: application/json" --data '{"id":"testing", "image_url":"new_image.jpg"}' "http://ckan:5000/api/action/group_patch"
{
"help": "http://ckan:5000/api/3/action/help_show?name=group_patch",
"success": true,
"result": {
"id": "e040fea8-4ba0-46d1-92ee-26dd5cbe5a7b",
"name": "testing",
"title": "Testing",
"type": "group",
"description": "Prueba",
"image_url": "2020-10-30-124145.785791PDB0980.jpg",
"created": "2020-10-30T09:41:45.798167",
"is_organization": false,
"approval_status": "approved",
"state": "active",
"display_name": "Testing",
"extras": [],
"packages": [],
"package_count": 0,
"tags": [],
"groups": [],
"users": [
{
"id": "9a5ffa4d-26e5-457f-8dca-570e1c3c9fb6",
"name": "ckan_admin",
"fullname": null,
"created": "2020-10-30T09:40:56.162463",
"about": null,
"activity_streams_email_notifications": false,
"sysadmin": true,
"state": "active",
"image_url": null,
"capacity": "admin",
"display_name": "ckan_admin",
"email_hash": "b1443134b36be9f6993b6d4ea4b3f1f1",
"number_created_packages": 0,
"image_display_url": null
}
],
"image_display_url": "http://ckan:5000/uploads/group/2020-10-30-124145.785791PDB0980.jpg"
}
}
```
**Steps to reproduce**
* Create a new group
* Add an image to it
* Try to update the field value with `group_patch` or `group_update`
**Expected behavior**
The field us updated correctly to the new value.
**Additional details**
This is working correctly for users. The problem seems to be in how the `user_update` and `group_update` instantiate the `upload` object:
https://github.com/ckan/ckan/blob/c44096e64e4ff0c98c79c9ad445b48c0750c331e/ckan/logic/action/update.py#L658-L660
https://github.com/ckan/ckan/blob/c44096e64e4ff0c98c79c9ad445b48c0750c331e/ckan/logic/action/update.py#L826-L828
| 2020-10-30T14:11:15 |
|
ckan/ckan | 5,721 | ckan__ckan-5721 | [
"5280"
] | a094e210bc8e71759fe48b4b634dbb8c4c10c890 | diff --git a/ckan/logic/action/create.py b/ckan/logic/action/create.py
--- a/ckan/logic/action/create.py
+++ b/ckan/logic/action/create.py
@@ -1302,7 +1302,8 @@ def tag_create(context, data_dict):
:py:func:`~ckan.logic.action.update.package_update` function.)
:param name: the name for the new tag, a string between 2 and 100
- characters long containing only alphanumeric characters and ``-``,
+ characters long containing only alphanumeric characters,
+ spaces and the characters ``-``,
``_`` and ``.``, e.g. ``'Jazz'``
:type name: string
:param vocabulary_id: the id of the vocabulary that the new tag
| tag_create Documentation needs update
### CKAN Version if known (or site URL)
2.8.3
### The Issue
The tag_create API documentation has 2 issues:
1. For the tag name space is an allowed character but is not currently listed
2. The example of using the vocabulary name ('Genre') is incorrect the actual id is what is required. Issue #2362 sought a fix the software to match the documentation but was not completed. Unless it is doing to get fixed the documentation should be updated.
| @pdekraker-epa @Zharktas , I am working on this issue. In tag name "space" is an allowed character but it is not listed in the document. I think vocabulary_id (string) – the id of the vocabulary that the new tag should be added to, e.g. the id of vocabulary 'Genre' is correct as it clearly states that in the end " e.g. the id of vocabulary 'Genre' ", Where 'Genre' is just an example. It can be id of any other vocabulary as well which has been created. | 2020-11-06T02:39:55 |
|
ckan/ckan | 5,723 | ckan__ckan-5723 | [
"5683"
] | 8eec3e27c320baf29e0d99b2ce20ed14ae10b0d3 | diff --git a/ckanext/stats/blueprint.py b/ckanext/stats/blueprint.py
--- a/ckanext/stats/blueprint.py
+++ b/ckanext/stats/blueprint.py
@@ -13,7 +13,6 @@
def index():
stats = stats_lib.Stats()
extra_vars = {
- u'top_rated_packages': stats.top_rated_packages(),
u'largest_groups': stats.largest_groups(),
u'top_tags': stats.top_tags(),
u'top_package_creators': stats.top_package_creators(),
diff --git a/ckanext/stats/stats.py b/ckanext/stats/stats.py
--- a/ckanext/stats/stats.py
+++ b/ckanext/stats/stats.py
@@ -32,30 +32,6 @@ def datetime2date(datetime_):
class Stats(object):
- @classmethod
- def top_rated_packages(cls, limit=10):
- # NB Not using sqlalchemy as sqla 0.4 doesn't work using both group_by
- # and apply_avg
- package = table('package')
- rating = table('rating')
- sql = select(
- [
- package.c.id,
- func.avg(rating.c.rating),
- func.count(rating.c.rating)
- ],
- from_obj=[package.join(rating)]
- ).where(and_(package.c.private == False, package.c.state == 'active')
- ).group_by(package.c.id).order_by(
- func.avg(rating.c.rating).desc(),
- func.count(rating.c.rating).desc()
- ).limit(limit)
- res_ids = model.Session.execute(sql).fetchall()
- res_pkgs = [(
- model.Session.query(model.Package).get(text_type(pkg_id)), avg, num
- ) for pkg_id, avg, num in res_ids]
- return res_pkgs
-
@classmethod
def largest_groups(cls, limit=10):
member = table('member')
| diff --git a/ckanext/stats/tests/test_stats_lib.py b/ckanext/stats/tests/test_stats_lib.py
--- a/ckanext/stats/tests/test_stats_lib.py
+++ b/ckanext/stats/tests/test_stats_lib.py
@@ -54,10 +54,6 @@ def initial_data(self, clean_db, with_request_context):
model.Package.by_name(u"test3").notes = "Test 3 notes"
model.repo.commit_and_remove()
- def test_top_rated_packages(self):
- pkgs = Stats.top_rated_packages()
- assert pkgs == []
-
def test_largest_groups(self):
grps = Stats.largest_groups()
grps = [(grp.name, count) for grp, count in grps]
| "Top Rated Datasets" needs to be removed from stats
**CKAN version**
2.9.1
**Describe the bug**
"Top Rated Datasets" is still in /stats even though ratings are being deprecated #5558
**Steps to reproduce**
With stats enabled, go to /stats page.
**Expected behavior**
"Top Rated Datasets" is removed from stats.
| 2020-11-06T19:28:55 |
|
ckan/ckan | 5,737 | ckan__ckan-5737 | [
"5731"
] | 8eec3e27c320baf29e0d99b2ce20ed14ae10b0d3 | diff --git a/ckan/plugins/core.py b/ckan/plugins/core.py
--- a/ckan/plugins/core.py
+++ b/ckan/plugins/core.py
@@ -8,7 +8,7 @@
import logging
from pkg_resources import iter_entry_points
from pyutilib.component.core import PluginGlobals, implements
-from pyutilib.component.core import ExtensionPoint as PluginImplementations
+from pyutilib.component.core import ExtensionPoint
from pyutilib.component.core import SingletonPlugin as _pca_SingletonPlugin
from pyutilib.component.core import Plugin as _pca_Plugin
from ckan.common import asbool
@@ -71,6 +71,21 @@ def use_plugin(*plugins):
unload(*plugins)
+class PluginImplementations(ExtensionPoint):
+
+ def __iter__(self):
+ '''
+ When we upgraded pyutilib on CKAN 2.9 the order in which
+ plugins were returned by `PluginImplementations` changed
+ so we use this wrapper to maintain the previous order
+ (which is the same as the ckan.plugins config option)
+ '''
+
+ iterator = super(PluginImplementations, self).__iter__()
+
+ return reversed(list(iterator))
+
+
class PluginNotFoundException(Exception):
'''
Raised when a requested plugin cannot be found.
| diff --git a/ckan/tests/plugins/test_core.py b/ckan/tests/plugins/test_core.py
new file mode 100644
--- /dev/null
+++ b/ckan/tests/plugins/test_core.py
@@ -0,0 +1,21 @@
+# encoding: utf-8
+
+import pytest
+
+import ckan.plugins as p
+
+
[email protected](u"with_plugins")
[email protected]_config(
+ u"ckan.plugins",
+ u"example_idatasetform_v1 example_idatasetform_v2 example_idatasetform_v3")
+def test_plugins_order_in_pluginimplementations():
+
+ assert (
+ [plugin.name for plugin in p.PluginImplementations(p.IDatasetForm)] ==
+ [
+ u"example_idatasetform_v1",
+ u"example_idatasetform_v2",
+ u"example_idatasetform_v3"
+ ]
+ )
| CKAN 2.9 changes order in which plugins are returned by PluginImplementations
## Summary
I'm porting a big project from CKAN 2.8 to 2.9. My plugin overrides a template from ckanext-scheming to customize the form. After upgrade, my changes weren't reflected because my custom template wasn't loaded.
Only after changing the ordering of the plugins in `ckan.plugins` it was picked up.
So on CKAN <= 2.8, in order for plugin `abc` to override `scheming_datasets` you needed:
```
ckan.plugins = abc scheming_datasets
```
In CKAN 2.9, you need:
```
ckan.plugins = scheming_datasets abc
```
### Why it is important
This is pretty significant change, which AFAICT wasn't mentioned in the changelog.
After initial investigation it looks like the issue is not how we parse the config option or load the plugins, but how the `PluginImplementations` iterator returns them. We use them in all places where we let plugins integrate with CKAN core. For instance in `environment.py` we call:
```python
for plugin in p.PluginImplementations(p.IConfigurer):
plugin.update_config(config)
```
This is one is relevant to my issue, as it registers template directories from plugins and stores them on a list in `config['extra_template_paths']`. Order is important, as the first template path found will be used to render.
At [this point](https://github.com/ckan/ckan/blob/8eec3e27c320baf29e0d99b2ce20ed14ae10b0d3/ckan/config/environment.py#L173) we get the following behaviour:
* On CKAN 2.8:
```python
[plugin for plugin in p.PluginImplementations(p.IConfigurer)]
# [<Plugin AbcPlugin 'abc'>, <Plugin SchemingDatasetsPlugin 'scheming_datasets'>]
config['extra_template_paths'].split(',')
# [
# u'/home/adria/dev/pyenvs/ckan/src/ckanext-abc/ckanext/abc/templates',
# u'/home/adria/dev/pyenvs/ckan/src/ckanext-scheming/ckanext/scheming/templates',
# ]
```
* On CKAN 2.9:
```python
[plugin for plugin in p.PluginImplementations(p.IConfigurer)]
# [<Plugin SchemingDatasetsPlugin 'scheming_datasets'>, <Plugin AbcPlugin 'abc'>]
config['extra_template_paths'].split(',')
# [
# u'/home/adria/dev/pyenvs/ckan/src/ckanext-scheming/ckanext/scheming/templates',
# u'/home/adria/dev/pyenvs/ckan/src/ckanext-abc/ckanext/abc/templates',
# ]
```
Apart from template loading issues this is likely to affect everywhere where the order of plugins is important, eg chained actions, chained auth functions.
### Root cause
After looking at [ckan/plugins/core.py](https://github.com/ckan/ckan/blob/master/ckan/plugins/core.py) my current thinking is that this is *not* related to the loading of the plugins. AFAICT we´ve always loaded them in the order that they are defined in `ckan.plugins`. It´s the actual iterator returned by `PluginImplementations` that changed the order of the returned plugins at some point between the two versions (pyutilib.component.core==4.6.4 in CKAN 2.8, PyUtilib==5.7.1 in CKAN 2.9). We are importing this class directly from Pyutillib. The only work done on this code between these two versions was https://github.com/ckan/ckan/pull/4886, and I don´t think it should affect the ordering (apart from upgrading the library of course)
### What should we do?
My ideas so far:
1. Change nothing and assume this is the new behaviour, *but* documenting it in the relevant places (2.9 Changelog, plugins docs, mail to ckan-dev). I don´t think we can leave a change like this undocumented
2. Create our own `PluginImplementations` wrapper that restores the old ordering (maybe optionally based on a config option). We would need to override the [`__iter__()`](https://github.com/PyUtilib/pyutilib/blob/5.7.3/pyutilib/component/core/core.py#L222) method, not sure how easy that is
Any thoughts or other ideas on what to do? @ckan/core
| Personally I think we should try to preserve the order if we can. People don't read change logs or understand them, based on solely on the amount of support requests we've had since 2.9 release. | 2020-11-10T11:57:54 |
ckan/ckan | 5,750 | ckan__ckan-5750 | [
"5589"
] | 821c73cebc09689c4f68826ff61b22eaedec4366 | diff --git a/ckanext/datastore/cli.py b/ckanext/datastore/cli.py
--- a/ckanext/datastore/cli.py
+++ b/ckanext/datastore/cli.py
@@ -7,6 +7,7 @@
from ckan.model import parse_db_config
from ckan.common import config
+import ckan.logic as logic
import ckanext.datastore as datastore_module
from ckanext.datastore.backend.postgres import identifier
@@ -111,3 +112,69 @@ def _parse_db_config(config_key=u'sqlalchemy.url'):
)
raise click.Abort()
return db_config
+
+
[email protected](
+ u'purge',
+ short_help=u'purge orphaned resources from the datastore.'
+)
+def purge():
+ u'''Purge orphaned resources from the datastore using the datastore_delete
+ action, which drops tables when called without filters.'''
+
+ site_user = logic.get_action(u'get_site_user')({u'ignore_auth': True}, {})
+ context = {u'user': site_user[u'name']}
+
+ result = logic.get_action(u'datastore_search')(
+ context,
+ {u'resource_id': u'_table_metadata'}
+ )
+
+ resource_id_list = []
+ for record in result[u'records']:
+ try:
+ # ignore 'alias' records (views) as they are automatically
+ # deleted when the parent resource table is dropped
+ if record[u'alias_of']:
+ continue
+
+ # we need to do this to trigger resource_show auth function
+ site_user = logic.get_action(u'get_site_user')(
+ {u'ignore_auth': True}, {})
+ context = {u'user': site_user[u'name']}
+
+ logic.get_action(u'resource_show')(
+ context,
+ {u'id': record[u'name']}
+ )
+ except logic.NotFound:
+ resource_id_list.append(record[u'name'])
+ click.echo(u"Resource '%s' orphaned - queued for drop" %
+ record[u'name'])
+ except KeyError:
+ continue
+
+ orphaned_table_count = len(resource_id_list)
+ click.echo(u'%d orphaned tables found.' % orphaned_table_count)
+
+ if not orphaned_table_count:
+ return
+
+ click.confirm(u'Proceed with purge?', abort=True)
+
+ # Drop the orphaned datastore tables. When datastore_delete is called
+ # without filters, it does a drop table cascade
+ drop_count = 0
+ for resource_id in resource_id_list:
+ logic.get_action(u'datastore_delete')(
+ context,
+ {u'resource_id': resource_id, u'force': True}
+ )
+ click.echo(u"Table '%s' dropped)" % resource_id)
+ drop_count += 1
+
+ click.echo(u'Dropped %s tables' % drop_count)
+
+
+def get_commands():
+ return (set_permissions, dump, purge)
| Purging deleted packages does not delete associated filestore/datastore resources
**CKAN version**
2.9
**Describe the bug**
After deleting and purging dataset packages, the associated datastore/filestore resources are orphaned and not deleted.
**Steps to reproduce**
1. Delete datasets
2. Go to sysadmin/trash
3. Select "Purge All"
4. Check datastore and filestore. Associated resources are still there.
**Expected behavior**
Dataset resources in the filestore and the datastore are deleted when the associated package resources are purged.
**Additional details**
This is related to #4705 and a lot of work has been done on PRs #4867 and #4905, but neither have been merged.
| 2020-11-20T19:46:24 |
||
ckan/ckan | 5,754 | ckan__ckan-5754 | [
"5732"
] | 612e0f9ab01b61516399e39a803d8cb66cd3c9cf | diff --git a/ckanext/reclineview/plugin.py b/ckanext/reclineview/plugin.py
--- a/ckanext/reclineview/plugin.py
+++ b/ckanext/reclineview/plugin.py
@@ -7,6 +7,7 @@
from ckan.common import json, config
import ckan.plugins as p
import ckan.plugins.toolkit as toolkit
+from ckan.plugins.toolkit import _
log = getLogger(__name__)
ignore_empty = p.toolkit.get_validator('ignore_empty')
@@ -106,7 +107,7 @@ class ReclineView(ReclineViewBase):
def info(self):
return {'name': 'recline_view',
- 'title': 'Data Explorer',
+ 'title': _('Data Explorer'),
'filterable': True,
'icon': 'table',
'requires_datastore': False,
@@ -135,7 +136,7 @@ class ReclineGridView(ReclineViewBase):
def info(self):
return {'name': 'recline_grid_view',
- 'title': 'Grid',
+ 'title': _('Grid'),
'filterable': True,
'icon': 'table',
'requires_datastore': True,
@@ -177,7 +178,7 @@ def info(self):
'series': [ignore_empty, in_list(self.list_datastore_fields)]
}
return {'name': 'recline_graph_view',
- 'title': 'Graph',
+ 'title': _('Graph'),
'filterable': True,
'icon': 'bar-chart-o',
'requires_datastore': True,
@@ -238,7 +239,7 @@ def info(self):
'cluster_markers': [ignore_empty]
}
return {'name': 'recline_map_view',
- 'title': 'Map',
+ 'title': _('Map'),
'schema': schema,
'filterable': True,
'icon': 'map-marker',
| Translation missing for "Data explorer" in reclineview
**CKAN version=2.8.6**
**Describe the bug**
When switching to the french language, the tab name "data explorer on a resource preview page is not translated
**Steps to reproduce**
1. Installing ckan from source
2. Set up a dataset with a previewable format (e.g csv)
3. preview the data
4. Select the french language by changing the url t0 http://XXX.X.X.X:XXXXfr/XXXXXXX
**Expected behavior**
The tab name shoud be translated to something like "Explorateur de données"
| You are right, the "Data Explorer" string [here](https://github.com/ckan/ckan/blob/f6ebeb5a581e7550bc8f2c5b3bf59343b1692602/ckanext/reclineview/plugin.py#L109) and all the the `title` properties of the other plugins should be wrapped in the underscore function to make them translatable, eg `'title': _('Data Explorer')`
Do you want to submit a pull request for this?
@J-bytes @amercader , I have wrapped the title property of recline_view and other plugins in the underscore function to make them translatable but getting the below NameError.

However to resolve the above NameError I have import _ from ckan.common but still "Data Explorer" is not translatable.
@amercader , I have check and found that "Data Explorer" is not translated in other languages as well.
@Gauravp-NEC thanks for your help. It's better to import `_` from the toolkit when in an extension like this one.
For "Data Explorer" to be translatable, the string needs to be extracted first and included in the `.po` files that we use for translation. But we do this separately before a release, so just wrapping the string with `_()` at this point should be enough
@amercader I've checked deeper and it seems many translations displayed inside the iframe do not get translated too. They are all wrapped with the underscore function and the traductions were already available in the .po file. I've tried recompiling the .mo file with and without fuzzy with no success... Do you have any idea what could stop babel from translating these? Thank you for your help.


| 2020-11-23T10:21:51 |
|
ckan/ckan | 5,758 | ckan__ckan-5758 | [
"5757"
] | 254b18cd274dc23f2895d9de7b7eb3022b49a534 | diff --git a/ckanext/datastore/plugin.py b/ckanext/datastore/plugin.py
--- a/ckanext/datastore/plugin.py
+++ b/ckanext/datastore/plugin.py
@@ -145,9 +145,10 @@ def after_delete(self, context, resources):
if res.extras.get('datastore_active') is True]
for res in deleted:
- self.backend.delete(context, {
- 'resource_id': res.id,
- })
+ if self.backend.resource_exists(res.id):
+ self.backend.delete(context, {
+ 'resource_id': res.id,
+ })
res.extras['datastore_active'] = False
res_query.filter_by(id=res.id).update(
{'extras': res.extras}, synchronize_session=False)
| Exception when deleting resource if datastore table should exist but does not
**2.8.4**
**Describe the bug**
If for whatever reason, you end up with a resource for which datastore_active is set in the resource extras, but the datastore table does not actually exist, an exception is thown when trying to delete this resource.
**Steps to reproduce**
1. Create a resource and make sure data is uploaded to the datastore
2. Manually delete the database table of this resource from the database
3. Try to delete this resource via the ckan UI
4. An exception is thrown
**Expected behavior**
Before deleting, check whether the datastore table actually exists. If it doesn't exist, just skip the delete step. Better than throwing an exception.
**Additional details**
Not sure how I managed to get into this inconsistent state. Might not even be CKAN's fault since we had some issues with our persistence infrastructure/volumes.
Stack trace here:
```
File '/srv/app/src/ckan/ckan/controllers/package.py', line 1175 in resource_delete
get_action('resource_delete')(context, {'id': resource_id})
File '/srv/app/src/ckan/ckan/logic/__init__.py', line 466 in wrapped
result = _action(context, data_dict, **kw)
File '/srv/app/src/ckan/ckan/logic/action/delete.py', line 204 in resource_delete
plugin.after_delete(context, pkg_dict.get('resources', []))
File '/srv/app/src/ckan/ckanext/datastore/plugin.py', line 161 in after_delete
'resource_id': res.id,
File '/srv/app/src/ckan/ckanext/datastore/backend/postgres.py', line 1720 in delete
data_dict['resource_id'])
File '/usr/lib/python2.7/site-packages/sqlalchemy/engine/base.py', line 939 in execute
return self._execute_text(object, multiparams, params)
File '/usr/lib/python2.7/site-packages/sqlalchemy/engine/base.py', line 1097 in _execute_text
statement, parameters
File '/usr/lib/python2.7/site-packages/sqlalchemy/engine/base.py', line 1189 in _execute_context
context)
File '/usr/lib/python2.7/site-packages/sqlalchemy/engine/base.py', line 1402 in _handle_dbapi_exception
exc_info
File '/usr/lib/python2.7/site-packages/sqlalchemy/util/compat.py', line 203 in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File '/usr/lib/python2.7/site-packages/sqlalchemy/engine/base.py', line 1182 in _execute_context
context)
File '/usr/lib/python2.7/site-packages/sqlalchemy/engine/default.py', line 470 in do_execute
cursor.execute(statement, parameters)
ProgrammingError: (psycopg2.ProgrammingError) table "f03c4532-bc47-4ca0-bf73-f96e42082f49" does not exist
[SQL: 'DROP TABLE "f03c4532-bc47-4ca0-bf73-f96e42082f49" CASCADE']
```
I will provide a pull request.
| 2020-11-23T16:04:26 |
||
ckan/ckan | 5,760 | ckan__ckan-5760 | [
"5115"
] | 254b18cd274dc23f2895d9de7b7eb3022b49a534 | diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py
--- a/ckan/logic/validators.py
+++ b/ckan/logic/validators.py
@@ -454,8 +454,9 @@ def tag_name_validator(value, context):
tagname_match = re.compile('[\w \-.]*$', re.UNICODE)
if not tagname_match.match(value):
- raise Invalid(_('Tag "%s" must be alphanumeric '
- 'characters or symbols: -_.') % (value))
+ raise Invalid(_(''Tag "%s" can only contain alphanumeric '
+ 'characters, spaces (" "), hyphens ("-"), '
+ 'underscores ("_") or dots (".")') % (value))
return value
def tag_not_uppercase(value, context):
| French: "alphanumeric characters" translated to "lettres minuscules, des chiffres"
The English string
> Tag \"%s\" must be alphanumeric characters or symbols: -_.
...which is used in ckan/logic/validators.py:428 to validate tags, has an inaccurate translation in French:
> Le mot-clé \"%s\" ne peut contenir que des lettres minuscules, des chiffres ou les symboles : -_.
An alphanumeric character can be a digit or any letter, whether lowercase or not, so the French description is overly restrictive. An accurate translation could therefore be:
"Le mot-clé \"%s\" ne peut contenir que des lettres, des chiffres ou les symboles : -_."
This affects CKAN 2.4.1, and persists in the master branch as of a3a6b582fcd758727c98b628d13d198b4317787c.
Note that it is unclear which (special) symbols these strings refer to.
| @Chealer that sounds good. Translations are managed on Transifex (https://www.transifex.com/okfn/ckan/). If you register for an account you can update the strings for the 2.6, 2.7 and 2.8 resources, and next time we do a patch release we will pull the latest translations with the fixes:

Thank you @amercader but I'm afraid an efficient solution for this string would start with a clarification of the English version.
@Chealer sorry, I don't follow. What needs clarification on the English string?
@amercader the "symbols" (special characters) which are allowed (if I understand correctly, dashes and underscores).
> Tag "%s" must be alphanumeric characters or symbols: -_.
The only [allowed](https://github.com/ckan/ckan/blob/master/ckan/logic/validators.py#L432) punctuation symbols are hyphen (`-`), underscore (`_`) and full stop (`.`). That's what it says on the message. Perhaps is the colon what is confusing?
If you can think of a better message please do send a PR and then we can create a new French translation.
| 2020-11-24T10:05:04 |
|
ckan/ckan | 5,763 | ckan__ckan-5763 | [
"5759"
] | 4c455353eb3319d557f7b18959e2259b52f7230b | diff --git a/ckan/logic/action/create.py b/ckan/logic/action/create.py
--- a/ckan/logic/action/create.py
+++ b/ckan/logic/action/create.py
@@ -668,7 +668,7 @@ def package_collaborator_create(context, data_dict):
user = model.User.get(user_id)
if not user:
- raise NotAuthorized(_('Not allowed to add collaborators'))
+ raise NotFound(_('User not found'))
if not authz.check_config_permission('allow_dataset_collaborators'):
raise ValidationError(_('Dataset collaborators not enabled'))
diff --git a/ckan/views/dataset.py b/ckan/views/dataset.py
--- a/ckan/views/dataset.py
+++ b/ckan/views/dataset.py
@@ -1313,10 +1313,12 @@ def post(self, package_type, id):
except NotAuthorized:
message = _(u'Unauthorized to edit collaborators {}').format(id)
return base.abort(401, _(message))
- except NotFound:
- return base.abort(404, _(u'Resource not found'))
+ except NotFound as e:
+ h.flash_error(_('User not found'))
+ return h.redirect_to(u'dataset.new_collaborator', id=id)
except ValidationError as e:
h.flash_error(e.error_summary)
+ return h.redirect_to(u'dataset.new_collaborator', id=id)
else:
h.flash_success(_(u'User added to collaborators'))
| diff --git a/ckan/tests/logic/action/test_create.py b/ckan/tests/logic/action/test_create.py
--- a/ckan/tests/logic/action/test_create.py
+++ b/ckan/tests/logic/action/test_create.py
@@ -1243,12 +1243,12 @@ def test_create_dataset_not_found(self):
'package_collaborator_create',
id=dataset['id'], user_id=user['id'], capacity=capacity)
- def test_create_user_not_authorized(self):
+ def test_create_user_not_found(self):
dataset = factories.Dataset()
user = {'id': 'yyy'}
capacity = 'editor'
- with pytest.raises(logic.NotAuthorized):
+ with pytest.raises(logic.NotFound):
helpers.call_action(
'package_collaborator_create',
id=dataset['id'], user_id=user['id'], capacity=capacity)
| Wrong Exception in package_collaborator_create
**CKAN version**
2.9.1
**Describe the bug**
When attempting to add a non-existent user as a dataset collaborator a NotAuthorized exception is raised, which should probably be a validation or not found exception. The message 'Not allowed to add collaborators' also does not make sense for the underlying cause. When using this functionality via the web interface (at least in my implementation) the NotAuthorized exception logs the user out, which is not desired behavior.
https://github.com/ckan/ckan/blob/254b18cd274dc23f2895d9de7b7eb3022b49a534/ckan/logic/action/create.py#L671
| 2020-11-26T13:46:06 |
|
ckan/ckan | 5,784 | ckan__ckan-5784 | [
"5775",
"5775"
] | 629fdc6391f1b05f5e405d46eb4573a55abb5a1a | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -1277,7 +1277,7 @@ def organization_show(context, data_dict):
:rtype: dictionary
- .. note:: Only its first 1000 datasets are returned
+ .. note:: Only its first 10 datasets are returned
'''
return _group_or_org_show(context, data_dict, is_org=True)
| organization_show returns 10 packages instead of the advertised 1000
**CKAN version**
2.9.1
**Describe the bug**
/api/3/action/organization_show?include_datasets=True returns a max of 10 packages.
api/3/action/help_show?name=organization_show says
> .. note:: Only its first 1000 datasets are returned
**Steps to reproduce**
Create an org and add 11 packages.
Hit the organization_show endpoint with id=your-org
Note that only 10 packages are returned.
**Expected behavior**
I expected up to 1000 packages to be returned.
**Additional details**
Looks like it might have been related to this change: https://github.com/ckan/ckan/commit/bd01afe8139eb8cb75277503089b96a8247beb7e#diff-479ec62a04a4a945f75aa6d8644b5b609ddc678b4ee8f56328b50b9d748420b9R394
I see logic that looks like it should allow overriding the search default limit of 10, but I'm not sure where/how `context['limits']['packags']` is set: https://github.com/ckan/ckan/blob/master/ckan/lib/dictization/model_dictize.py#L331
organization_show returns 10 packages instead of the advertised 1000
**CKAN version**
2.9.1
**Describe the bug**
/api/3/action/organization_show?include_datasets=True returns a max of 10 packages.
api/3/action/help_show?name=organization_show says
> .. note:: Only its first 1000 datasets are returned
**Steps to reproduce**
Create an org and add 11 packages.
Hit the organization_show endpoint with id=your-org
Note that only 10 packages are returned.
**Expected behavior**
I expected up to 1000 packages to be returned.
**Additional details**
Looks like it might have been related to this change: https://github.com/ckan/ckan/commit/bd01afe8139eb8cb75277503089b96a8247beb7e#diff-479ec62a04a4a945f75aa6d8644b5b609ddc678b4ee8f56328b50b9d748420b9R394
I see logic that looks like it should allow overriding the search default limit of 10, but I'm not sure where/how `context['limits']['packags']` is set: https://github.com/ckan/ckan/blob/master/ckan/lib/dictization/model_dictize.py#L331
| The change (1000 -> 10) was done for performance reasons, but sadly the documentation was not updated alongside it.
Do you mind submitting a PR fixing the docs?
If you need to get all datasets belonging to an organization it's much more efficient to use [`package_search`](https://docs.ckan.org/en/latest/api/index.html#ckan.logic.action.get.package_search) and the `rows` and `start` parameters to paginate. You can actually request 1000 datasets using that API action.
The change (1000 -> 10) was done for performance reasons, but sadly the documentation was not updated alongside it.
Do you mind submitting a PR fixing the docs?
If you need to get all datasets belonging to an organization it's much more efficient to use [`package_search`](https://docs.ckan.org/en/latest/api/index.html#ckan.logic.action.get.package_search) and the `rows` and `start` parameters to paginate. You can actually request 1000 datasets using that API action. | 2020-12-08T13:59:20 |
|
ckan/ckan | 5,830 | ckan__ckan-5830 | [
"5789"
] | 4ec2a7167e731b8ed7e2e98f0bae435aa8f829e0 | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -350,11 +350,18 @@ def _group_or_org_list(context, data_dict, is_org=False):
if all_fields:
# all_fields is really computationally expensive, so need a tight limit
- max_limit = config.get(
- 'ckan.group_and_organization_list_all_fields_max', 25)
+ try:
+ max_limit = int(config.get(
+ 'ckan.group_and_organization_list_all_fields_max', 25))
+ except ValueError:
+ max_limit = 25
else:
- max_limit = config.get('ckan.group_and_organization_list_max', 1000)
- if limit is None or limit > max_limit:
+ try:
+ max_limit = int(config.get('ckan.group_and_organization_list_max', 1000))
+ except ValueError:
+ max_limit = 1000
+
+ if limit is None or int(limit) > max_limit:
limit = max_limit
# order_by deprecated in ckan 1.8
| diff --git a/ckan/tests/logic/action/test_get.py b/ckan/tests/logic/action/test_get.py
--- a/ckan/tests/logic/action/test_get.py
+++ b/ckan/tests/logic/action/test_get.py
@@ -460,6 +460,15 @@ def test_group_list_limit_and_offset(self):
assert len(group_list) == 1
assert group_list[0] == group2["name"]
+ def test_group_list_limit_as_string(self):
+
+ group1 = factories.Group(name='aa')
+ group2 = factories.Group(name='bb')
+
+ group_list = helpers.call_action("group_list", limit="1")
+
+ assert len(group_list) == 1
+
def test_group_list_wrong_limit(self):
with pytest.raises(logic.ValidationError):
| Organization list crashes when called with a limit parameter
**CKAN version**
2.9.1
**Describe the bug**
When querying/listing organizations or groups with an added limit parameter there is a server error.
**Steps to reproduce**
Calling `curl` on the `organization_list` with the limit field set should recreate it.
E.g.
```
curl http://localhost:5000/api/3/action/organization_list\?limit\=31
{"help": "http://localhost:5000/api/3/action/help_show?name=organization_list", "error": {"__type": "Internal Server Error", "message": "Internal Server Error"}, "success": false}%
```
**Expected behavior**
The server should return a list of organizations/groups.
| 2021-01-15T11:27:00 |
|
ckan/ckan | 5,837 | ckan__ckan-5837 | [
"5836"
] | 4e639b09d76c1571273d7323f962055029943b5f | diff --git a/ckan/plugins/toolkit.py b/ckan/plugins/toolkit.py
--- a/ckan/plugins/toolkit.py
+++ b/ckan/plugins/toolkit.py
@@ -404,7 +404,7 @@ def _add_served_directory(cls, config, relative_path, config_var):
this_dir = os.path.dirname(filename)
absolute_path = os.path.join(this_dir, relative_path)
- if absolute_path not in config.get(config_var, ''):
+ if absolute_path not in config.get(config_var, '').split(','):
if config.get(config_var):
config[config_var] += ',' + absolute_path
else:
| Can't add directories from plugins if partially string matches existing values
**CKAN version**
1.7 or so
**Describe the bug**
If you add a served directory that partially string matches existing values it will be ignored
**Steps to reproduce**
```
if old_ckan:
add_template_directory(config, 'templates-for-old-ckans')
add_template_directory(config, 'templates')
```
**Expected behavior**
when old_ckan is True I expect both template directories to be in the template search path
**Additional details**
only the `/path/to/my/extension/templates-for-old-ckans` appears in the template search path
| 2021-01-18T23:37:31 |
||
ckan/ckan | 5,846 | ckan__ckan-5846 | [
"5831",
"5832"
] | 821c73cebc09689c4f68826ff61b22eaedec4366 | diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py
--- a/ckanext/datastore/backend/postgres.py
+++ b/ckanext/datastore/backend/postgres.py
@@ -1857,7 +1857,7 @@ def create(self, context, data_dict):
trans = context['connection'].begin()
try:
- # check if table already existes
+ # check if table already exists
context['connection'].execute(
u'SET LOCAL statement_timeout TO {0}'.format(timeout))
result = context['connection'].execute(
@@ -1951,45 +1951,116 @@ def resource_id_from_alias(self, alias):
# pass
def resource_fields(self, id):
- def _type_lookup(t):
- if t in ['numeric', 'integer']:
- return 'number'
- if t.startswith('timestamp'):
- return "date"
- return "text"
- info = {'schema': {}, 'meta': {}}
+ info = {'meta': {}, 'fields': []}
- schema_results = None
- meta_results = None
try:
+ engine = self._get_read_engine()
+
+ # resource id for deferencing aliases
+ info['meta']['id'] = id
+
+ # count of rows in table
+ meta_sql = sqlalchemy.text(
+ u'SELECT count(_id) FROM "{0}"'.format(id))
+ meta_results = engine.execute(meta_sql)
+ info['meta']['count'] = meta_results.fetchone()[0]
+
+ # table_type - BASE TABLE, VIEW, FOREIGN TABLE, MATVIEW
+ tabletype_sql = sqlalchemy.text(u'''
+ SELECT table_type FROM INFORMATION_SCHEMA.TABLES
+ WHERE table_name = '{0}'
+ '''.format(id))
+ tabletype_results = engine.execute(tabletype_sql)
+ info['meta']['table_type'] = tabletype_results.fetchone()[0]
+ # MATERIALIZED VIEWS show as BASE TABLE, so
+ # we check pg_matviews
+ matview_sql = sqlalchemy.text(u'''
+ SELECT count(*) FROM pg_matviews
+ WHERE matviewname = '{0}'
+ '''.format(id))
+ matview_results = engine.execute(matview_sql)
+ if matview_results.fetchone()[0]:
+ info['meta']['table_type'] = 'MATERIALIZED VIEW'
+
+ # SIZE - size of table in bytes
+ size_sql = sqlalchemy.text(
+ u"SELECT pg_relation_size('{0}')".format(id))
+ size_results = engine.execute(size_sql)
+ info['meta']['size'] = size_results.fetchone()[0]
+
+ # DB_SIZE - size of database in bytes
+ dbsize_sql = sqlalchemy.text(
+ u"SELECT pg_database_size(current_database())".format(id))
+ dbsize_results = engine.execute(dbsize_sql)
+ info['meta']['db_size'] = dbsize_results.fetchone()[0]
+
+ # IDXSIZE - size of all indices for table in bytes
+ idxsize_sql = sqlalchemy.text(
+ u"SELECT pg_indexes_size('{0}')".format(id))
+ idxsize_results = engine.execute(idxsize_sql)
+ info['meta']['idx_size'] = idxsize_results.fetchone()[0]
+
+ # all the aliases for this resource
+ alias_sql = sqlalchemy.text(u'''
+ SELECT name FROM "_table_metadata" WHERE alias_of = '{0}'
+ '''.format(id))
+ alias_results = engine.execute(alias_sql)
+ aliases = []
+ for alias in alias_results.fetchall():
+ aliases.append(alias[0])
+ info['meta']['aliases'] = aliases
+
+ # get the data dictionary for the resource
+ data_dictionary = datastore_helpers.datastore_dictionary(id)
+
schema_sql = sqlalchemy.text(u'''
- SELECT column_name, data_type
- FROM INFORMATION_SCHEMA.COLUMNS
- WHERE table_name = :resource_id;
- ''')
- schema_results = self._get_read_engine().execute(
- schema_sql, resource_id=id)
+ SELECT
+ f.attname AS column_name,
+ pg_catalog.format_type(f.atttypid,f.atttypmod) AS native_type,
+ f.attnotnull AS notnull,
+ i.relname as index_name,
+ CASE
+ WHEN i.oid<>0 THEN True
+ ELSE False
+ END AS is_index,
+ CASE
+ WHEN p.contype = 'u' THEN True
+ WHEN p.contype = 'p' THEN True
+ ELSE False
+ END AS uniquekey
+ FROM pg_attribute f
+ JOIN pg_class c ON c.oid = f.attrelid
+ JOIN pg_type t ON t.oid = f.atttypid
+ LEFT JOIN pg_constraint p ON p.conrelid = c.oid
+ AND f.attnum = ANY (p.conkey)
+ LEFT JOIN pg_index AS ix ON f.attnum = ANY(ix.indkey)
+ AND c.oid = f.attrelid AND c.oid = ix.indrelid
+ LEFT JOIN pg_class AS i ON ix.indexrelid = i.oid
+ WHERE c.relkind = 'r'::char
+ AND c.relname = '{0}'
+ AND f.attnum > 0
+ ORDER BY c.relname,f.attnum;
+ '''.format(id))
+ schema_results = engine.execute(schema_sql)
+ schemainfo = {}
for row in schema_results.fetchall():
- k = row[0]
- v = row[1]
- if k.startswith('_'): # Skip internal rows
+ colname = row.column_name
+ if colname.startswith('_'): # Skip internal rows
continue
- info['schema'][k] = _type_lookup(v)
+ colinfo = {'native_type': row.native_type,
+ 'notnull': row.notnull,
+ 'index_name': row.index_name,
+ 'is_index': row.is_index,
+ 'uniquekey': row.uniquekey}
+ schemainfo[colname] = colinfo
- # We need to make sure the resource_id is a valid resource_id
- # before we use it like this, we have done that above.
- meta_sql = sqlalchemy.text(u'''
- SELECT count(_id) FROM "{0}";
- '''.format(id))
- meta_results = self._get_read_engine().execute(
- meta_sql, resource_id=id)
- info['meta']['count'] = meta_results.fetchone()[0]
- finally:
- if schema_results:
- schema_results.close()
- if meta_results:
- meta_results.close()
+ for field in data_dictionary:
+ field.update({'schema': schemainfo[field['id']]})
+ info['fields'].append(field)
+
+ except Exception:
+ pass
return info
def get_all_ids(self):
diff --git a/ckanext/datastore/logic/action.py b/ckanext/datastore/logic/action.py
--- a/ckanext/datastore/logic/action.py
+++ b/ckanext/datastore/logic/action.py
@@ -289,27 +289,57 @@ def datastore_upsert(context, data_dict):
def datastore_info(context, data_dict):
'''
- Returns information about the data imported, such as column names
- and types.
+ Returns detailed metadata about a resource.
+
+ :param resource_id: id or alias of the resource we want info about.
+ :type resource_id: string
+
+ **Results:**
+
+ :rtype: dictionary
+ :returns:
+ **meta**: resource metadata dictionary with the following keys:
+
+ - aliases - aliases (views) for the resource
+ - count - row count
+ - db_size - size of the datastore database (bytes)
+ - id - resource id (useful for dereferencing aliases)
+ - idx_size - size of all indices for the resource (bytes)
+ - size - size of resource (bytes)
+ - table_type - BASE TABLE, VIEW, FOREIGN TABLE or MATERIALIZED VIEW
+
+ **fields**: A list of dictionaries based on :ref:`fields`, with an
+ additional nested dictionary per field called **schema**, with the
+ following keys:
+
+ - native_type - native database data type
+ - index_name
+ - is_index
+ - notnull
+ - uniquekey
- :rtype: A dictionary describing the columns and their types.
- :param id: Id of the resource we want info about
- :type id: A UUID
'''
backend = DatastoreBackend.get_active_backend()
- p.toolkit.check_access('datastore_info', context, data_dict)
-
resource_id = _get_or_bust(data_dict, 'id')
- p.toolkit.get_action('resource_show')(context, {'id': resource_id})
-
res_exists = backend.resource_exists(resource_id)
if not res_exists:
- raise p.toolkit.ObjectNotFound(p.toolkit._(
- u'Resource "{0}" was not found.'.format(resource_id)
- ))
+ alias_exists, real_id = backend.resource_id_from_alias(resource_id)
+ if not alias_exists:
+ raise p.toolkit.ObjectNotFound(p.toolkit._(
+ u'Resource/Alias "{0}" was not found.'.format(resource_id)
+ ))
+ else:
+ id = real_id
+ else:
+ id = resource_id
+
+ data_dict['id'] = id
+ p.toolkit.check_access('datastore_info', context, data_dict)
+
+ p.toolkit.get_action('resource_show')(context, {'id': id})
- info = backend.resource_fields(resource_id)
+ info = backend.resource_fields(id)
return info
| diff --git a/ckanext/datastore/tests/test_info.py b/ckanext/datastore/tests/test_info.py
--- a/ckanext/datastore/tests/test_info.py
+++ b/ckanext/datastore/tests/test_info.py
@@ -19,15 +19,38 @@ def test_info_success():
{"from": "Brazil", "to": "Italy", "num": 22},
],
}
- result = helpers.call_action("datastore_create", **data)
+ helpers.call_action("datastore_create", **data)
+
+ # aliases can only be created against an existing resource
+ data = {
+ "resource_id": resource["id"],
+ "force": True,
+ "aliases": "testalias1, testview2",
+
+ }
+ helpers.call_action("datastore_create", **data)
info = helpers.call_action("datastore_info", id=resource["id"])
- assert info["meta"]["count"] == 2, info["meta"]
- assert len(info["schema"]) == 3
- assert info["schema"]["to"] == "text"
- assert info["schema"]["from"] == "text"
- assert info["schema"]["num"] == "number", info["schema"]
+ assert len(info["meta"]) == 7, info["meta"]
+ assert info["meta"]["count"] == 2
+ assert info["meta"]["table_type"] == "BASE TABLE"
+ assert len(info["meta"]["aliases"]) == 2
+ assert info["meta"]["aliases"] == ["testview2", "testalias1"]
+ assert len(info["fields"]) == 3, info["fields"]
+ assert info["fields"][0]["id"] == "from"
+ assert info["fields"][0]["type"] == "text"
+ assert info["fields"][0]["schema"]["native_type"] == "text"
+ assert not info["fields"][0]["schema"]["is_index"]
+ assert info["fields"][2]["id"] == "num"
+ assert info["fields"][2]["schema"]["native_type"] == "integer"
+
+ # check datastore_info with alias
+ info = helpers.call_action("datastore_info", id='testalias1')
+
+ assert len(info["meta"]) == 7, info["meta"]
+ assert info["meta"]["count"] == 2
+ assert info["meta"]["id"] == resource["id"]
@pytest.mark.ckan_config("ckan.plugins", "datastore")
| datastore_info does not return all available datastore info
**CKAN version**
2.9.1
**Describe the bug**
`datastore_info` _["returns information about the data imported, such as column names and types."](https://docs.ckan.org/en/2.9/maintaining/datastore.html#ckanext.datastore.logic.action.datastore_info)_. For example:
```
$ ckanapi action datastore_info id=5ab4b4de-c970-4619-ab55-ce4338535b24 -r https://data.boston.gov
{
"meta": {
"count": 1268020
},
"schema": {
"Agency": "text",
"DateEntered": "text",
"Developer": "text",
"GeneralContractor": "text",
"MINOR": "text",
"ProjectAddress_1": "text",
"ProjectName": "text",
"ProjectNeigborhood": "text",
"RESIDENT": "text",
"Race_Desc": "text",
"SEX": "text",
"SubContractor": "text",
"SubContractorAddress_1": "text",
"SubContractorAddress_2": "text",
"TotalHours": "text",
"Trade": "text"
}
}
```
However, it doesn't return other relevant available datastore information like aliases and the data dictionary.
Currently, to get an alias, you need to [query a special view `_table_metadata`](https://docs.ckan.org/en/2.9/maintaining/datastore.html#resource-aliases). To [get the data dictionary](https://docs.ckan.org/en/2.9/maintaining/datastore.html#data-dictionary), you need to call `datastore_search`.
**Expected behavior**
Instead of fetching datastore information for a given resource from three different areas, expand
`datastore_info` so that it also returns the resource's aliases and its data dictionary in addition to what it returns now,
Having the actual data type as stored in the database, and the logical datatype as described by the data dictionary is also useful for Datastore API users. Returning if a column is indexed is also useful for developers who are using `datastore_search_sql` so they can create performant SQL queries.
**Additional details**
This will facilitate implementing #5801. It will also help CKAN Datastore API users who are using the datastore to create efficient reports/visualizations and extensions.
datastore_info does not work for aliases
**CKAN version**
2.9.1
**Describe the bug**
`datastore_info` does not work for resource aliases.
**Steps to reproduce**
1. Create a resource
2. Use `datastore_create` to create aliases for the resource
3. Calling `datastore_info` with a valid alias results in a `NotFound` error
**Expected behavior**
`datastore_info` should also work for aliases. Further, it should returned the aliased resource id.
| 2021-01-20T21:55:54 |
|
ckan/ckan | 5,864 | ckan__ckan-5864 | [
"5670"
] | cd1171a9819cb7827321876ec155f7e1a5bfea87 | diff --git a/ckan/views/resource.py b/ckan/views/resource.py
--- a/ckan/views/resource.py
+++ b/ckan/views/resource.py
@@ -172,7 +172,11 @@ def download(package_type, id, resource_id, filename=None):
if rsc.get(u'url_type') == u'upload':
upload = uploader.get_resource_uploader(rsc)
filepath = upload.get_path(rsc[u'id'])
- return flask.send_file(filepath)
+ resp = flask.send_file(filepath)
+ if rsc.get('mimetype'):
+ resp.headers['Content-Type'] = rsc['mimetype']
+ return resp
+
elif u'url' not in rsc:
return base.abort(404, _(u'No download is available'))
return h.redirect_to(rsc[u'url'])
| diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py
--- a/ckan/tests/controllers/test_package.py
+++ b/ckan/tests/controllers/test_package.py
@@ -1065,6 +1065,29 @@ def test_anonymous_users_cannot_edit_resource(self, app):
)
[email protected]("clean_db", "with_plugins", "with_request_context")
+class TestResourceDownload(object):
+
+ def test_resource_download_content_type(self, create_with_upload, app):
+
+ dataset = factories.Dataset()
+ resource = create_with_upload(
+ u"hello,world", u"file.csv",
+ package_id=dataset[u"id"]
+ )
+
+ assert resource[u"mimetype"] == u"text/csv"
+ url = url_for(
+ u"{}_resource.download".format(dataset[u"type"]),
+ id=dataset[u"id"],
+ resource_id=resource[u"id"],
+ )
+
+ response = app.get(url)
+
+ assert response.headers[u"Content-Type"] == u"text/csv"
+
+
@pytest.mark.ckan_config("ckan.plugins", "image_view")
@pytest.mark.usefixtures("clean_db", "with_plugins", "with_request_context")
class TestResourceView(object):
| Embed file in another site problem with mime type
**CKAN version**
ckan_version": "2.9"
**Describe the bug**
Embed file in another site from ckan force to download because mime type is incorrect, always is embed with Content-Type: application/octet-stream
**Steps to reproduce**
Load PDF in ckan and use embed to display in another site, when you load page with embed file try download and not display pdf.
**Expected behavior**
Display embed pdf
| This is why I had to do the ugly NGINX workaround in the built-in PDF resource viewer PR #5541.
Hopefully, fixing this will allow that PR to be merged.
I had a look at this while working on the upgrade of ckanext-pdfview and it's potential replacement with builtin viewers submitted by @jqnatividad.
I do now believe that this is a bug on the CKAN side, or at least behavior that could be improved. As the reporter suggests all uploaded files that are downloaded from CKAN are returned with a `Content-Type: application/octet-stream` regardless of format. With the main use case of users downloading files from the browser this is generally fine as the browsers will generally auto-detect the format from the file name, but when integrating with other tools things start to break. For instance in the case described here, where you are embedding a CKAN-hosted PDF in another site, or trying to use the new builtin viewer in #5541 in Chrome.
We are extracting and storing the mime type [when a file is uploaded](https://github.com/ckan/ckan/blob/bb3b80eef5ff26ed4d0ef413a599a09b4eb0cef4/ckan/logic/action/update.py#L284:L286) so it makes sense to use it when serving the file in the [download endpoint](https://github.com/ckan/ckan/blob/bb3b80eef5ff26ed4d0ef413a599a09b4eb0cef4/ckan/views/resource.py#L175), eg:
```python
if rsc.get(u'url_type') == u'upload':
upload = uploader.get_resource_uploader(rsc)
filepath = upload.get_path(rsc[u'id'])
resp = flask.send_file(filepath)
if rsc.get('mimetype'):
resp.headers['Content-Type'] = rsc['mimetype']
return resp
```
Note that this does not affect the disposition of the downloaded file ( `Content-disposition` header), soI don't think we would be breaking anything with this change and we could consider it for backporting to 2.9
Any thoughts on this?
@pdelboca clearing your assignation so this gets raised in the next meeting | 2021-01-29T10:28:37 |
ckan/ckan | 5,930 | ckan__ckan-5930 | [
"5650"
] | bd1de98891a36e8d94b61b3fe56194e32f591cc5 | diff --git a/ckan/migration/migrate_package_activity.py b/ckan/migration/migrate_package_activity.py
--- a/ckan/migration/migrate_package_activity.py
+++ b/ckan/migration/migrate_package_activity.py
@@ -273,8 +273,11 @@ def print_errors(errors):
u'dataset - specify its name')
args = parser.parse_args()
assert args.config, u'You must supply a --config'
+ print(u'Loading config')
try:
- from ckan.lib.cli import load_config
+ from ckan.cli import load_config
+ from ckan.config.middleware import make_app
+ make_app(load_config(args.config))
except ImportError:
# for CKAN 2.6 and earlier
def load_config(config):
@@ -287,9 +290,7 @@ class Options(object):
cmd.options.config = config
cmd._load_config()
return
-
- print(u'Loading config')
- load_config(args.config)
+ load_config(args.config)
if not args.dataset:
migrate_all_datasets()
wipe_activity_detail(delete_activity_detail=args.delete)
| migrate_package_activity fails under Python 3
**CKAN version**
2.9 with Python 3.6
**Describe the bug**
The migrate_package_activity script fails when run under Python 3
Initially producing a module not found error for paste.script
After installing pastescript via pip the error becomes an attribute error
**Steps to reproduce**
Clean CKAN 2.9 install on Python 3
Use pg_restore to load database from an earlier version (2.8 in my case)
Run ckan db upgrade
Attempt to run migrate_package_activity
**Expected behavior**
Package activity should be migrated and script exit gracefully
**Additional details**
Initial Error:
```
Loading config
Traceback (most recent call last):
File "ckan/ckan/migration/migrate_package_activity.py", line 290, in <module>
load_config(args.config)
File "ckan/ckan/migration/migrate_package_activity.py", line 279, in load_config
from ckan.lib.cli import CkanCommand
File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 9, in <module>
import paste.script
ModuleNotFoundError: No module named 'paste.script'
```
After pip install pastescript
```
Traceback (most recent call last):
File "ckan/ckan/migration/migrate_package_activity.py", line 275, in <module>
from ckan.lib.cli import load_config
File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 212, in <module>
class CkanCommand(paste.script.command.Command):
AttributeError: module 'paste.script' has no attribute 'command'
```
| 2021-03-04T07:38:37 |
||
ckan/ckan | 5,937 | ckan__ckan-5937 | [
"5932"
] | 58d165235a9c53dfcbfd5f196d55ebb0faaf27d1 | diff --git a/ckan/config/environment.py b/ckan/config/environment.py
--- a/ckan/config/environment.py
+++ b/ckan/config/environment.py
@@ -286,7 +286,7 @@ def update_config():
# Enable pessimistic disconnect handling (added in SQLAlchemy 1.2)
# to eliminate database errors due to stale pooled connections
- config.setdefault('pool_pre_ping', True)
+ config.setdefault('sqlalchemy.pool_pre_ping', True)
# Initialize SQLAlchemy
engine = sqlalchemy.engine_from_config(config)
| sqlalchemy setting "pool_pre_ping"
**CKAN version**
Introduced in commit https://github.com/ckan/ckan/commit/ae9eb1360028a77b35506716eed2768349827806 which is related at least to 2.9.0, 2.9.1, 2.9.2.
**Describe the bug**
This is the ckan code:
```python
# Enable pessimistic disconnect handling (added in SQLAlchemy 1.2)
# to eliminate database errors due to stale pooled connections
config.setdefault('pool_pre_ping', True)
# Initialize SQLAlchemy
engine = sqlalchemy.engine_from_config(config)
```
This is the sqlalchemy function:
```python
def engine_from_config(configuration, prefix="sqlalchemy.", **kwargs):
```
I guess the `pool_pre_ping` config is not taken into account by sqlalchemy since it's missing the prefix.
| Sounds good, want to submit a PR @etj | 2021-03-05T09:34:26 |
|
ckan/ckan | 5,949 | ckan__ckan-5949 | [
"4805"
] | 58d165235a9c53dfcbfd5f196d55ebb0faaf27d1 | diff --git a/ckan/config/middleware/__init__.py b/ckan/config/middleware/__init__.py
--- a/ckan/config/middleware/__init__.py
+++ b/ckan/config/middleware/__init__.py
@@ -4,44 +4,12 @@
import logging
-import six
-from six.moves.urllib.parse import urlparse
-
-from ckan.lib.i18n import get_locales_from_config
from ckan.config.environment import load_environment
from ckan.config.middleware.flask_app import make_flask_stack
-from ckan.common import config
-from ckan.views import handle_i18n
log = logging.getLogger(__name__)
-if six.PY2:
- import webob
- from routes import request_config as routes_request_config
- from ckan.config.middleware.pylons_app import make_pylons_stack
-
- # This monkey-patches the webob request object because of the way it messes
- # with the WSGI environ.
-
- # Start of webob.requests.BaseRequest monkey patch
- original_charset__set = webob.request.BaseRequest._charset__set
-
- def custom_charset__set(self, charset):
- original_charset__set(self, charset)
- if self.environ.get('CONTENT_TYPE', '').startswith(';'):
- self.environ['CONTENT_TYPE'] = ''
-
- webob.request.BaseRequest._charset__set = custom_charset__set
-
- webob.request.BaseRequest.charset = property(
- webob.request.BaseRequest._charset__get,
- custom_charset__set,
- webob.request.BaseRequest._charset__del,
- webob.request.BaseRequest._charset__get.__doc__)
-
- # End of webob.requests.BaseRequest monkey patch
-
# This is a test Flask request context to be used internally.
# Do not use it!
_internal_test_request_context = None
@@ -56,117 +24,10 @@ def make_app(conf):
load_environment(conf)
flask_app = make_flask_stack(conf)
- if six.PY2:
- full_stack = True
- static_files = True
- pylons_app = make_pylons_stack(
- conf, full_stack, static_files)
-
- app = AskAppDispatcherMiddleware(
- {'pylons_app': pylons_app,
- 'flask_app': flask_app})
- else:
- app = flask_app
# Set this internal test request context with the configured environment so
# it can be used when calling url_for from tests
global _internal_test_request_context
_internal_test_request_context = flask_app._wsgi_app.test_request_context()
- return app
-
-
-class AskAppDispatcherMiddleware(object):
-
- '''
- Dispatches incoming requests to either the Flask or Pylons apps depending
- on the WSGI environ.
-
- Used to help transition from Pylons to Flask, and should be removed once
- Pylons has been deprecated and all app requests are handled by Flask.
-
- Each app should handle a call to 'can_handle_request(environ)', responding
- with a tuple:
- (<bool>, <app>, [<origin>])
- where:
- `bool` is True if the app can handle the payload url,
- `app` is the wsgi app returning the answer
- `origin` is an optional string to determine where in the app the url
- will be handled, e.g. 'core' or 'extension'.
-
- Order of precedence if more than one app can handle a url:
- Flask Extension > Pylons Extension > Flask Core > Pylons Core
- '''
-
- def __init__(self, apps=None):
- # Dict of apps managed by this middleware {<app_name>: <app_obj>, ...}
- self.apps = apps or {}
- self.default_locale = config.get('ckan.locale_default', 'en')
- self.locale_list = get_locales_from_config()
-
- def ask_around(self, environ):
- '''Checks with all apps whether they can handle the incoming request
- '''
- answers = [
- app._wsgi_app.can_handle_request(environ)
- for name, app in six.iteritems(self.apps)
- ]
- # Sort answers by app name
- answers = sorted(answers, key=lambda x: x[1])
- log.debug('Route support answers for {0} {1}: {2}'.format(
- environ.get('REQUEST_METHOD'), environ.get('PATH_INFO'),
- answers))
-
- return answers
-
- def __call__(self, environ, start_response):
- '''Determine which app to call by asking each app if it can handle the
- url and method defined on the eviron'''
-
- # Process locale part on the incoming request URL so it doesn't affect
- # the mapper queries
- handle_i18n(environ)
-
- app_name = 'pylons_app' # currently defaulting to pylons app
- answers = self.ask_around(environ)
- available_handlers = []
- for answer in answers:
- if len(answer) == 2:
- can_handle, asked_app = answer
- origin = 'core'
- else:
- can_handle, asked_app, origin = answer
- if can_handle:
- available_handlers.append('{0}_{1}'.format(asked_app, origin))
-
- # Enforce order of precedence:
- # Flask Extension > Pylons Extension > Flask Core > Pylons Core
- if available_handlers:
- if 'flask_app_extension' in available_handlers:
- app_name = 'flask_app'
- elif 'pylons_app_extension' in available_handlers:
- app_name = 'pylons_app'
- elif 'flask_app_core' in available_handlers:
- app_name = 'flask_app'
-
- log.debug('Serving request via {0} app'.format(app_name))
- environ['ckan.app'] = app_name
- if app_name == 'flask_app':
- # This request will be served by Flask, but we still need the
- # Pylons URL builder (Routes) to work
- parts = urlparse(
- config.get('ckan.site_url', 'http://0.0.0.0:5000'))
- request_config = routes_request_config()
- request_config.host = str(parts.netloc + parts.path)
- request_config.protocol = str(parts.scheme)
- request_config.mapper = config['routes.map']
-
- return self.apps[app_name](environ, start_response)
- else:
- # Although this request will be served by Pylons we still
- # need an application context in order for the Flask URL
- # builder to work and to be able to access the Flask config
- flask_app = self.apps['flask_app']._wsgi_app
-
- with flask_app.test_request_context():
- return self.apps[app_name](environ, start_response)
+ return flask_app
diff --git a/ckan/config/middleware/common_middleware.py b/ckan/config/middleware/common_middleware.py
--- a/ckan/config/middleware/common_middleware.py
+++ b/ckan/config/middleware/common_middleware.py
@@ -1,62 +1,14 @@
# encoding: utf-8
-"""Common middleware used by both Flask and Pylons app stacks."""
+"""Additional middleware used by the Flask app stack."""
import hashlib
-import cgi
import six
from six.moves.urllib.parse import unquote, urlparse
import sqlalchemy as sa
-from webob.request import FakeCGIBody
from ckan.common import config
-from ckan.lib.i18n import get_locales_from_config
-
-
-class RootPathMiddleware(object):
- '''
- Prevents the SCRIPT_NAME server variable conflicting with the ckan.root_url
- config. The routes package uses the SCRIPT_NAME variable and appends to the
- path and ckan addes the root url causing a duplication of the root path.
-
- This is a middleware to ensure that even redirects use this logic.
- '''
- def __init__(self, app, config):
- self.app = app
-
- def __call__(self, environ, start_response):
- # Prevents the variable interfering with the root_path logic
- if 'SCRIPT_NAME' in environ:
- environ['SCRIPT_NAME'] = ''
-
- return self.app(environ, start_response)
-
-
-class CloseWSGIInputMiddleware(object):
- '''
- webob.request.Request has habit to create FakeCGIBody. This leads(
- during file upload) to creating temporary files that are not closed.
- For long lived processes this means that for each upload you will
- spend the same amount of temporary space as size of uploaded
- file additionally, until server restart(this will automatically
- close temporary files).
-
- This middleware is supposed to close such files after each request.
- '''
- def __init__(self, app, config):
- self.app = app
-
- def __call__(self, environ, start_response):
- wsgi_input = environ['wsgi.input']
- if isinstance(wsgi_input, FakeCGIBody):
- for _, item in wsgi_input.vars.items():
- if not isinstance(item, cgi.FieldStorage):
- continue
- fp = getattr(item, 'fp', None)
- if fp is not None:
- fp.close()
- return self.app(environ, start_response)
class TrackingMiddleware(object):
diff --git a/ckan/config/middleware/pylons_app.py b/ckan/config/middleware/pylons_app.py
deleted file mode 100644
--- a/ckan/config/middleware/pylons_app.py
+++ /dev/null
@@ -1,289 +0,0 @@
-# encoding: utf-8
-
-import os
-import re
-
-from pylons.wsgiapp import PylonsApp
-
-from beaker.middleware import CacheMiddleware, SessionMiddleware
-from paste.cascade import Cascade
-from paste.registry import RegistryManager
-from paste.urlparser import StaticURLParser
-from ckan.common import asbool
-from paste.fileapp import _FileIter
-from pylons.middleware import ErrorHandler, StatusCodeRedirect
-from routes.middleware import RoutesMiddleware
-from repoze.who.config import WhoConfig
-from repoze.who.middleware import PluggableAuthenticationMiddleware
-from fanstatic import Fanstatic
-
-from ckan.plugins import PluginImplementations
-from ckan.plugins.interfaces import IMiddleware
-import ckan.lib.uploader as uploader
-from ckan.config.middleware import common_middleware
-from ckan.common import config
-
-import logging
-log = logging.getLogger(__name__)
-
-
-def make_pylons_stack(conf, full_stack=True, static_files=True,
- **app_conf):
- """Create a Pylons WSGI application and return it
-
- ``conf``
- The inherited configuration for this application. Normally from
- the [DEFAULT] section of the Paste ini file.
-
- ``full_stack``
- Whether this application provides a full WSGI stack (by default,
- meaning it handles its own exceptions and errors). Disable
- full_stack when this application is "managed" by another WSGI
- middleware.
-
- ``static_files``
- Whether this application serves its own static files; disable
- when another web server is responsible for serving them.
-
- ``app_conf``
- The application's local configuration. Normally specified in
- the [app:<name>] section of the Paste ini file (where <name>
- defaults to main).
-
- """
- # The Pylons WSGI app
- app = pylons_app = CKANPylonsApp()
-
- for plugin in PluginImplementations(IMiddleware):
- app = plugin.make_middleware(app, config)
-
- app = common_middleware.CloseWSGIInputMiddleware(app, config)
- app = common_middleware.RootPathMiddleware(app, config)
- # Routing/Session/Cache Middleware
- app = RoutesMiddleware(app, config['routes.map'])
- # we want to be able to retrieve the routes middleware to be able to update
- # the mapper. We store it in the pylons config to allow this.
- config['routes.middleware'] = app
- app = SessionMiddleware(app, config)
- app = CacheMiddleware(app, config)
-
- # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
- # app = QueueLogMiddleware(app)
- if asbool(config.get('ckan.use_pylons_response_cleanup_middleware',
- True)):
- app = execute_on_completion(app, config,
- cleanup_pylons_response_string)
-
- # Fanstatic
- fanstatic_enable_rollup = asbool(
- conf.get('fanstatic_enable_rollup', False))
- if asbool(config.get('debug', False)):
- fanstatic_config = {
- 'versioning': True,
- 'recompute_hashes': True,
- 'minified': False,
- 'bottom': True,
- 'bundle': False,
- 'rollup': fanstatic_enable_rollup,
- }
- else:
- fanstatic_config = {
- 'versioning': True,
- 'recompute_hashes': False,
- 'minified': True,
- 'bottom': True,
- 'bundle': True,
- 'rollup': fanstatic_enable_rollup,
- }
- root_path = config.get('ckan.root_path', None)
- if root_path:
- root_path = re.sub('/{{LANG}}', '', root_path)
- fanstatic_config['base_url'] = root_path
- app = Fanstatic(app, **fanstatic_config)
-
- for plugin in PluginImplementations(IMiddleware):
- try:
- app = plugin.make_error_log_middleware(app, config)
- except AttributeError:
- log.critical('Middleware class {0} is missing the method'
- 'make_error_log_middleware.'
- .format(plugin.__class__.__name__))
-
- if asbool(full_stack):
- # Handle Python exceptions
- app = ErrorHandler(app, conf, **config['pylons.errorware'])
-
- # Display error documents for 400, 403, 404 status codes (and
- # 500 when debug is disabled)
- if asbool(config['debug']):
- app = StatusCodeRedirect(app, [400, 403, 404])
- else:
- app = StatusCodeRedirect(app, [400, 403, 404, 500])
-
- # Initialize repoze.who
- who_parser = WhoConfig(conf['here'])
- who_parser.parse(open(conf['who.config_file']))
-
- app = PluggableAuthenticationMiddleware(
- app,
- who_parser.identifiers,
- who_parser.authenticators,
- who_parser.challengers,
- who_parser.mdproviders,
- who_parser.request_classifier,
- who_parser.challenge_decider,
- logging.getLogger('repoze.who'),
- logging.WARN, # ignored
- who_parser.remote_user_key
- )
-
- # Establish the Registry for this application
- app = RegistryManager(app, streaming=False)
-
- if asbool(static_files):
- # Serve static files
- static_max_age = None if not asbool(
- config.get('ckan.cache_enabled')) \
- else int(config.get('ckan.static_max_age', 3600))
-
- static_app = StaticURLParser(
- config['pylons.paths']['static_files'],
- cache_max_age=static_max_age)
- static_parsers = [static_app, app]
-
- storage_directory = uploader.get_storage_path()
- if storage_directory:
- path = os.path.join(storage_directory, 'storage')
- try:
- os.makedirs(path)
- except OSError as e:
- # errno 17 is file already exists
- if e.errno != 17:
- raise
-
- storage_app = StaticURLParser(path, cache_max_age=static_max_age)
- static_parsers.insert(0, storage_app)
-
- # Configurable extra static file paths
- extra_static_parsers = []
- for public_path in config.get(
- 'extra_public_paths', '').split(','):
- if public_path.strip():
- extra_static_parsers.append(
- StaticURLParser(public_path.strip(),
- cache_max_age=static_max_age)
- )
- app = Cascade(extra_static_parsers + static_parsers)
-
- # Prevent the host from request to be added to the new header location.
- app = common_middleware.HostHeaderMiddleware(app)
- # Tracking
- if asbool(config.get('ckan.tracking_enabled', 'false')):
- app = common_middleware.TrackingMiddleware(app, config)
-
- # Add a reference to the actual Pylons app so it's easier to access
- app._wsgi_app = pylons_app
-
- return app
-
-
-class CKANPylonsApp(PylonsApp):
-
- app_name = 'pylons_app'
-
- def can_handle_request(self, environ):
- '''
- Decides whether it can handle a request with the Pylons app by
- matching the request environ against the route mapper
-
- Returns (True, 'pylons_app', origin) if this is the case.
-
- origin can be either 'core' or 'extension' depending on where
- the route was defined.
-
- NOTE: There is currently a catch all route for GET requests to
- point arbitrary urls to templates with the same name:
-
- map.connect('/*url', controller='template', action='view')
-
- This means that this function will match all GET requests. This
- does not cause issues as the Pylons core routes are the last to
- take precedence so the current behaviour is kept, but it's worth
- keeping in mind.
- '''
-
- pylons_mapper = config['routes.map']
- match_route = pylons_mapper.routematch(environ=environ)
- if match_route:
- match, route = match_route
- origin = 'core'
- if hasattr(route, '_ckan_core') and not route._ckan_core:
- origin = 'extension'
- log.debug('Pylons route match: {0} Origin: {1}'.format(
- match, origin))
- return (True, self.app_name, origin)
- else:
- return (False, self.app_name)
-
-
-class CloseCallbackWrapper(object):
- def __init__(self, iterable, callback, environ):
- # pylons.fileapp expects app_iter to have `file` attribute.
- self.file = iterable
- self.callback = callback
- self.environ = environ
-
- def __iter__(self):
- """
- return a generator that passes through items from iterable
- then calls callback(environ).
- """
- try:
- for item in self.file:
- yield item
- except GeneratorExit:
- if hasattr(self.file, 'close'):
- self.file.close()
- raise
- finally:
- self.callback(self.environ)
-
-
-class FileIterWrapper(CloseCallbackWrapper, _FileIter):
- """Same CloseCallbackWrapper, just with _FileIter mixin.
-
- That will prevent pylons from converting file responses into
- in-memori lists.
- """
- pass
-
-
-def execute_on_completion(application, config, callback):
- """
- Call callback(environ) once complete response is sent
- """
-
- def inner(environ, start_response):
- try:
- result = application(environ, start_response)
- except Exception:
- callback(environ)
- raise
- # paste.fileapp converts non-file responses into list
- # In order to avoid interception of OOM Killer
- # file responses wrapped into generator with
- # _FileIter in parent tree.
- klass = CloseCallbackWrapper
- if isinstance(result, _FileIter):
- klass = FileIterWrapper
- return klass(result, callback, environ)
-
- return inner
-
-
-def cleanup_pylons_response_string(environ):
- try:
- msg = 'response cleared by pylons response cleanup middleware'
- environ['pylons.controller']._py_object.response._body = msg
- except (KeyError, AttributeError):
- pass
| diff --git a/ckan/tests/config/test_middleware.py b/ckan/tests/config/test_middleware.py
--- a/ckan/tests/config/test_middleware.py
+++ b/ckan/tests/config/test_middleware.py
@@ -1,7 +1,6 @@
# encoding: utf-8
import flask
-import mock
import pytest
import wsgiref
import six
@@ -12,68 +11,13 @@
import ckan.plugins as p
import ckan.tests.factories as factories
from ckan.common import config, _
-from ckan.config.middleware import AskAppDispatcherMiddleware
from ckan.config.middleware.flask_app import CKANFlask
-if six.PY2:
- from ckan.config.middleware.pylons_app import CKANPylonsApp
-else:
- CKANPylonsApp = object
-
-_test_controller = u"ckan.tests.config.test_middleware:MockPylonsController"
class MockRoutingPlugin(p.SingletonPlugin):
- p.implements(p.IRoutes)
p.implements(p.IBlueprint)
- controller = _test_controller
-
- def before_map(self, _map):
-
- _map.connect(
- u"/from_pylons_extension_before_map",
- controller=self.controller,
- action=u"view",
- )
-
- _map.connect(
- u"/from_pylons_extension_before_map_post_only",
- controller=self.controller,
- action=u"view",
- conditions={u"method": u"POST"},
- )
- # This one conflicts with an extension Flask route
- _map.connect(
- u"/pylons_and_flask", controller=self.controller, action=u"view"
- )
-
- # This one conflicts with a core Flask route
- _map.connect(u"/about", controller=self.controller, action=u"view")
-
- _map.connect(
- u"/pylons_route_flask_url_for",
- controller=self.controller,
- action=u"test_flask_url_for",
- )
- _map.connect(
- u"/pylons_translated",
- controller=self.controller,
- action=u"test_translation",
- )
-
- return _map
-
- def after_map(self, _map):
-
- _map.connect(
- u"/from_pylons_extension_after_map",
- controller=self.controller,
- action=u"view",
- )
-
- return _map
-
def get_blueprint(self):
# Create Blueprint for plugin
blueprint = Blueprint(self.name, self.__module__)
@@ -82,11 +26,6 @@ def get_blueprint(self):
u"/simple_flask", u"flask_plugin_view", flask_plugin_view
)
- blueprint.add_url_rule(
- u"/flask_route_pylons_url_for",
- u"flask_route_pylons_url_for",
- flask_plugin_view_url_for,
- )
blueprint.add_url_rule(
u"/flask_translated", u"flask_translated", flask_translated_view
)
@@ -98,28 +37,10 @@ def flask_plugin_view():
return u"Hello World, this is served from a Flask extension"
-def flask_plugin_view_url_for():
- url = h.url_for(controller=_test_controller, action=u"view")
- return u"This URL was generated by Pylons: {0}".format(url)
-
-
def flask_translated_view():
return _(u"Dataset")
-if six.PY2:
- class MockPylonsController(p.toolkit.BaseController):
- def view(self):
- return u"Hello World, this is served from a Pylons extension"
-
- def test_flask_url_for(self):
- url = h.url_for(u"api.get_api", ver=3)
- return u"This URL was generated by Flask: {0}".format(url)
-
- def test_translation(self):
- return _(u"Groups")
-
-
@pytest.fixture
def patched_app(app):
flask_app = app.flask_app
@@ -127,17 +48,9 @@ def patched_app(app):
def test_view():
return u"This was served from Flask"
- # This endpoint is defined both in Flask and in Pylons core
flask_app.add_url_rule(
u"/flask_core", view_func=test_view, endpoint=u"flask_core.index"
)
-
- # This endpoint is defined both in Flask and a Pylons extension
- flask_app.add_url_rule(
- u"/pylons_and_flask",
- view_func=test_view,
- endpoint=u"pylons_and_flask.index",
- )
return app
@@ -149,157 +62,6 @@ def test_flask_core_route_is_served(patched_app):
assert six.ensure_text(res.data) == u"This was served from Flask"
[email protected]_config(u"ckan.plugins", u"test_routing_plugin")
-class TestMiddlewareWithRoutingPlugin:
- @pytest.mark.skipif(six.PY3, reason=u"Do not test AskAppDispatcherMiddleware in Py3")
- def test_ask_around_pylons_extension_route_get_before_map(
- self, patched_app
- ):
- environ = {
- u"PATH_INFO": u"/from_pylons_extension_before_map",
- u"REQUEST_METHOD": u"GET",
- }
- wsgiref.util.setup_testing_defaults(environ)
-
- answers = patched_app.app.ask_around(environ)
-
- # Even though this route is defined in Pylons, there is catch all route
- # in Flask for all requests to serve static files with the same name,
- # so we get two positive answers
- assert answers == [
- (True, u"flask_app", u"core"),
- (True, u"pylons_app", u"extension"),
- ]
-
- @pytest.mark.skipif(six.PY3, reason=u"Do not test AskAppDispatcherMiddleware in Py3")
- def test_ask_around_pylons_extension_route_post(self, patched_app):
- environ = {
- u"PATH_INFO": u"/from_pylons_extension_before_map_post_only",
- u"REQUEST_METHOD": u"POST",
- }
- wsgiref.util.setup_testing_defaults(environ)
-
- answers = patched_app.app.ask_around(environ)
-
- assert answers == [
- (False, u"flask_app"),
- (True, u"pylons_app", u"extension"),
- ]
-
- @pytest.mark.skipif(six.PY3, reason=u"Do not test AskAppDispatcherMiddleware in Py3")
- def test_ask_around_pylons_extension_route_post_using_get(
- self, patched_app
- ):
- environ = {
- u"PATH_INFO": u"/from_pylons_extension_before_map_post_only",
- u"REQUEST_METHOD": u"GET",
- }
- wsgiref.util.setup_testing_defaults(environ)
-
- answers = patched_app.app.ask_around(environ)
-
- # Even though this route is defined in Pylons, there is catch all route
- # in Flask for all requests to serve static files with the same name,
- # so we get two positive answers
- assert answers == [
- (True, u"flask_app", u"core"),
- (False, u"pylons_app"),
- ]
-
- @pytest.mark.skipif(six.PY3, reason=u"Do not test AskAppDispatcherMiddleware in Py3")
- def test_ask_around_pylons_extension_route_get_after_map(
- self, patched_app
- ):
- environ = {
- u"PATH_INFO": u"/from_pylons_extension_after_map",
- u"REQUEST_METHOD": u"GET",
- }
- wsgiref.util.setup_testing_defaults(environ)
-
- answers = patched_app.app.ask_around(environ)
-
- # Even though this route is defined in Pylons, there is catch all route
- # in Flask for all requests to serve static files with the same name,
- # so we get two positive answers
- assert answers == [
- (True, u"flask_app", u"core"),
- (True, u"pylons_app", u"extension"),
- ]
-
- def test_flask_extension_route_is_served_by_flask(self, patched_app):
- res = patched_app.get(u"/simple_flask")
- assert res.status_code == 200
-
- @pytest.mark.skipif(six.PY3, reason=u"Do not test AskAppDispatcherMiddleware in Py3")
- def test_pylons_extension_route_is_served_by_pylons(self, patched_app):
- res = patched_app.get(u"/from_pylons_extension_before_map")
- assert (
- res.data == u"Hello World, this is served from a Pylons extension"
- )
-
- @pytest.mark.usefixtures(u"clean_db", u"with_request_context")
- def test_user_objects_in_g_normal_user(self, app):
- """
- A normal logged in user request will have expected user objects added
- to request.
- """
- username = factories.User()[u"name"]
- test_user_obj = model.User.by_name(username)
- app.get(
- u"/simple_flask",
- environ_overrides={u"REMOTE_USER": username.encode(u"ascii") if six.PY2 else username},
- )
- assert flask.g.user == username
- assert flask.g.userobj == test_user_obj
- assert flask.g.author == username
- assert flask.g.remote_addr == u"Unknown IP Address"
-
- @pytest.mark.usefixtures(u"clean_db")
- def test_user_objects_in_g_anon_user(self, app):
- """
- An anon user request will have expected user objects added to request.
- """
- with app.flask_app.app_context():
- app.get(u"/simple_flask", environ_overrides={u"REMOTE_USER": str(u"")})
- assert flask.g.user == u""
- assert flask.g.userobj is None
- assert flask.g.author == u"Unknown IP Address"
- assert flask.g.remote_addr == u"Unknown IP Address"
-
- @pytest.mark.usefixtures(u"clean_db", u"with_request_context")
- def test_user_objects_in_g_sysadmin(self, app):
- """
- A sysadmin user request will have expected user objects added to
- request.
- """
- user = factories.Sysadmin()
- test_user_obj = model.User.by_name(user[u"name"])
- app.get(
- u"/simple_flask",
- environ_overrides={u"REMOTE_USER": user[u"name"].encode(u"ascii") if six.PY2 else user[u"name"]},
- )
- assert flask.g.user == user[u"name"]
- assert flask.g.userobj == test_user_obj
- assert flask.g.author == user[u"name"]
- assert flask.g.remote_addr == u"Unknown IP Address"
-
- @pytest.mark.skipif(six.PY3, reason=u"Do not test AskAppDispatcherMiddleware in Py3")
- @pytest.mark.ckan_config(
- u"ckan.use_pylons_response_cleanup_middleware", True
- )
- def test_pylons_route_with_cleanup_middleware_activated(self, app):
- u"""Test the home page renders with the middleware activated
-
- We are just testing the home page renders without any troubles and that
- the middleware has not done anything strange to the response string"""
-
- response = app.get(url=u"/pylons_translated")
-
- assert response.status_code == 200
- # make sure we haven't overwritten the response too early.
- assert u"cleanup middleware" not in response.data
-
-
@pytest.mark.ckan_config(u"SECRET_KEY", u"super_secret_stuff")
def test_secret_key_is_used_if_present(app):
assert app.flask_app.config[u"SECRET_KEY"] == u"super_secret_stuff"
@@ -319,77 +81,3 @@ def test_no_beaker_secret_crashes(make_app):
# RuntimeError instead (thrown on `make_flask_stack`)
with pytest.raises(RuntimeError):
make_app()
-
-
[email protected](six.PY3, reason=u"Do not test AskAppDispatcherMiddleware in Py3")
[email protected](
- u"rv,app_base",
- [
- ((False, u"flask_app"), CKANFlask),
- ((True, u"pylons_app", u"core"), CKANPylonsApp),
- ],
-)
-def test_can_handle_request_with_environ(monkeypatch, app, rv, app_base):
- ckan_app = app.app
-
- handler = mock.Mock(return_value=rv)
- monkeypatch.setattr(app_base, u"can_handle_request", handler)
-
- environ = {u"PATH_INFO": str(u"/")}
- wsgiref.util.setup_testing_defaults(environ)
- start_response = mock.MagicMock()
- ckan_app(environ, start_response)
-
- assert handler.called_with(environ)
-
-
[email protected](six.PY3, reason=u"Do not test AskAppDispatcherMiddleware in Py3")
-def test_ask_around_is_called(monkeypatch, app):
- ask = mock.MagicMock()
- monkeypatch.setattr(AskAppDispatcherMiddleware, u"ask_around", ask)
- res = app.get(u"/")
- assert ask.called
- assert res.status_code == 404
-
-
[email protected](six.PY3, reason=u"Do not test AskAppDispatcherMiddleware in Py3")
-def test_ask_around_is_called_with_args(monkeypatch, app):
- ckan_app = app.app
-
- environ = {}
- start_response = mock.MagicMock()
- wsgiref.util.setup_testing_defaults(environ)
-
- ask = mock.MagicMock()
- monkeypatch.setattr(AskAppDispatcherMiddleware, u"ask_around", ask)
-
- ckan_app(environ, start_response)
- assert ask.called
- ask.assert_called_with(environ)
-
-
[email protected](six.PY3, reason=u"Do not test AskAppDispatcherMiddleware in Py3")
-def test_ask_around_flask_core_route_get(app):
- ckan_app = app.app
-
- environ = {u"PATH_INFO": u"/", u"REQUEST_METHOD": u"GET"}
- wsgiref.util.setup_testing_defaults(environ)
-
- answers = ckan_app.ask_around(environ)
-
- assert answers == [(True, u"flask_app", u"core"), (False, u"pylons_app")]
-
-
[email protected](six.PY3, reason=u"Do not test AskAppDispatcherMiddleware in Py3")
-def test_ask_around_flask_core_route_post(app):
- ckan_app = app.app
-
- environ = {u"PATH_INFO": u"/group/new", u"REQUEST_METHOD": u"POST"}
- wsgiref.util.setup_testing_defaults(environ)
-
- answers = ckan_app.ask_around(environ)
-
- assert answers == [
- (True, u"flask_app", u"core"),
- (False, u"pylons_app"),
- ]
diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py
--- a/ckan/tests/lib/test_helpers.py
+++ b/ckan/tests/lib/test_helpers.py
@@ -229,39 +229,6 @@ def test_url_for_flask_route_new_syntax_request_context(self, app):
generated_url = h.url_for("api.get_api", ver=3)
assert generated_url == url
- @pytest.mark.skipif(six.PY3, reason="Pylons was removed in Py3")
- @pytest.mark.ckan_config("ckan.plugins", "test_routing_plugin")
- @pytest.mark.usefixtures("with_plugins")
- def test_url_for_flask_request_using_pylons_url_for(self, app):
-
- res = app.get("/flask_route_pylons_url_for")
-
- assert u"This URL was generated by Pylons" in res.body
- assert u"/from_pylons_extension_before_map" in res.body
-
- @pytest.mark.skipif(six.PY3, reason="Pylons was removed in Py3")
- @pytest.mark.ckan_config("ckan.plugins", "test_routing_plugin")
- @pytest.mark.usefixtures("with_plugins")
- def test_url_for_pylons_request_using_flask_url_for(self, app):
-
- res = app.get("/pylons_route_flask_url_for")
-
- assert u"This URL was generated by Flask" in res.body
- assert u"/api/3" in res.body
-
- @pytest.mark.skipif(six.PY3, reason="Pylons was removed in Py3")
- @pytest.mark.ckan_config("ckan.plugins", "test_routing_plugin")
- @pytest.mark.usefixtures("with_plugins")
- def test_url_for_pylons_request_external(self):
-
- url = "http://example.com/from_pylons_extension_before_map"
- generated_url = h.url_for(
- controller="ckan.tests.config.test_middleware:MockPylonsController",
- action="view",
- _external=True,
- )
- assert generated_url == url
-
class TestHelpersRenderMarkdown(object):
@pytest.mark.parametrize(
diff --git a/ckan/tests/lib/test_i18n.py b/ckan/tests/lib/test_i18n.py
--- a/ckan/tests/lib/test_i18n.py
+++ b/ckan/tests/lib/test_i18n.py
@@ -140,7 +140,7 @@ def test_translations_from_extensions(self):
@pytest.mark.ckan_config(u"ckan.plugins", u"test_routing_plugin")
@pytest.mark.usefixtures(u"with_plugins")
-class TestI18nFlaskAndPylons(object):
+class TestI18nFlask(object):
def test_translation_works_on_flask_and_pylons(self, app):
resp = app.get(u"/flask_translated")
assert six.ensure_text(resp.data) == six.text_type(u"Dataset")
@@ -148,13 +148,6 @@ def test_translation_works_on_flask_and_pylons(self, app):
resp = app.get(u"/es/flask_translated")
assert six.ensure_text(resp.data) == six.text_type(u"Conjunto de datos")
- if six.PY2:
- resp = app.get(u"/pylons_translated")
- assert six.ensure_text(resp.data) == six.text_type(u"Groups")
-
- resp = app.get(u"/es/pylons_translated")
- assert six.ensure_text(resp.data) == six.text_type(u"Grupos")
-
@pytest.mark.ckan_config(u"ckan.i18n_directory", I18N_DUMMY_DIR)
def test_config_i18n_directory(self, app):
resp = app.get(u"/flask_translated")
@@ -162,10 +155,3 @@ def test_config_i18n_directory(self, app):
resp = app.get(u"/es/flask_translated")
assert six.ensure_text(resp.data) == six.text_type(u"Foo baz 123")
-
- if six.PY2:
- resp = app.get(u"/pylons_translated")
- assert six.ensure_text(resp.data) == six.text_type(u"Groups")
-
- resp = app.get(u"/es/pylons_translated")
- assert six.ensure_text(resp.data) == six.text_type(u"Bar Buz 321")
diff --git a/ckan/tests/test_coding_standards.py b/ckan/tests/test_coding_standards.py
--- a/ckan/tests/test_coding_standards.py
+++ b/ckan/tests/test_coding_standards.py
@@ -257,7 +257,6 @@ def find_unprefixed_string_literals(filename):
u"ckan/config/middleware/__init__.py",
u"ckan/config/middleware/common_middleware.py",
u"ckan/config/middleware/flask_app.py",
- u"ckan/config/middleware/pylons_app.py",
u"ckan/exceptions.py",
u"ckan/i18n/check_po_files.py",
u"ckan/lib/activity_streams.py",
| Remove AppDispatcher and Pylons middleware
TODO
#### Approach
#### Story points
| While I think of it, `paste.urlparser.StaticURLParser` is one of the middlewares that needs replacing in [pylons_app.py](https://github.com/ckan/ckan/blob/master/ckan/config/middleware/pylons_app.py). Probably this: http://flask.pocoo.org/docs/1.0/api/#flask.send_from_directory (which we already use for webassets) | 2021-03-08T11:27:30 |
ckan/ckan | 5,974 | ckan__ckan-5974 | [
"5097"
] | d43ce9bfd882f63c986711e2d59e186a58c8e489 | diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py
--- a/ckanext/datastore/backend/postgres.py
+++ b/ckanext/datastore/backend/postgres.py
@@ -389,7 +389,7 @@ def _where_clauses(data_dict, fields_types):
clause_str = u'_full_text @@ {0}'.format(ts_query_alias)
clauses.append((clause_str,))
elif isinstance(q, dict):
- lang = _fts_lang(data_dict.get('lang'))
+ lang = _fts_lang(data_dict.get('language'))
for field, value in six.iteritems(q):
if field not in fields_types:
continue
@@ -573,7 +573,7 @@ def _build_fts_indexes(connection, data_dict, sql_index_str_method, fields):
default_fts_lang = config.get('ckan.datastore.default_fts_lang')
if default_fts_lang is None:
default_fts_lang = u'english'
- fts_lang = data_dict.get('lang', default_fts_lang)
+ fts_lang = data_dict.get('language', default_fts_lang)
# create full-text search indexes
def to_tsvector(x):
@@ -1774,7 +1774,7 @@ def datastore_search(self, context, data_dict, fields_types, query_dict):
fields = data_dict.get('fields')
ts_query, rank_columns = _textsearch_query(
- _fts_lang(data_dict.get('lang')),
+ _fts_lang(data_dict.get('language')),
data_dict.get('q'),
data_dict.get('plain', True))
# mutate parameter to add rank columns for _result_fields
| diff --git a/ckanext/datastore/tests/test_db.py b/ckanext/datastore/tests/test_db.py
--- a/ckanext/datastore/tests/test_db.py
+++ b/ckanext/datastore/tests/test_db.py
@@ -90,7 +90,7 @@ def test_creates_fts_index_on_textual_fields_can_overwrite_lang_using_lang_param
connection = mock.MagicMock()
context = {"connection": connection}
resource_id = "resource_id"
- data_dict = {"resource_id": resource_id, "lang": "french"}
+ data_dict = {"resource_id": resource_id, "language": "french"}
db.create_indexes(context, data_dict)
diff --git a/ckanext/datastore/tests/test_plugin.py b/ckanext/datastore/tests/test_plugin.py
--- a/ckanext/datastore/tests/test_plugin.py
+++ b/ckanext/datastore/tests/test_plugin.py
@@ -85,7 +85,7 @@ def test_can_overwrite_default_fts_lang_using_config_variable(self):
@pytest.mark.ckan_config("ckan.datastore.default_fts_lang", "simple")
def test_lang_parameter_overwrites_default_fts_lang(self):
expected_ts_query = ", plainto_tsquery('french', 'foo') \"query\""
- data_dict = {"q": "foo", "lang": "french"}
+ data_dict = {"q": "foo", "language": "french"}
result = self._datastore_search(data_dict=data_dict)
@@ -95,7 +95,7 @@ def test_fts_rank_column_uses_lang_when_casting_to_tsvector(self):
expected_select_content = (
u"to_tsvector('french', cast(\"country\" as text))"
)
- data_dict = {"q": {"country": "Brazil"}, "lang": "french"}
+ data_dict = {"q": {"country": "Brazil"}, "language": "french"}
result = self._datastore_search(data_dict=data_dict, fields_types={})
assert expected_select_content in result["select"][0]
@@ -156,7 +156,7 @@ def test_fts_where_clause_lang_can_be_overwritten_using_lang_param(self):
u' @@ "query country"',
)
]
- data_dict = {"q": {"country": "Brazil"}, "lang": "french"}
+ data_dict = {"q": {"country": "Brazil"}, "language": "french"}
fields_types = {"country": "text"}
result = self._datastore_search(
@@ -177,7 +177,7 @@ def test_fts_adds_where_clause_on_full_text_when_querying_non_indexed_fields(
u' @@ "query country"',
),
]
- data_dict = {"q": {"country": "Brazil"}, "lang": "english"}
+ data_dict = {"q": {"country": "Brazil"}, "language": "english"}
fields_types = {"country": "non-indexed field type"}
result = self._datastore_search(
| Datastore_search full-text language parameter is not parsed correctly
### CKAN Version if known (or site URL)
2.8.3
### Please describe the expected behaviour
The full-text language used for `datastore_search` should be controlled by the 'language' parameter.
### Please describe the actual behaviour
The 'language' parameter to `/api/action/datastore_search` is ignored.
Code inspection indicates that `ckanext/datastore/backend/postgres.py` expects the parameter to be called "lang", but the validation in `ckanext/datastore/plugin.py` only permits a parameter called "language", which is then thrown away.
### What steps can be taken to reproduce the issue?
- Perform a datastore search via `/api/action/datastore_search?resource_id=<id>&q=<query>&language=english`
- Perform a datastore search via `/api/action/datastore_search?resource_id=<id>&q=<query>&language=spanish`
- Perform a datastore search via `/api/action/datastore_search?resource_id=<id>&q=<query>&language=simple`
- Perform a datastore search via `/api/action/datastore_search?resource_id=<id>&q=<query>&language=klingon`
All queries will produce the same results.
- Perform a datastore search via `/api/action/datastore_search?resource_id=<id>&q=<query>&lang=simple`
The "lang" parameter is rejected.
| The problem is with the inconsistent with the params. If you can provide PR with the fix will be great
Should the parameter be called "language" as the validation expects, or "lang" as the action expects? I suppose using "language" means no external change.
Hi , I have been investigating the point of code where the change needs to take place, mostly in `/ckanext/datastore` of `datastore_search`, location with the following files:
1) `/ckan/ckanext/datastore/logic/action.py `
2) `/ckan/ckanext/datastore/backend/postgres.py
`
But, when I request the API:
`http://ckan-hostname:port/api/3/action/datastore_search?limit=5&resource_id=ce41bda8-9ff6-457a-92e9-f664f9b8bba0`
After debugging and inserting the checkpoint in (`datastore_search `method) It doesn't stops at the breakpoint. Could you please suggest whether is there any other location apart from the above which I have stated ?
Thanks ! | 2021-03-20T16:43:09 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.