Skip to content

Commit

Permalink
Adds unit tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
Pavle Jonoski committed Apr 15, 2020
1 parent 43be52c commit c6f82b4
Show file tree
Hide file tree
Showing 8 changed files with 175 additions and 7 deletions.
4 changes: 4 additions & 0 deletions ckanext/knowledgehub/cli/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ def db():

@db.command(u'init', short_help=u'Initialize Knowledgehub tables')
def init():
init_db()


def init_db():
u'''Initialising the Knowledgehub tables'''
log.info(u"Initialize Knowledgehub tables")
try:
Expand Down
13 changes: 13 additions & 0 deletions ckanext/knowledgehub/logic/action/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -1654,6 +1654,19 @@ def notification_create(context, data_dict):


def post_create(context, data_dict):
'''Creates a new post to be shown in the news feed.
:param title: `str`, the post title. Required.
:param description: `str`, the post description. Optional.
:param entity_type: `str`, the type of the referenced entity. May be one of
`dashboard`, `dataset`, `research_question` or `visualization`.
Optional.
:param entity_ref: `str`, the ID (reference, like dataset ID or dashboard
ID) of the refrenced entity in the post. Required if `entity_type`
is set.
:returns: `dict`, the newly created post data.
'''
entities_actions = {
'dashboard': 'dashboard_show',
'dataset': 'package_show',
Expand Down
6 changes: 6 additions & 0 deletions ckanext/knowledgehub/logic/action/delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,12 @@ def delete_package_from_hdx(context, data_dict):


def post_delete(context, data_dict):
'''Deletes a newsfeed post.
Only sysadmins and the post author can delete the post.
:param id: `str`, the post ID. Required.
'''
if 'id' not in data_dict:
raise logic.ValidationError({
'id': _('Missing Value'),
Expand Down
25 changes: 25 additions & 0 deletions ckanext/knowledgehub/logic/action/get.py
Original file line number Diff line number Diff line change
Expand Up @@ -2144,6 +2144,19 @@ def group_list_for_user(context, data_dict):


def post_show(context, data_dict):
'''Looks up a newsfeed post by its id.
:param id: `str`, the post id.
:param with_comments: `bool`, default `False`, if set to `True`, returns
the comments to this post as well.
:param with_related_entity: `bool`, default `True`, if set to `True` and
the post has a related entity (such as dataset, dashboard etc), it will
fetch the data for that entity as well.
:param with_user_info: `bool`, default `True`. If set to true, returns the
post author info.
:returns: `dict`, the post data.
'''
check_access('post_show', context, data_dict)

post_id = data_dict.get('id')
Expand Down Expand Up @@ -2202,6 +2215,18 @@ def post_show(context, data_dict):


def post_search(context, data_dict):
'''Performs a search for posts based on a user query.
:param text: `str`, the search query string. Required.
:param sort: `str`, the sort string. Optional.
:param page: `int`, which page to fetch (starting from 1). Optional,
default is 1.
:param limit: `int`, how many items per page to fetch. Optional, default is
20.
:returns: `dict`, the search result dict containing: `count` - the number
of results and `items` - a `list` of posts.
'''
check_access('post_search', context, data_dict)

if 'sort' in data_dict:
Expand Down
15 changes: 15 additions & 0 deletions ckanext/knowledgehub/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,22 @@
ValidationError = logic.ValidationError

_TIMEOUT = 60000 # milliseconds
_DB_INITIALIZED = False

log = getLogger(__name__)


def _init_knowledgehub_database():
global _DB_INITIALIZED
if _DB_INITIALIZED:
log.debug('Database already initialized')
return

from ckanext.knowledgehub.cli.db import init_db

init_db()


class KnowledgehubPlugin(plugins.SingletonPlugin, DefaultDatasetForm,
DefaultPermissionLabels):
plugins.implements(plugins.IConfigurer)
Expand Down Expand Up @@ -92,6 +104,9 @@ def update_config(self, config_):
hdx_key=hdx_api_key
)

# Eliminates the need to re-initialize the database when model changes.
_init_knowledgehub_database()

# IBlueprint
def get_blueprint(self):
return _register_blueprints()
Expand Down
104 changes: 102 additions & 2 deletions ckanext/knowledgehub/tests/test_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from ckan import plugins
from ckan.tests import helpers
from ckan.plugins import toolkit
from ckan import logic
from ckan import model
from datetime import datetime
from ckan.common import config
Expand Down Expand Up @@ -44,6 +45,7 @@
Visualization,
DataQualityMetrics as DataQualityMetricsModel,
ResourceValidate,
Posts,
)
from ckanext.knowledgehub.model.keyword import extend_tag_table
from ckanext.knowledgehub.lib.rnn import PredictiveSearchWorker
Expand Down Expand Up @@ -530,7 +532,6 @@ def test_resource_validate_create(self):
assert_equals(rv.get('what'), 'The resource is invalid!')
assert_equals(rv.get('resource'), resource.get('id'))


@monkey_patch(Dataset, 'read_from_hdx', mock.Mock())
@monkey_patch(Resource, 'delete_from_hdx', mock.Mock())
def test_delete_package_from_hdx(self):
Expand All @@ -540,7 +541,6 @@ def test_delete_package_from_hdx(self):
delete_pkg = delete_actions.delete_package_from_hdx(ctx, dataset)
assert_equals(delete_pkg, None)


@monkey_patch(Dataset, 'read_from_hdx', mock.Mock())
@monkey_patch(Dataset, 'check_required_fields', mock.Mock())
@monkey_patch(Dataset, 'create_in_hdx', mock.Mock())
Expand Down Expand Up @@ -629,6 +629,35 @@ def test_upsert_dataset_to_hdx(self):

assert_equals(push_to_hdx, None)

def test_post_create(self):
context = get_context()
rq = toolkit.get_action('research_question_create')(
context,
{
'title': 'Test research question for post',
'name': 'test-research-question-for-post',
}
)

post = toolkit.get_action('post_create')(
context,
{
'title': 'Test post rq 1',
'description': 'Test post description',
'entity_type': 'research_question',
'entity_ref': rq['id']
}
)

assert_true(post is not None)
assert_true(post.get('id') is not None)
assert_equals(post.get('title'), 'Test post rq 1')
assert_equals(post.get('description'), 'Test post description')
assert_equals(post.get('entity_type'), 'research_question')
assert_equals(post.get('entity_ref'), rq['id'])
assert_true(post.get('created_by') is not None)
assert_true(post.get('created_at') is not None)


class TestKWHGetActions(ActionsBase):

Expand Down Expand Up @@ -1225,6 +1254,55 @@ def test_group_list_for_user(self):
assert_true(groups is not None)
assert_equals(len(groups), 1)

def test_post_show(self):
context = get_context()
post = toolkit.get_action('post_create')(context, {
'title': 'Post 3',
'description': 'Post 3 description',
})

result = toolkit.get_action('post_show')(context, {
'id': post['id'],
})

assert_true(result is not None)
assert_true(result.get('author') is not None)

@monkey_patch(Posts, 'search_index', mock.Mock())
def test_post_search(self):
context = get_context()
p1 = toolkit.get_action('post_create')(context, {
'title': 'Simple test',
'description': 'simple test',
})

p2 = toolkit.get_action('post_create')(context, {
'title': 'Other value',
'description': 'other',
})

class _Results:

def __init__(self, hits, docs, page, page_size, facets, stats):
self.hits = hits
self.docs = docs
self.page = page
self.page_size = page_size
self.facets = facets
self.stats = stats

Posts.search_index.return_value = _Results(2, [p1, p2], 1, 20, {}, {})

results = toolkit.get_action('post_search')(
context,
{
'text': '*',
}
)

assert_true(results is not None)
assert_true(results.get('count', 0) == 2)


class TestKWHDeleteActions(ActionsBase):

Expand Down Expand Up @@ -1448,6 +1526,28 @@ def test_package_delete(self):

assert_equals(r, None)

def test_post_delete(self):
context = get_context()
post = toolkit.get_action('post_create')(context, {
'title': 'Post 2',
'description': 'Post 2 description',
})

result = toolkit.get_action('post_show')(context, {
'id': post['id'],
})

assert_true(result is not None)

toolkit.get_action('post_delete')(context, {'id': post['id']})

not_found = False
try:
toolkit.get_action('post_show')(context, {'id': post['id']})
except logic.NotFound:
not_found = True
assert_true(not_found)


class TestKWHUpdateActions(ActionsBase):

Expand Down
10 changes: 7 additions & 3 deletions ckanext/knowledgehub/views/newsfeed.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def _get_context():
def index():
u'''List all news on the feed.
'''
default_limit = int(config.get('ckanext.knowledgehub.news_per_page', '20'))
context = _get_context()
text = request.args.get('q', '').strip()
page = request.args.get('page', '').strip()
Expand All @@ -57,9 +58,9 @@ def index():
if limit:
limit = int(limit)
if limit < 0:
limit = 20
limit = default_limit
else:
limit = 20
limit = default_limit

partial = partial in ['true', 'yes', '1', 't']

Expand Down Expand Up @@ -93,7 +94,8 @@ def index():


def view(id):

'''View the post with the given ID.
'''
context = _get_context()

post = None
Expand Down Expand Up @@ -124,6 +126,8 @@ def view(id):


def delete(id):
'''Delete the post with the given ID.
'''
context = _get_context()

try:
Expand Down
5 changes: 3 additions & 2 deletions ckanext/knowledgehub/views/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,7 @@ def profile_set_interests():


def user_posts():
default_limit = int(config.get('ckanext.knowledgehub.news_per_page', '20'))
page = request.args.get('page', '').strip()
limit = request.args.get('limit', '').strip()
partial = request.args.get('partial', 'false').lower()
Expand All @@ -418,9 +419,9 @@ def user_posts():
if limit:
limit = int(limit)
if limit < 0:
limit = 20
limit = default_limit
else:
limit = 20
limit = default_limit

partial = partial in ['true', 'yes', '1', 't']
context = {
Expand Down

0 comments on commit c6f82b4

Please sign in to comment.