def test_create(self): self.log_user() rev = '27cd5cce30c96924232dffcd24178a07ffeb5dfc' text = u'CommentOnRevision' params = {'text': text} response = self.app.post(url(controller='changeset', action='comment', repo_name=HG_REPO, revision=rev), params=params) # Test response... self.assertEqual(response.status, '302 Found') response.follow() response = self.app.get(url(controller='changeset', action='index', repo_name=HG_REPO, revision=rev)) # test DB self.assertEqual(ChangesetComment.query().count(), 1) response.mustcontain('''<div class="comments-number">%s comment ''' '''(0 inline)</div>''' % 1) self.assertEqual(Notification.query().count(), 1) self.assertEqual(ChangesetComment.query().count(), 1) notification = Notification.query().all()[0] ID = ChangesetComment.query().first().comment_id self.assertEqual(notification.type_, Notification.TYPE_CHANGESET_COMMENT) sbj = (u'/vcs_test_hg/changeset/' '27cd5cce30c96924232dffcd24178a07ffeb5dfc#comment-%s' % ID) print "%s vs %s" % (sbj, notification.subject) self.assertTrue(sbj in notification.subject)
def _clean_notifications(self, request, pylonsapp): for n in Notification.query().all(): Session().delete(n) Session().commit() assert [] == Notification.query().all() assert [] == UserNotification.query().all()
def test_create_notification(self): self.assertEqual([], Notification.query().all()) self.assertEqual([], UserNotification.query().all()) usrs = [self.u1, self.u2] notification = NotificationModel().create(created_by=self.u1, subject=u'subj', body=u'hi there', recipients=usrs) Session().commit() u1 = User.get(self.u1) u2 = User.get(self.u2) u3 = User.get(self.u3) notifications = Notification.query().all() self.assertEqual(len(notifications), 1) self.assertEqual(notifications[0].recipients, [u1, u2]) self.assertEqual(notification.notification_id, notifications[0].notification_id) unotification = UserNotification.query()\ .filter(UserNotification.notification == notification).all() self.assertEqual(len(unotification), len(usrs)) self.assertEqual(set([x.user.user_id for x in unotification]), set(usrs))
def test_create_inline(self): self.log_user() rev = "27cd5cce30c96924232dffcd24178a07ffeb5dfc" text = u"CommentOnRevision" f_path = "vcs/web/simplevcs/views/repository.py" line = "n1" params = {"text": text, "f_path": f_path, "line": line} response = self.app.post( url(controller="changeset", action="comment", repo_name=HG_REPO, revision=rev), params=params ) # Test response... self.assertEqual(response.status, "302 Found") response.follow() response = self.app.get(url(controller="changeset", action="index", repo_name=HG_REPO, revision=rev)) # test DB self.assertEqual(ChangesetComment.query().count(), 1) response.mustcontain("""<div class="comments-number">0 comment(s)""" """ (%s inline)</div>""" % 1) response.mustcontain( """<div style="display:none" class="inline-comment-placeholder" """ """path="vcs/web/simplevcs/views/repository.py" """ """target_id="vcswebsimplevcsviewsrepositorypy">""" ) self.assertEqual(Notification.query().count(), 1) self.assertEqual(ChangesetComment.query().count(), 1) notification = Notification.query().all()[0] ID = ChangesetComment.query().first().comment_id self.assertEqual(notification.type_, Notification.TYPE_CHANGESET_COMMENT) sbj = u"/vcs_test_hg/changeset/" "27cd5cce30c96924232dffcd24178a07ffeb5dfc#comment-%s" % ID print "%s vs %s" % (sbj, notification.subject) self.assertTrue(sbj in notification.subject)
def test_create(self): self.log_user() rev = "27cd5cce30c96924232dffcd24178a07ffeb5dfc" text = u"CommentOnRevision" params = {"text": text} response = self.app.post( url(controller="changeset", action="comment", repo_name=HG_REPO, revision=rev), params=params ) # Test response... self.assertEqual(response.status, "302 Found") response.follow() response = self.app.get(url(controller="changeset", action="index", repo_name=HG_REPO, revision=rev)) # test DB self.assertEqual(ChangesetComment.query().count(), 1) self.assertTrue("""<div class="comments-number">%s """ """comment(s) (0 inline)</div>""" % 1 in response.body) self.assertEqual(Notification.query().count(), 1) self.assertEqual(ChangesetComment.query().count(), 1) notification = Notification.query().all()[0] ID = ChangesetComment.query().first().comment_id self.assertEqual(notification.type_, Notification.TYPE_CHANGESET_COMMENT) sbj = u"/vcs_test_hg/changeset/" "27cd5cce30c96924232dffcd24178a07ffeb5dfc#comment-%s" % ID print "%s vs %s" % (sbj, notification.subject) self.assertTrue(sbj in notification.subject)
def test_create(self): self.log_user() rev = '27cd5cce30c96924232dffcd24178a07ffeb5dfc' text = u'CommentOnRevision' params = {'text': text} response = self.app.post(url(controller='changeset', action='comment', repo_name=HG_REPO, revision=rev), params=params) # Test response... self.assertEqual(response.status, '302 Found') response.follow() response = self.app.get(url(controller='changeset', action='index', repo_name=HG_REPO, revision=rev)) # test DB self.assertEqual(ChangesetComment.query().count(), 1) self.assertTrue('''<div class="comments-number">%s ''' '''comment(s) (0 inline)</div>''' % 1 in response.body) self.assertEqual(Notification.query().count(), 1) self.assertEqual(ChangesetComment.query().count(), 1) notification = Notification.query().all()[0] ID = ChangesetComment.query().first().comment_id self.assertEqual(notification.type_, Notification.TYPE_CHANGESET_COMMENT) sbj = (u'/vcs_test_hg/changeset/' '27cd5cce30c96924232dffcd24178a07ffeb5dfc#comment-%s' % ID) print "%s vs %s" % (sbj, notification.subject) self.assertTrue(sbj in notification.subject)
def test_create_inline(self, backend): self.log_user() commit_id = backend.repo.get_commit('300').raw_id text = u'CommentOnCommit' f_path = 'vcs/web/simplevcs/views/repository.py' line = 'n1' params = { 'text': text, 'f_path': f_path, 'line': line, 'csrf_token': self.csrf_token } self.app.post(url(controller='changeset', action='comment', repo_name=backend.repo_name, revision=commit_id), params=params) response = self.app.get( url(controller='changeset', action='index', repo_name=backend.repo_name, revision=commit_id)) # test DB assert ChangesetComment.query().count() == 1 assert_comment_links(response, 0, ChangesetComment.query().count()) response.mustcontain( '''class="inline-comment-placeholder" ''' '''path="vcs/web/simplevcs/views/repository.py" ''' '''target_id="vcswebsimplevcsviewsrepositorypy"''') assert Notification.query().count() == 1 assert ChangesetComment.query().count() == 1 notification = Notification.query().all()[0] comment = ChangesetComment.query().first() assert notification.type_ == Notification.TYPE_CHANGESET_COMMENT assert comment.revision == commit_id sbj = 'commented on commit of {0}'.format(backend.repo_name) assert sbj in notification.subject lnk = (u'/{0}/changeset/{1}#comment-{2}'.format( backend.repo_name, commit_id, comment.comment_id)) assert lnk in notification.body assert 'on line n1' in notification.body
def test_notification_counter(self): self._clean_notifications() self.assertEqual([], Notification.query().all()) self.assertEqual([], UserNotification.query().all()) NotificationModel().create(created_by=self.u1, subject=u'title', body=u'hi there_delete', recipients=[self.u3, self.u1]) Session().commit() self.assertEqual(NotificationModel() .get_unread_cnt_for_user(self.u1), 1) self.assertEqual(NotificationModel() .get_unread_cnt_for_user(self.u2), 0) self.assertEqual(NotificationModel() .get_unread_cnt_for_user(self.u3), 1) notification = NotificationModel().create(created_by=self.u1, subject=u'title', body=u'hi there3', recipients=[self.u3, self.u1, self.u2]) Session().commit() self.assertEqual(NotificationModel() .get_unread_cnt_for_user(self.u1), 2) self.assertEqual(NotificationModel() .get_unread_cnt_for_user(self.u2), 1) self.assertEqual(NotificationModel() .get_unread_cnt_for_user(self.u3), 2)
def test_delete_association(self): notification = NotificationModel().create( created_by=self.u1, notification_subject=u'title', notification_body=u'hi there3', recipients=[self.u3, self.u1, self.u2]) Session().commit() unotification = (UserNotification.query().filter( UserNotification.notification == notification).filter( UserNotification.user_id == self.u3).scalar()) assert unotification.user_id == self.u3 NotificationModel().delete(self.u3, notification.notification_id) Session().commit() u3notification = (UserNotification.query().filter( UserNotification.notification == notification).filter( UserNotification.user_id == self.u3).scalar()) assert u3notification is None # notification object is still there assert Notification.query().all() == [notification] # u1 and u2 still have assignments u1notification = (UserNotification.query().filter( UserNotification.notification == notification).filter( UserNotification.user_id == self.u1).scalar()) assert u1notification is not None u2notification = (UserNotification.query().filter( UserNotification.notification == notification).filter( UserNotification.user_id == self.u2).scalar()) assert u2notification is not None
def test_create_with_mention(self): self.log_user() rev = '27cd5cce30c96924232dffcd24178a07ffeb5dfc' text = u'@test_regular check CommentOnRevision' params = {'text': text} response = self.app.post(url(controller='changeset', action='comment', repo_name=HG_REPO, revision=rev), params=params) # Test response... self.assertEqual(response.status, '302 Found') response.follow() response = self.app.get( url(controller='changeset', action='index', repo_name=HG_REPO, revision=rev)) # test DB self.assertEqual(ChangesetComment.query().count(), 1) response.mustcontain('''<div class="comments-number">%s ''' '''comment (0 inline)</div>''' % 1) self.assertEqual(Notification.query().count(), 2) users = [x.user.username for x in UserNotification.query().all()] # test_regular get's notification by @mention self.assertEqual(sorted(users), [u'test_admin', u'test_regular'])
def test_create_with_mention(self): self.log_user() rev = '27cd5cce30c96924232dffcd24178a07ffeb5dfc' text = u'@test_regular check CommentOnRevision' params = {'text':text} response = self.app.post(url(controller='changeset', action='comment', repo_name=HG_REPO, revision=rev), params=params) # Test response... self.assertEqual(response.status, '302 Found') response.follow() response = self.app.get(url(controller='changeset', action='index', repo_name=HG_REPO, revision=rev)) # test DB self.assertEqual(ChangesetComment.query().count(), 1) response.mustcontain('''<div class="comments-number">%s ''' '''comment (0 inline)</div>''' % 1) self.assertEqual(Notification.query().count(), 2) users = [x.user.username for x in UserNotification.query().all()] # test_regular get's notification by @mention self.assertEqual(sorted(users), [u'test_admin', u'test_regular'])
def test_notification_counter(self): self._clean_notifications() self.assertEqual([], Notification.query().all()) self.assertEqual([], UserNotification.query().all()) NotificationModel().create(created_by=self.u1, subject=u'title', body=u'hi there_delete', recipients=[self.u3, self.u1]) Session.commit() self.assertEqual(NotificationModel().get_unread_cnt_for_user(self.u1), 1) self.assertEqual(NotificationModel().get_unread_cnt_for_user(self.u2), 0) self.assertEqual(NotificationModel().get_unread_cnt_for_user(self.u3), 1) notification = NotificationModel().create( created_by=self.u1, subject=u'title', body=u'hi there3', recipients=[self.u3, self.u1, self.u2]) Session.commit() self.assertEqual(NotificationModel().get_unread_cnt_for_user(self.u1), 2) self.assertEqual(NotificationModel().get_unread_cnt_for_user(self.u2), 1) self.assertEqual(NotificationModel().get_unread_cnt_for_user(self.u3), 2)
def test_create_with_mention(self, backend): self.log_user() commit_id = backend.repo.get_commit('300').raw_id text = u'@test_regular check CommentOnCommit' params = {'text': text, 'csrf_token': self.csrf_token} self.app.post(url(controller='changeset', action='comment', repo_name=backend.repo_name, revision=commit_id), params=params) response = self.app.get( url(controller='changeset', action='index', repo_name=backend.repo_name, revision=commit_id)) # test DB assert ChangesetComment.query().count() == 1 assert_comment_links(response, ChangesetComment.query().count(), 0) notification = Notification.query().one() assert len(notification.recipients) == 2 users = [x.username for x in notification.recipients] # test_regular gets notification by @mention assert sorted(users) == [u'test_admin', u'test_regular']
def test_delete_association(self): self.assertEqual([], Notification.query().all()) self.assertEqual([], UserNotification.query().all()) notification = NotificationModel().create( created_by=self.u1, subject=u'title', body=u'hi there3', recipients=[self.u3, self.u1, self.u2]) Session.commit() unotification = UserNotification.query()\ .filter(UserNotification.notification == notification)\ .filter(UserNotification.user_id == self.u3)\ .scalar() self.assertEqual(unotification.user_id, self.u3) NotificationModel().delete(self.u3, notification.notification_id) Session.commit() u3notification = UserNotification.query()\ .filter(UserNotification.notification == notification)\ .filter(UserNotification.user_id == self.u3)\ .scalar() self.assertEqual(u3notification, None) # notification object is still there self.assertEqual(Notification.query().all(), [notification]) #u1 and u2 still have assignments u1notification = UserNotification.query()\ .filter(UserNotification.notification == notification)\ .filter(UserNotification.user_id == self.u1)\ .scalar() self.assertNotEqual(u1notification, None) u2notification = UserNotification.query()\ .filter(UserNotification.notification == notification)\ .filter(UserNotification.user_id == self.u2)\ .scalar() self.assertNotEqual(u2notification, None)
def cleanup(self): for x in ChangesetComment.query().all(): Session().delete(x) Session().commit() for x in Notification.query().all(): Session().delete(x) Session().commit()
def setUp(self): for x in ChangesetComment.query().all(): Session().delete(x) Session().commit() for x in Notification.query().all(): Session().delete(x) Session().commit()
def tearDown(self): for x in ChangesetComment.query().all(): self.Session.delete(x) self.Session.commit() for x in Notification.query().all(): self.Session.delete(x) self.Session.commit()
def test_delete_association(self): self.assertEqual([], Notification.query().all()) self.assertEqual([], UserNotification.query().all()) notification = NotificationModel().create(created_by=self.u1, subject=u'title', body=u'hi there3', recipients=[self.u3, self.u1, self.u2]) Session().commit() unotification = UserNotification.query()\ .filter(UserNotification.notification == notification)\ .filter(UserNotification.user_id == self.u3)\ .scalar() self.assertEqual(unotification.user_id, self.u3) NotificationModel().delete(self.u3, notification.notification_id) Session().commit() u3notification = UserNotification.query()\ .filter(UserNotification.notification == notification)\ .filter(UserNotification.user_id == self.u3)\ .scalar() self.assertEqual(u3notification, None) # notification object is still there self.assertEqual(Notification.query().all(), [notification]) #u1 and u2 still have assignments u1notification = UserNotification.query()\ .filter(UserNotification.notification == notification)\ .filter(UserNotification.user_id == self.u1)\ .scalar() self.assertNotEqual(u1notification, None) u2notification = UserNotification.query()\ .filter(UserNotification.notification == notification)\ .filter(UserNotification.user_id == self.u2)\ .scalar() self.assertNotEqual(u2notification, None)
def setUp(self): for x in ChangesetComment.query().all(): self.Session.delete(x) self.Session.commit() for x in Notification.query().all(): self.Session.delete(x) self.Session.commit()
def __get_notification(self, notification): if isinstance(notification, Notification): return notification elif isinstance(notification, (int, long)): return Notification.get(notification) else: if notification: raise Exception('notification must be int, long or Instance' ' of Notification got %s' % type(notification))
def test_delete_notifications(self): notification = NotificationModel().create( created_by=self.u1, notification_subject=u'title', notification_body=u'hi there3', recipients=[self.u3, self.u1, self.u2]) Session().commit() notifications = Notification.query().all() assert notification in notifications Notification.delete(notification.notification_id) Session().commit() notifications = Notification.query().all() assert notification not in notifications un = UserNotification.query().filter( UserNotification.notification == notification).all() assert un == []
def prepare(self, request, pylonsapp): for x in ChangesetComment.query().all(): Session().delete(x) Session().commit() for x in Notification.query().all(): Session().delete(x) Session().commit() request.addfinalizer(self.cleanup)
def test_create_inline(self): self.log_user() rev = '27cd5cce30c96924232dffcd24178a07ffeb5dfc' text = u'CommentOnRevision' f_path = 'vcs/web/simplevcs/views/repository.py' line = 'n1' params = {'text': text, 'f_path': f_path, 'line': line} response = self.app.post(url(controller='changeset', action='comment', repo_name=HG_REPO, revision=rev), params=params) # Test response... self.assertEqual(response.status, '302 Found') response.follow() response = self.app.get( url(controller='changeset', action='index', repo_name=HG_REPO, revision=rev)) #test DB self.assertEqual(ChangesetComment.query().count(), 1) response.mustcontain('''<div class="comments-number">0 comments''' ''' (%s inline)</div>''' % 1) response.mustcontain( '''<div style="display:none" class="inline-comment-placeholder" ''' '''path="vcs/web/simplevcs/views/repository.py" ''' '''target_id="vcswebsimplevcsviewsrepositorypy">''') self.assertEqual(Notification.query().count(), 1) self.assertEqual(ChangesetComment.query().count(), 1) notification = Notification.query().all()[0] ID = ChangesetComment.query().first().comment_id self.assertEqual(notification.type_, Notification.TYPE_CHANGESET_COMMENT) sbj = (u'/vcs_test_hg/changeset/' '27cd5cce30c96924232dffcd24178a07ffeb5dfc#comment-%s' % ID) print "%s vs %s" % (sbj, notification.subject) self.assertTrue(sbj in notification.subject)
def test_delete_notifications(self): self.assertEqual([], Notification.query().all()) self.assertEqual([], UserNotification.query().all()) notification = NotificationModel().create(created_by=self.u1, subject=u'title', body=u'hi there3', recipients=[self.u3, self.u1, self.u2]) Session().commit() notifications = Notification.query().all() self.assertTrue(notification in notifications) Notification.delete(notification.notification_id) Session().commit() notifications = Notification.query().all() self.assertFalse(notification in notifications) un = UserNotification.query().filter(UserNotification.notification == notification).all() self.assertEqual(un, [])
def test_reviewer_notifications(self, backend, csrf_token): # We have to use the app.post for this test so it will create the # notifications properly with the new PR commits = [ {'message': 'ancestor', 'added': [FileNode('file_A', content='content_of_ancestor')]}, {'message': 'change', 'added': [FileNode('file_a', content='content_of_change')]}, {'message': 'change-child'}, {'message': 'ancestor-child', 'parents': ['ancestor'], 'added': [ FileNode('file_B', content='content_of_ancestor_child')]}, {'message': 'ancestor-child-2'}, ] commit_ids = backend.create_master_repo(commits) target = backend.create_repo(heads=['ancestor-child']) source = backend.create_repo(heads=['change']) response = self.app.post( url( controller='pullrequests', action='create', repo_name=source.repo_name), params={ 'source_repo': source.repo_name, 'source_ref': 'branch:default:' + commit_ids['change'], 'target_repo': target.repo_name, 'target_ref': 'branch:default:' + commit_ids['ancestor-child'], 'pullrequest_desc': 'Description', 'pullrequest_title': 'Title', 'review_members': '2', 'revisions': commit_ids['change'], 'user': '', 'csrf_token': csrf_token, }, status=302) location = response.headers['Location'] pull_request_id = int(location.rsplit('/', 1)[1]) pull_request = PullRequest.get(pull_request_id) # Check that a notification was made notifications = Notification.query()\ .filter(Notification.created_by == pull_request.author.user_id, Notification.type_ == Notification.TYPE_PULL_REQUEST, Notification.subject.contains("wants you to review " "pull request #%d" % pull_request_id)) assert len(notifications.all()) == 1 # Change reviewers and check that a notification was made PullRequestModel().update_reviewers(pull_request.pull_request_id, [1]) assert len(notifications.all()) == 2
def test_create_inline(self): self.log_user() rev = '27cd5cce30c96924232dffcd24178a07ffeb5dfc' text = u'CommentOnRevision' f_path = 'vcs/web/simplevcs/views/repository.py' line = 'n1' params = {'text': text, 'f_path': f_path, 'line': line} response = self.app.post(url(controller='changeset', action='comment', repo_name=HG_REPO, revision=rev), params=params) # Test response... self.assertEqual(response.status, '302 Found') response.follow() response = self.app.get(url(controller='changeset', action='index', repo_name=HG_REPO, revision=rev)) #test DB self.assertEqual(ChangesetComment.query().count(), 1) response.mustcontain( '''<div class="comments-number">0 comments''' ''' (%s inline)</div>''' % 1 ) response.mustcontain( '''<div style="display:none" class="inline-comment-placeholder" ''' '''path="vcs/web/simplevcs/views/repository.py" ''' '''target_id="vcswebsimplevcsviewsrepositorypy">''' ) self.assertEqual(Notification.query().count(), 1) self.assertEqual(ChangesetComment.query().count(), 1) notification = Notification.query().all()[0] ID = ChangesetComment.query().first().comment_id self.assertEqual(notification.type_, Notification.TYPE_CHANGESET_COMMENT) sbj = (u'/vcs_test_hg/changeset/' '27cd5cce30c96924232dffcd24178a07ffeb5dfc#comment-%s' % ID) print "%s vs %s" % (sbj, notification.subject) self.assertTrue(sbj in notification.subject)
def test_delete_notifications(self): self.assertEqual([], Notification.query().all()) self.assertEqual([], UserNotification.query().all()) notification = NotificationModel().create( created_by=self.u1, subject=u'title', body=u'hi there3', recipients=[self.u3, self.u1, self.u2]) Session.commit() notifications = Notification.query().all() self.assertTrue(notification in notifications) Notification.delete(notification.notification_id) Session.commit() notifications = Notification.query().all() self.assertFalse(notification in notifications) un = UserNotification.query().filter( UserNotification.notification == notification).all() self.assertEqual(un, [])
def test_create(self, backend): self.log_user() commit_id = backend.repo.get_commit('300').raw_id text = u'CommentOnCommit' params = {'text': text, 'csrf_token': self.csrf_token} self.app.post(url(controller='changeset', action='comment', repo_name=backend.repo_name, revision=commit_id), params=params) response = self.app.get( url(controller='changeset', action='index', repo_name=backend.repo_name, revision=commit_id)) # test DB assert ChangesetComment.query().count() == 1 assert_comment_links(response, ChangesetComment.query().count(), 0) assert Notification.query().count() == 1 assert ChangesetComment.query().count() == 1 notification = Notification.query().all()[0] comment_id = ChangesetComment.query().first().comment_id assert notification.type_ == Notification.TYPE_CHANGESET_COMMENT sbj = 'commented on commit of {0}'.format(backend.repo_name) assert sbj in notification.subject lnk = (u'/{0}/changeset/{1}#comment-{2}'.format( backend.repo_name, commit_id, comment_id)) assert lnk in notification.body
def test_user_notifications(self): self.assertEqual([], Notification.query().all()) self.assertEqual([], UserNotification.query().all()) notification1 = NotificationModel().create(created_by=self.u1, subject=u'subj', body=u'hi there1', recipients=[self.u3]) Session().commit() notification2 = NotificationModel().create(created_by=self.u1, subject=u'subj', body=u'hi there2', recipients=[self.u3]) Session().commit() u3 = Session().query(User).get(self.u3) self.assertEqual(sorted([x.notification for x in u3.notifications]), sorted([notification2, notification1]))
def test_user_notifications(self): self.assertEqual([], Notification.query().all()) self.assertEqual([], UserNotification.query().all()) notification1 = NotificationModel().create(created_by=self.u1, subject=u'subj', body=u'hi there1', recipients=[self.u3]) Session.commit() notification2 = NotificationModel().create(created_by=self.u1, subject=u'subj', body=u'hi there2', recipients=[self.u3]) Session.commit() u3 = Session.query(User).get(self.u3) self.assertEqual(sorted([x.notification for x in u3.notifications]), sorted([notification2, notification1]))
def delete(self, notification_id): """DELETE /_admin/notifications/id: Delete an existing item""" # Forms posted to this method should contain a hidden field: # <input type="hidden" name="_method" value="DELETE" /> # Or using helpers: # h.form(url('notification', notification_id=ID), # method='delete') # url('notification', notification_id=ID) try: no = Notification.get(notification_id) if self._has_permissions(no): # deletes only notification2user NotificationModel().delete(c.rhodecode_user.user_id, no) Session().commit() return 'ok' except Exception: Session().rollback() log.exception("Exception deleting a notification item") raise HTTPBadRequest()
def update(self, notification_id): """PUT /_admin/notifications/id: Update an existing item""" # Forms posted to this method should contain a hidden field: # <input type="hidden" name="_method" value="PUT" /> # Or using helpers: # h.form(url('notification', notification_id=ID), # method='put') # url('notification', notification_id=ID) try: no = Notification.get(notification_id) owner = all(un.user.user_id == c.rhodecode_user.user_id for un in no.notifications_to_users) if h.HasPermissionAny('hg.admin')() or owner: NotificationModel().mark_read(c.rhodecode_user.user_id, no) Session().commit() return 'ok' except Exception: Session().rollback() log.error(traceback.format_exc()) return 'fail'
def delete(self, notification_id): """DELETE /_admin/notifications/id: Delete an existing item""" # Forms posted to this method should contain a hidden field: # <input type="hidden" name="_method" value="DELETE" /> # Or using helpers: # h.form(url('notification', notification_id=ID), # method='delete') # url('notification', notification_id=ID) try: no = Notification.get(notification_id) owner = lambda: (no.notifications_to_users.user.user_id == c.rhodecode_user.user_id) if h.HasPermissionAny("hg.admin", "repository.admin")() or owner: NotificationModel().delete(c.rhodecode_user.user_id, no) Session.commit() return "ok" except Exception: Session.rollback() log.error(traceback.format_exc()) return "fail"
def show(self, notification_id, format="html"): """GET /_admin/notifications/id: Show a specific item""" # url('notification', notification_id=ID) c.user = self.rhodecode_user no = Notification.get(notification_id) owner = lambda: (no.notifications_to_users.user.user_id == c.user.user_id) if no and (h.HasPermissionAny("hg.admin", "repository.admin")() or owner): unotification = NotificationModel().get_user_notification(c.user.user_id, no) # if this association to user is not valid, we don't want to show # this message if unotification: if unotification.read is False: unotification.mark_as_read() Session.commit() c.notification = no return render("admin/notifications/show_notification.html") return redirect(url("notifications"))
def test_create_notification(self): usrs = [self.u1, self.u2] notification = NotificationModel().create( created_by=self.u1, notification_subject=u'subj', notification_body=u'hi there', recipients=usrs) Session().commit() u1 = User.get(self.u1) u2 = User.get(self.u2) notifications = Notification.query().all() assert len(notifications) == 1 assert notifications[0].recipients, [u1 == u2] assert notification.notification_id == notifications[0].notification_id unotification = UserNotification.query()\ .filter(UserNotification.notification == notification).all() assert len(unotification) == len(usrs) assert set([x.user.user_id for x in unotification]) == set(usrs)
def show(self, notification_id): """GET /_admin/notifications/id: Show a specific item""" # url('notification', notification_id=ID) c.user = c.rhodecode_user no = Notification.get(notification_id) if no and self._has_permissions(no): unotification = NotificationModel()\ .get_user_notification(c.user.user_id, no) # if this association to user is not valid, we don't want to show # this message if unotification: if not unotification.read: unotification.mark_as_read() Session().commit() c.notification = no return render('admin/notifications/show_notification.html') return abort(403)
def delete(self, notification_id): """DELETE /_admin/notifications/id: Delete an existing item""" # Forms posted to this method should contain a hidden field: # <input type="hidden" name="_method" value="DELETE" /> # Or using helpers: # h.form(url('notification', notification_id=ID), # method='delete') # url('notification', notification_id=ID) try: no = Notification.get(notification_id) owner = lambda: (no.notifications_to_users.user.user_id == c. rhodecode_user.user_id) if h.HasPermissionAny('hg.admin', 'repository.admin')() or owner: NotificationModel().delete(c.rhodecode_user.user_id, no) Session.commit() return 'ok' except Exception: Session.rollback() log.error(traceback.format_exc()) return 'fail'
def show(self, notification_id, format='html'): """GET /_admin/notifications/id: Show a specific item""" # url('notification', notification_id=ID) c.user = self.rhodecode_user no = Notification.get(notification_id) owner = lambda: (no.notifications_to_users.user.user_id == c.user. user_id) if no and (h.HasPermissionAny('hg.admin', 'repository.admin')() or owner): unotification = NotificationModel()\ .get_user_notification(c.user.user_id, no) # if this association to user is not valid, we don't want to show # this message if unotification: if unotification.read is False: unotification.mark_as_read() Session.commit() c.notification = no return render('admin/notifications/show_notification.html') return redirect(url('notifications'))
def show(self, notification_id, format='html'): """GET /_admin/notifications/id: Show a specific item""" # url('notification', notification_id=ID) c.user = self.rhodecode_user no = Notification.get(notification_id) owner = any(un.user.user_id == c.rhodecode_user.user_id for un in no.notifications_to_users) if no and (h.HasPermissionAny('hg.admin', 'repository.admin')() or owner): unotification = NotificationModel()\ .get_user_notification(c.user.user_id, no) # if this association to user is not valid, we don't want to show # this message if unotification: if not unotification.read: unotification.mark_as_read() Session().commit() c.notification = no return render('admin/notifications/show_notification.html') return abort(403)
def test_create_with_mention(self): self.log_user() rev = "27cd5cce30c96924232dffcd24178a07ffeb5dfc" text = u"@test_regular check CommentOnRevision" params = {"text": text} response = self.app.post( url(controller="changeset", action="comment", repo_name=HG_REPO, revision=rev), params=params ) # Test response... self.assertEqual(response.status, "302 Found") response.follow() response = self.app.get(url(controller="changeset", action="index", repo_name=HG_REPO, revision=rev)) # test DB self.assertEqual(ChangesetComment.query().count(), 1) self.assertTrue("""<div class="comments-number">%s """ """comment(s) (0 inline)</div>""" % 1 in response.body) self.assertEqual(Notification.query().count(), 2) users = [x.user.username for x in UserNotification.query().all()] # test_regular get's notification by @mention self.assertEqual(sorted(users), [u"test_admin", u"test_regular"])
def create(self, created_by, subject, body, recipients=None, type_=Notification.TYPE_MESSAGE, with_email=True, email_kwargs={}, email_subject=None): """ Creates notification of given type :param created_by: int, str or User instance. User who created this notification :param subject: :param body: :param recipients: list of int, str or User objects, when None is given send to all admins :param type_: type of notification :param with_email: send email with this notification :param email_kwargs: additional dict to pass as args to email template :param email_subject: use given subject as email subject """ from rhodecode.lib.celerylib import tasks, run_task if recipients and not getattr(recipients, '__iter__', False): raise Exception('recipients must be a list or iterable') created_by_obj = self._get_user(created_by) if recipients: recipients_objs = [] for u in recipients: obj = self._get_user(u) if obj: recipients_objs.append(obj) else: # TODO: inform user that requested operation couldn't be completed log.error('cannot email unknown user %r', u) recipients_objs = set(recipients_objs) log.debug('sending notifications %s to %s' % ( type_, recipients_objs) ) else: # empty recipients means to all admins recipients_objs = User.query().filter(User.admin == True).all() log.debug('sending notifications %s to admins: %s' % ( type_, recipients_objs) ) # TODO: inform user who are notified notif = Notification.create( created_by=created_by_obj, subject=subject, body=body, recipients=recipients_objs, type_=type_ ) if not with_email: return notif #don't send email to person who created this comment rec_objs = set(recipients_objs).difference(set([created_by_obj])) # send email with notification to all other participants for rec in rec_objs: if not email_subject: email_subject = NotificationModel()\ .make_description(notif, show_age=False) type_ = type_ email_body = None # we set body to none, we just send HTML emails ## this is passed into template kwargs = {'subject': subject, 'body': h.rst_w_mentions(body)} kwargs.update(email_kwargs) email_body_html = EmailNotificationModel()\ .get_email_tmpl(type_, **kwargs) run_task(tasks.send_email, rec.email, email_subject, email_body, email_body_html) return notif
def tearDown(self): for n in Notification.query().all(): self.Session().delete(n) self.Session().commit() self.assertEqual(Notification.query().all(), [])
def create(self, created_by, subject, body, recipients=None, type_=Notification.TYPE_MESSAGE, with_email=True, email_kwargs={}): """ Creates notification of given type :param created_by: int, str or User instance. User who created this notification :param subject: :param body: :param recipients: list of int, str or User objects, when None is given send to all admins :param type_: type of notification :param with_email: send email with this notification :param email_kwargs: additional dict to pass as args to email template """ from rhodecode.lib.celerylib import tasks, run_task if recipients and not getattr(recipients, '__iter__', False): raise Exception('recipients must be a list of iterable') created_by_obj = self.__get_user(created_by) if recipients: recipients_objs = [] for u in recipients: obj = self.__get_user(u) if obj: recipients_objs.append(obj) recipients_objs = set(recipients_objs) log.debug('sending notifications %s to %s' % ( type_, recipients_objs) ) else: # empty recipients means to all admins recipients_objs = User.query().filter(User.admin == True).all() log.debug('sending notifications %s to admins: %s' % ( type_, recipients_objs) ) notif = Notification.create( created_by=created_by_obj, subject=subject, body=body, recipients=recipients_objs, type_=type_ ) if with_email is False: return notif # send email with notification for rec in recipients_objs: email_subject = NotificationModel().make_description(notif, False) type_ = type_ email_body = body kwargs = {'subject': subject, 'body': h.rst_w_mentions(body)} kwargs.update(email_kwargs) email_body_html = EmailNotificationModel()\ .get_email_tmpl(type_, **kwargs) run_task(tasks.send_email, rec.email, email_subject, email_body, email_body_html) return notif
def _clean_notifications(self): for n in Notification.query().all(): Session().delete(n) Session().commit() self.assertEqual(Notification.query().all(), [])
def tearDown(self): for n in Notification.query().all(): inst = Notification.get(n.notification_id) self.Session().delete(inst) self.Session().commit()
def tearDown(self): for n in Notification.query().all(): inst = Notification.get(n.notification_id) Session().delete(inst) Session().commit()
def create(self, created_by, notification_subject, notification_body, notification_type=Notification.TYPE_MESSAGE, recipients=None, mention_recipients=None, with_email=True, email_kwargs=None): """ Creates notification of given type :param created_by: int, str or User instance. User who created this notification :param notification_subject: subject of notification itself :param notification_body: body of notification text :param notification_type: type of notification, based on that we pick templates :param recipients: list of int, str or User objects, when None is given send to all admins :param mention_recipients: list of int, str or User objects, that were mentioned :param with_email: send email with this notification :param email_kwargs: dict with arguments to generate email """ from rhodecode.lib.celerylib import tasks, run_task if recipients and not getattr(recipients, '__iter__', False): raise Exception('recipients must be an iterable object') created_by_obj = self._get_user(created_by) # default MAIN body if not given email_kwargs = email_kwargs or {'body': notification_body} mention_recipients = mention_recipients or set() if not created_by_obj: raise Exception('unknown user %s' % created_by) if recipients is None: # recipients is None means to all admins recipients_objs = User.query().filter(User.admin == true()).all() log.debug('sending notifications %s to admins: %s', notification_type, recipients_objs) else: recipients_objs = [] for u in recipients: obj = self._get_user(u) if obj: recipients_objs.append(obj) else: # we didn't find this user, log the error and carry on log.error('cannot notify unknown user %r', u) recipients_objs = set(recipients_objs) if not recipients_objs: raise Exception('no valid recipients specified') log.debug('sending notifications %s to %s', notification_type, recipients_objs) # add mentioned users into recipients final_recipients = set(recipients_objs).union(mention_recipients) notification = Notification.create(created_by=created_by_obj, subject=notification_subject, body=notification_body, recipients=final_recipients, type_=notification_type) if not with_email: # skip sending email, and just create notification return notification # don't send email to person who created this comment rec_objs = set(recipients_objs).difference(set([created_by_obj])) # now notify all recipients in question for recipient in rec_objs.union(mention_recipients): # inject current recipient email_kwargs['recipient'] = recipient email_kwargs['mention'] = recipient in mention_recipients (subject, headers, email_body, email_body_plaintext) = EmailNotificationModel().render_email( notification_type, **email_kwargs) log.debug('Creating notification email task for user:`%s`', recipient) task = run_task(tasks.send_email, recipient.email, subject, email_body_plaintext, email_body) log.debug('Created email task: %s', task) return notification
def teardown_method(self, method): for n in Notification.query().all(): inst = Notification.get(n.notification_id) Session().delete(inst) Session().commit()
def _clean_notifications(self): for n in Notification.query().all(): Session.delete(n) Session.commit() self.assertEqual(Notification.query().all(), [])