Changeset - 54687aa00724
rhodecode/controllers/admin/notifications.py
Show inline comments
 
import logging
 
import traceback
 

	
 
from pylons import tmpl_context as c
 
from pylons import tmpl_context as c, url
 

	
 
from rhodecode.lib.base import BaseController, render
 
from rhodecode.model.db import Notification
 

	
 
from rhodecode.model.notification import NotificationModel
 
from rhodecode.lib.auth import LoginRequired
 
from rhodecode.lib import helpers as h
 
from rhodecode.model.meta import Session
 
from pylons.controllers.util import redirect
 

	
 
log = logging.getLogger(__name__)
 

	
 
class NotificationsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
@@ -54,31 +57,46 @@ class NotificationsController(BaseContro
 
        #    <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
 
            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(notification_id)
 
                    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
 
        c.notification = Notification.get(notification_id)
 
        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,
 
                                                   c.notification)
 
                            .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 edit(self, notification_id, format='html'):
 
        """GET /_admin/notifications/id/edit: Form to edit an existing item"""
 
        # url('edit_notification', notification_id=ID)
rhodecode/controllers/changeset.py
Show inline comments
 
@@ -41,12 +41,13 @@ from rhodecode.model.comment import Chan
 

	
 
from vcs.exceptions import RepositoryError, ChangesetError, \
 
    ChangesetDoesNotExistError
 
from vcs.nodes import FileNode
 
from vcs.utils import diffs as differ
 
from webob.exc import HTTPForbidden
 
from rhodecode.model.meta import Session
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class ChangesetController(BaseRepoController):
 

	
 
@@ -276,21 +277,21 @@ class ChangesetController(BaseRepoContro
 
        ChangesetCommentsModel().create(text=request.POST.get('text'),
 
                                        repo_id=c.rhodecode_db_repo.repo_id,
 
                                        user_id=c.rhodecode_user.user_id,
 
                                        revision=revision,
 
                                        f_path=request.POST.get('f_path'),
 
                                        line_no=request.POST.get('line'))
 

	
 
        Session.commit()
 
        return redirect(h.url('changeset_home', repo_name=repo_name,
 
                              revision=revision))
 

	
 
    @jsonify
 
    def delete_comment(self, comment_id):
 
        co = ChangesetComment.get(comment_id)
 
        owner = lambda : co.author.user_id == c.rhodecode_user.user_id
 
        if h.HasPermissionAny('hg.admin', 'repository.admin')() or owner:
 
            ccmodel = ChangesetCommentsModel()
 
            ccmodel.delete(comment_id=comment_id)
 
            ChangesetCommentsModel().delete(comment=co)
 
            Session.commit()
 
            return True
 
        else:
 
            raise HTTPForbidden()
 

	
rhodecode/lib/__init__.py
Show inline comments
 
@@ -21,12 +21,13 @@
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import os
 
import re
 

	
 
def __get_lem():
 
    from pygments import lexers
 
    from string import lower
 
    from collections import defaultdict
 

	
 
@@ -433,6 +434,17 @@ def get_current_revision(quiet=False):
 
    except Exception, err:
 
        if not quiet:
 
            print ("Cannot retrieve rhodecode's revision. Original error "
 
                   "was: %s" % err)
 
        return None
 

	
 
def extract_mentioned_users(s):
 
    """
 
    Returns unique usernames from given string s that have @mention
 
    
 
    :param s: string to get mentions
 
    """
 
    usrs = {}
 
    for username in re.findall(r'(?:^@|\s@)(\w+)', s):
 
        usrs[username] = username
 

	
 
    return sorted(usrs.keys())
rhodecode/lib/celerylib/tasks.py
Show inline comments
 
@@ -52,14 +52,12 @@ from rhodecode.model.db import RhodeCode
 
from vcs.backends import get_repo
 

	
 
from sqlalchemy import engine_from_config
 

	
 
add_cache(config)
 

	
 

	
 

	
 
__all__ = ['whoosh_index', 'get_commits_stats',
 
           'reset_user_password', 'send_email']
 

	
 
CELERY_ON = str2bool(config['app_conf'].get('use_celery'))
 

	
 

	
 
@@ -98,12 +96,13 @@ def get_commits_stats(repo_name, ts_min_
 
    lockkey = __get_lockkey('get_commits_stats', repo_name, ts_min_y,
 
                            ts_max_y)
 
    lockkey_path = config['here']
 

	
 
    log.info('running task with lockkey %s', lockkey)
 
    try:
 
        sa = get_session()
 
        lock = l = DaemonLock(file_=jn(lockkey_path, lockkey))
 

	
 
        #for js data compatibilty cleans the key for person from '
 
        akc = lambda k: person(k).replace('"', "")
 

	
 
        co_day_auth_aggr = {}
 
@@ -119,14 +118,12 @@ def get_commits_stats(repo_name, ts_min_
 
        skip_date_limit = True
 
        parse_limit = int(config['app_conf'].get('commit_parse_limit'))
 
        last_rev = 0
 
        last_cs = None
 
        timegetter = itemgetter('time')
 

	
 
        sa = get_session()
 

	
 
        dbrepo = sa.query(Repository)\
 
            .filter(Repository.repo_name == repo_name).scalar()
 
        cur_stats = sa.query(Statistics)\
 
            .filter(Statistics.repository == dbrepo).scalar()
 

	
 
        if cur_stats is not None:
rhodecode/model/__init__.py
Show inline comments
 
@@ -68,7 +68,25 @@ class BaseModel(object):
 
    """
 

	
 
    def __init__(self, sa=None):
 
        if sa is not None:
 
            self.sa = sa
 
        else:
 
            self.sa = meta.Session
 
            self.sa = meta.Session()
 

	
 
    def __get_instance(self, cls, instance):
 
        """
 
        Get's instance of given cls using some simple lookup mechanism
 
        
 
        :param cls: class to fetch
 
        :param instance: int or Instance
 
        """
 

	
 
        if isinstance(instance, cls):
 
            return instance
 
        elif isinstance(instance, int) or str(instance).isdigit():
 
            return cls.get(instance)
 
        else:
 
            if instance:
 
                raise Exception('given object must be int or Instance'
 
                                ' of %s got %s' % (type(cls),
 
                                                   type(instance)))
rhodecode/model/comment.py
Show inline comments
 
@@ -20,38 +20,39 @@
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import re
 
import logging
 
import traceback
 

	
 
from pylons.i18n.translation import _
 
from sqlalchemy.util.compat import defaultdict
 

	
 
from rhodecode.lib import extract_mentioned_users
 
from rhodecode.lib import helpers as h
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import ChangesetComment, User, Repository, Notification
 
from rhodecode.model.notification import NotificationModel
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class ChangesetCommentsModel(BaseModel):
 

	
 
    def __get_changeset_comment(self, changeset_comment):
 
        return self.__get_instance(ChangesetComment, changeset_comment)
 

	
 
    def _extract_mentions(self, s):
 
        usrs = []
 
        for username in re.findall(r'(?:^@|\s@)(\w+)', s):
 
        user_objects = []
 
        for username in extract_mentioned_users(s):
 
            user_obj = User.get_by_username(username, case_insensitive=True)
 
            if user_obj:
 
                usrs.append(user_obj)
 

	
 
        return usrs
 
                user_objects.append(user_obj)
 
        return user_objects
 

	
 
    def create(self, text, repo_id, user_id, revision, f_path=None,
 
               line_no=None):
 
        """
 
        Creates new comment for changeset
 
        
 
@@ -93,21 +94,21 @@ class ChangesetCommentsModel(BaseModel):
 
            NotificationModel().create(created_by=user_id, subject=subj,
 
                                   body = body, recipients = recipients,
 
                                   type_ = Notification.TYPE_CHANGESET_COMMENT)
 

	
 
            return comment
 

	
 
    def delete(self, comment_id):
 
    def delete(self, comment):
 
        """
 
        Deletes given comment
 
        
 
        :param comment_id:
 
        """
 
        comment = ChangesetComment.get(comment_id)
 
        comment = self.__get_changeset_comment(comment)
 
        self.sa.delete(comment)
 
        self.sa.commit()
 

	
 
        return comment
 

	
 

	
 
    def get_comments(self, repo_id, revision):
 
        return ChangesetComment.query()\
 
                .filter(ChangesetComment.repo_id == repo_id)\
rhodecode/model/db.py
Show inline comments
 
@@ -45,13 +45,12 @@ from rhodecode.lib import str2bool, safe
 
from rhodecode.lib.exceptions import UsersGroupsAssignedException
 
from rhodecode.lib.compat import json
 
from rhodecode.lib.caching_query import FromCache
 

	
 
from rhodecode.model.meta import Base, Session
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 
#==============================================================================
 
# BASE CLASSES
 
#==============================================================================
 

	
 
@@ -119,13 +118,13 @@ class BaseModel(object):
 
        for k in self._get_keys():
 
            if k in populate_dict:
 
                setattr(self, k, populate_dict[k])
 

	
 
    @classmethod
 
    def query(cls):
 
        return Session.query(cls)
 
        return Session().query(cls)
 

	
 
    @classmethod
 
    def get(cls, id_):
 
        if id_:
 
            return cls.query().get(id_)
 

	
 
@@ -133,14 +132,13 @@ class BaseModel(object):
 
    def getAll(cls):
 
        return cls.query().all()
 

	
 
    @classmethod
 
    def delete(cls, id_):
 
        obj = cls.query().get(id_)
 
        Session.delete(obj)
 
        Session.commit()
 
        Session().delete(obj)
 

	
 

	
 
class RhodeCodeSetting(Base, BaseModel):
 
    __tablename__ = 'rhodecode_settings'
 
    __table_args__ = (UniqueConstraint('app_settings_name'), {'extend_existing':True})
 
    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
@@ -254,14 +252,14 @@ class RhodeCodeUi(Base, BaseModel):
 
        new_ui = cls.get_by_key(key).scalar() or cls()
 
        new_ui.ui_section = 'hooks'
 
        new_ui.ui_active = True
 
        new_ui.ui_key = key
 
        new_ui.ui_value = val
 

	
 
        Session.add(new_ui)
 
        Session.commit()
 
        Session().add(new_ui)
 
        Session().commit()
 

	
 

	
 
class User(Base, BaseModel):
 
    __tablename__ = 'users'
 
    __table_args__ = (UniqueConstraint('username'), UniqueConstraint('email'), {'extend_existing':True})
 
    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
@@ -282,15 +280,13 @@ class User(Base, BaseModel):
 
    repositories = relationship('Repository')
 
    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
 
    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
 

	
 
    group_member = relationship('UsersGroupMember', cascade='all')
 

	
 
    notifications = relationship('Notification',
 
                            secondary='user_to_notification',
 
                            order_by=lambda :Notification.created_on.desc())
 
    notifications = relationship('UserNotification')
 

	
 
    @property
 
    def full_contact(self):
 
        return '%s %s <%s>' % (self.name, self.lastname, self.email)
 

	
 
    @property
 
@@ -328,14 +324,14 @@ class User(Base, BaseModel):
 
        return q.scalar()
 

	
 
    def update_lastlogin(self):
 
        """Update user lastlogin"""
 

	
 
        self.last_login = datetime.datetime.now()
 
        Session.add(self)
 
        Session.commit()
 
        Session().add(self)
 
        Session().commit()
 
        log.debug('updated user %s lastlogin', self.username)
 

	
 

	
 
class UserLog(Base, BaseModel):
 
    __tablename__ = 'user_logs'
 
    __table_args__ = {'extend_existing':True}
 
@@ -394,44 +390,44 @@ class UsersGroup(Base, BaseModel):
 
    def create(cls, form_data):
 
        try:
 
            new_users_group = cls()
 
            for k, v in form_data.items():
 
                setattr(new_users_group, k, v)
 

	
 
            Session.add(new_users_group)
 
            Session.commit()
 
            Session().add(new_users_group)
 
            Session().commit()
 
            return new_users_group
 
        except:
 
            log.error(traceback.format_exc())
 
            Session.rollback()
 
            Session().rollback()
 
            raise
 

	
 
    @classmethod
 
    def update(cls, users_group_id, form_data):
 

	
 
        try:
 
            users_group = cls.get(users_group_id, cache=False)
 

	
 
            for k, v in form_data.items():
 
                if k == 'users_group_members':
 
                    users_group.members = []
 
                    Session.flush()
 
                    Session().flush()
 
                    members_list = []
 
                    if v:
 
                        v = [v] if isinstance(v, basestring) else v
 
                        for u_id in set(v):
 
                            member = UsersGroupMember(users_group_id, u_id)
 
                            members_list.append(member)
 
                    setattr(users_group, 'members', members_list)
 
                setattr(users_group, k, v)
 

	
 
            Session.add(users_group)
 
            Session.commit()
 
            Session().add(users_group)
 
            Session().commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            Session.rollback()
 
            Session().rollback()
 
            raise
 

	
 
    @classmethod
 
    def delete(cls, users_group_id):
 
        try:
 

	
 
@@ -442,17 +438,17 @@ class UsersGroup(Base, BaseModel):
 

	
 
            if assigned_groups:
 
                raise UsersGroupsAssignedException('RepoGroup assigned to %s' %
 
                                                   assigned_groups)
 

	
 
            users_group = cls.get(users_group_id, cache=False)
 
            Session.delete(users_group)
 
            Session.commit()
 
            Session().delete(users_group)
 
            Session().commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            Session.rollback()
 
            Session().rollback()
 
            raise
 

	
 
class UsersGroupMember(Base, BaseModel):
 
    __tablename__ = 'users_groups_members'
 
    __table_args__ = {'extend_existing':True}
 

	
 
@@ -469,14 +465,14 @@ class UsersGroupMember(Base, BaseModel):
 

	
 
    @staticmethod
 
    def add_user_to_group(group, user):
 
        ugm = UsersGroupMember()
 
        ugm.users_group = group
 
        ugm.user = user
 
        Session.add(ugm)
 
        Session.commit()
 
        Session().add(ugm)
 
        Session().commit()
 
        return ugm
 

	
 
class Repository(Base, BaseModel):
 
    __tablename__ = 'repositories'
 
    __table_args__ = (UniqueConstraint('repo_name'), {'extend_existing':True},)
 

	
 
@@ -513,13 +509,13 @@ class Repository(Base, BaseModel):
 
    @classmethod
 
    def url_sep(cls):
 
        return '/'
 

	
 
    @classmethod
 
    def get_by_repo_name(cls, repo_name):
 
        q = Session.query(cls).filter(cls.repo_name == repo_name)
 
        q = Session().query(cls).filter(cls.repo_name == repo_name)
 
        q = q.options(joinedload(Repository.fork))\
 
                .options(joinedload(Repository.user))\
 
                .options(joinedload(Repository.group))
 
        return q.one()
 

	
 
    @classmethod
 
@@ -530,13 +526,13 @@ class Repository(Base, BaseModel):
 
    def base_path(cls):
 
        """
 
        Returns base path when all repos are stored
 

	
 
        :param cls:
 
        """
 
        q = Session.query(RhodeCodeUi).filter(RhodeCodeUi.ui_key ==
 
        q = Session().query(RhodeCodeUi).filter(RhodeCodeUi.ui_key ==
 
                                              cls.url_sep())
 
        q.options(FromCache("sql_cache_short", "repository_repo_path"))
 
        return q.one().ui_value
 

	
 
    @property
 
    def just_name(self):
 
@@ -566,13 +562,13 @@ class Repository(Base, BaseModel):
 
    @LazyProperty
 
    def repo_path(self):
 
        """
 
        Returns base full path for that repository means where it actually
 
        exists on a filesystem
 
        """
 
        q = Session.query(RhodeCodeUi).filter(RhodeCodeUi.ui_key ==
 
        q = Session().query(RhodeCodeUi).filter(RhodeCodeUi.ui_key ==
 
                                              Repository.url_sep())
 
        q.options(FromCache("sql_cache_short", "repository_repo_path"))
 
        return q.one().ui_value
 

	
 
    @property
 
    def repo_full_path(self):
 
@@ -883,29 +879,30 @@ class UserToPerm(Base, BaseModel):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        new = cls()
 
        new.user_id = user_id
 
        new.permission = perm
 
        try:
 
            Session.add(new)
 
            Session.commit()
 
            Session().add(new)
 
            Session().commit()
 
        except:
 
            Session.rollback()
 
            Session().rollback()
 

	
 

	
 
    @classmethod
 
    def revoke_perm(cls, user_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        try:
 
            cls.query().filter(cls.user_id == user_id)\
 
                .filter(cls.permission == perm).delete()
 
            Session.commit()
 
            obj = cls.query().filter(cls.user_id == user_id)\
 
                    .filter(cls.permission == perm).one()
 
            Session().delete(obj)
 
            Session().commit()
 
        except:
 
            Session.rollback()
 
            Session().rollback()
 

	
 
class UsersGroupRepoToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_to_perm'
 
    __table_args__ = (UniqueConstraint('repository_id', 'users_group_id', 'permission_id'), {'extend_existing':True})
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
@@ -945,29 +942,30 @@ class UsersGroupToPerm(Base, BaseModel):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        new = cls()
 
        new.users_group_id = users_group_id
 
        new.permission = perm
 
        try:
 
            Session.add(new)
 
            Session.commit()
 
            Session().add(new)
 
            Session().commit()
 
        except:
 
            Session.rollback()
 
            Session().rollback()
 

	
 

	
 
    @classmethod
 
    def revoke_perm(cls, users_group_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        try:
 
            cls.query().filter(cls.users_group_id == users_group_id)\
 
                .filter(cls.permission == perm).delete()
 
            Session.commit()
 
            obj = cls.query().filter(cls.users_group_id == users_group_id)\
 
                .filter(cls.permission == perm).one()
 
            Session().delete(obj)
 
            Session().commit()
 
        except:
 
            Session.rollback()
 
            Session().rollback()
 

	
 

	
 
class UserRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'group_to_perm'
 
    __table_args__ = (UniqueConstraint('group_id', 'permission_id'), {'extend_existing':True})
 

	
 
@@ -1074,30 +1072,30 @@ class CacheInvalidation(Base, BaseModel)
 
            inv_obj.cache_active = False
 
        else:
 
            log.debug('cache key not found in invalidation db -> creating one')
 
            inv_obj = CacheInvalidation(key)
 

	
 
        try:
 
            Session.add(inv_obj)
 
            Session.commit()
 
            Session().add(inv_obj)
 
            Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            Session.rollback()
 
            Session().rollback()
 

	
 
    @classmethod
 
    def set_valid(cls, key):
 
        """
 
        Mark this cache key as active and currently cached
 
        
 
        :param key:
 
        """
 
        inv_obj = Session().query(CacheInvalidation)\
 
        inv_obj = CacheInvalidation.query()\
 
            .filter(CacheInvalidation.cache_key == key).scalar()
 
        inv_obj.cache_active = True
 
        Session.add(inv_obj)
 
        Session.commit()
 
        Session().add(inv_obj)
 
        Session().commit()
 

	
 

	
 
class ChangesetComment(Base, BaseModel):
 
    __tablename__ = 'changeset_comments'
 
    __table_args__ = ({'extend_existing':True},)
 
    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
 
@@ -1119,13 +1117,13 @@ class ChangesetComment(Base, BaseModel):
 
        Returns user associated with this changesetComment. ie those
 
        who actually commented
 
        
 
        :param cls:
 
        :param revision:
 
        """
 
        return Session.query(User)\
 
        return Session().query(User)\
 
                .filter(cls.revision == revision)\
 
                .join(ChangesetComment.author).all()
 

	
 

	
 
class Notification(Base, BaseModel):
 
    __tablename__ = 'notifications'
 
@@ -1160,39 +1158,40 @@ class Notification(Base, BaseModel):
 

	
 
        notification = cls()
 
        notification.created_by_user = created_by
 
        notification.subject = subject
 
        notification.body = body
 
        notification.type_ = type_
 
        Session.add(notification)
 

	
 
        for u in recipients:
 
            u.notifications.append(notification)
 
            assoc = UserNotification()
 
            assoc.notification = notification
 
            u.notifications.append(assoc)
 
        Session().add(notification)
 
        return notification
 

	
 
    @property
 
    def description(self):
 
        from rhodecode.model.notification import NotificationModel
 
        return NotificationModel().make_description(self)
 

	
 
class UserNotification(Base, BaseModel):
 
    __tablename__ = 'user_to_notification'
 
    __table_args__ = (UniqueConstraint('user_id', 'notification_id'),
 
                      {'extend_existing':True})
 
    user_to_notification_id = Column("user_to_notification_id", Integer(), nullable=False, unique=True, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), nullable=False)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), primary_key=True)
 
    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
 
    read = Column('read', Boolean, default=False)
 
    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
 

	
 
    user = relationship('User', single_parent=True, lazy="joined")
 
    notification = relationship('Notification', single_parent=True,)
 
    user = relationship('User', lazy="joined")
 
    notification = relationship('Notification', lazy="joined", cascade='all')
 

	
 
    def mark_as_read(self):
 
        self.read = True
 
        Session.add(self)
 
        Session.commit()
 
        Session().add(self)
 

	
 
class DbMigrateVersion(Base, BaseModel):
 
    __tablename__ = 'db_migrate_version'
 
    __table_args__ = {'extend_existing':True}
 
    repository_id = Column('repository_id', String(250), primary_key=True)
 
    repository_path = Column('repository_path', Text)
rhodecode/model/notification.py
Show inline comments
 
@@ -85,36 +85,41 @@ class NotificationModel(BaseModel):
 
            recipients_objs.append(self.__get_user(u))
 
        recipients_objs = set(recipients_objs)
 
        return Notification.create(created_by=created_by_obj, subject=subject,
 
                            body=body, recipients=recipients_objs,
 
                            type_=type_)
 

	
 
    def delete(self, notification_id):
 
        # we don't want to remove actuall notification just the assignment
 
    def delete(self, user, notification):
 
        # we don't want to remove actual notification just the assignment
 
        try:
 
            notification_id = int(notification_id)
 
            no = self.__get_notification(notification_id)
 
            if no:
 
                UserNotification.delete(no.notifications_to_users.user_to_notification_id)
 
            notification = self.__get_notification(notification)
 
            user = self.__get_user(user)
 
            if notification and user:
 
                obj = UserNotification.query().filter(UserNotification.user == user)\
 
                    .filter(UserNotification.notification == notification).one()
 
                self.sa.delete(obj)
 
                return True
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def get_for_user(self, user_id):
 
        return User.get(user_id).notifications
 
    def get_for_user(self, user):
 
        user = self.__get_user(user)
 
        return user.notifications
 

	
 
    def get_unread_cnt_for_user(self, user_id):
 
    def get_unread_cnt_for_user(self, user):
 
        user = self.__get_user(user)
 
        return UserNotification.query()\
 
                .filter(UserNotification.read == False)\
 
                .filter(UserNotification.user_id == user_id).count()
 
                .filter(UserNotification.user == user).count()
 

	
 
    def get_unread_for_user(self, user_id):
 
    def get_unread_for_user(self, user):
 
        user = self.__get_user(user)
 
        return [x.notification for x in UserNotification.query()\
 
                .filter(UserNotification.read == False)\
 
                .filter(UserNotification.user_id == user_id).all()]
 
                .filter(UserNotification.user == user).all()]
 

	
 
    def get_user_notification(self, user, notification):
 
        user = self.__get_user(user)
 
        notification = self.__get_notification(notification)
 

	
 
        return UserNotification.query()\
rhodecode/model/repo.py
Show inline comments
 
@@ -297,40 +297,43 @@ class RepoModel(BaseModel):
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def delete_perm_user(self, form_data, repo_name):
 
        try:
 
            self.sa.query(UserRepoToPerm)\
 
            obj = self.sa.query(UserRepoToPerm)\
 
                .filter(UserRepoToPerm.repository \
 
                        == self.get_by_repo_name(repo_name))\
 
                .filter(UserRepoToPerm.user_id == form_data['user_id']).delete()
 
                .filter(UserRepoToPerm.user_id == form_data['user_id']).one()
 
            self.sa.delete(obj)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def delete_perm_users_group(self, form_data, repo_name):
 
        try:
 
            self.sa.query(UsersGroupRepoToPerm)\
 
            obj = self.sa.query(UsersGroupRepoToPerm)\
 
                .filter(UsersGroupRepoToPerm.repository \
 
                        == self.get_by_repo_name(repo_name))\
 
                .filter(UsersGroupRepoToPerm.users_group_id \
 
                        == form_data['users_group_id']).delete()
 
 == form_data['users_group_id']).one()
 
            self.sa.delete(obj)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def delete_stats(self, repo_name):
 
        try:
 
            self.sa.query(Statistics)\
 
            obj = self.sa.query(Statistics)\
 
                .filter(Statistics.repository == \
 
                        self.get_by_repo_name(repo_name)).delete()
 
                        self.get_by_repo_name(repo_name)).one()
 
            self.sa.delete(obj)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
rhodecode/model/user.py
Show inline comments
 
@@ -350,13 +350,13 @@ class UserModel(BaseModel):
 
        user.permissions['repositories'] = {}
 
        user.permissions['global'] = set()
 

	
 
        #======================================================================
 
        # fetch default permissions
 
        #======================================================================
 
        default_user = self.get_by_username('default')
 
        default_user = User.get_by_username('default')
 

	
 
        default_perms = self.sa.query(UserRepoToPerm, Repository, Permission)\
 
            .join((Repository, UserRepoToPerm.repository_id ==
 
                   Repository.repo_id))\
 
            .join((Permission, UserRepoToPerm.permission_id ==
 
                   Permission.permission_id))\
rhodecode/model/users_group.py
Show inline comments
 
@@ -32,29 +32,20 @@ from rhodecode.model import BaseModel
 
from rhodecode.model.db import UsersGroupMember, UsersGroup
 

	
 
log = logging.getLogger(__name__)
 

	
 
class UsersGroupModel(BaseModel):
 

	
 
    def __get_users_group(self, users_group):
 
        return self.__get_instance(UsersGroup, users_group)
 

	
 
    def get(self, users_group_id, cache = False):
 
        users_group = UsersGroup.query()
 
        if cache:
 
            users_group = users_group.options(FromCache("sql_cache_short",
 
                                          "get_users_group_%s" % users_group_id))
 
        return users_group.get(users_group_id)
 
        return UsersGroup.get(users_group_id)
 

	
 
    def get_by_name(self, name, cache = False, case_insensitive = False):
 
        users_group = UsersGroup.query()
 
        if case_insensitive:
 
            users_group = users_group.filter(UsersGroup.users_group_name.ilike(name))
 
        else:
 
            users_group = users_group.filter(UsersGroup.users_group_name == name)
 
        if cache:
 
            users_group = users_group.options(FromCache("sql_cache_short",
 
                                          "get_users_group_%s" % name))
 
        return users_group.scalar()
 
        return UsersGroup.get_by_group_name(name, cache, case_insensitive)
 

	
 
    def create(self, form_data):
 
        try:
 
            new_users_group = UsersGroup()
 
            for k, v in form_data.items():
 
                setattr(new_users_group, k, v)
 
@@ -64,12 +55,24 @@ class UsersGroupModel(BaseModel):
 
            return new_users_group
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 

	
 
    def create_(self, name, active=True):
 
        new = UsersGroup()
 
        new.users_group_name = name
 
        new.users_group_active = active
 
        self.sa.add(new)
 
        return new
 

	
 
    def delete(self, users_group):
 
        obj = self.__get_users_group(users_group)
 
        self.sa.delete(obj)
 

	
 
    def add_user_to_group(self, users_group, user):
 
        for m in users_group.members:
 
            u = m.user
 
            if u.user_id == user.user_id:
 
                return m
 

	
rhodecode/templates/admin/notifications/notifications.html
Show inline comments
 
@@ -27,25 +27,25 @@
 
    % if c.notifications:
 
    <%
 
    unread = lambda n:{False:'unread'}.get(n)
 
    %>
 
    <div class="table">
 
      %for notification in c.notifications:
 
        <div id="notification_${notification.notification_id}">
 
        <div id="notification_${notification.notification.notification_id}">
 
          <div class="notification-header">
 
            <div class="gravatar">
 
                <img alt="gravatar" src="${h.gravatar_url(h.email(notification.created_by_user.email),24)}"/>
 
                <img alt="gravatar" src="${h.gravatar_url(h.email(notification.notification.created_by_user.email),24)}"/>
 
            </div>
 
            <div class="desc">
 
            <a href="${url('notification', notification_id=notification.notification_id)}">${notification.description}</a>
 
            <div class="desc ${unread(notification.read)}">
 
            <a href="${url('notification', notification_id=notification.notification.notification_id)}">${notification.notification.description}</a>
 
            </div>
 
            <div class="delete-notifications">
 
              <span id="${notification.notification_id}" class="delete-notification delete_icon action"></span>
 
              <span id="${notification.notification.notification_id}" class="delete-notification delete_icon action"></span>
 
            </div>
 
          </div>
 
          <div class="notification-subject">${h.urlify_text(notification.subject)}</div>
 
          <div class="notification-subject">${h.urlify_text(notification.notification.subject)}</div>
 
        </div>
 
      %endfor
 
    </div>
 
    %else:
 
        <div class="table">${_('No notifications here yet')}</div>
 
    %endif
rhodecode/tests/__init__.py
Show inline comments
 
@@ -61,13 +61,13 @@ class TestController(TestCase):
 
    def __init__(self, *args, **kwargs):
 
        wsgiapp = pylons.test.pylonsapp
 
        config = wsgiapp.config
 

	
 
        self.app = TestApp(wsgiapp)
 
        url._push_object(URLGenerator(config['routes.map'], environ))
 
        self.sa = meta.Session
 
        self.Session = meta.Session
 
        self.index_location = config['app_conf']['index_dir']
 
        TestCase.__init__(self, *args, **kwargs)
 

	
 
    def log_user(self, username=TEST_USER_ADMIN_LOGIN,
 
                 password=TEST_USER_ADMIN_PASS):
 
        self._logged_username = username
rhodecode/tests/functional/test_admin_ldap_settings.py
Show inline comments
 
@@ -39,12 +39,13 @@ class TestLdapSettingsController(TestCon
 
                    'ldap_attr_login':'test_attr_login',
 
                    'ldap_attr_firstname':'ima',
 
                    'ldap_attr_lastname':'tester',
 
                    'ldap_attr_email':'test@example.com' })
 

	
 
        new_settings = RhodeCodeSetting.get_ldap_settings()
 
        print new_settings
 
        self.assertEqual(new_settings['ldap_host'], u'dc.example.com',
 
                         'fail db write compare')
 

	
 
        self.checkSessionFlash(response,
 
                               'Ldap settings updated successfully')
 

	
rhodecode/tests/functional/test_admin_notifications.py
Show inline comments
 
from rhodecode.tests import *
 
from rhodecode.model.db import Notification, User, UserNotification
 

	
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.notification import NotificationModel
 
from rhodecode.model.meta import Session
 

	
 
class TestNotificationsController(TestController):
 

	
 

	
 
    def tearDown(self):
 
        for n in Notification.query().all():
 
            inst = Notification.get(n.notification_id)
 
            Session().delete(inst)
 
        Session().commit()
 

	
 
    def test_index(self):
 
        self.log_user()
 

	
 

	
 
        u1 = UserModel().create_or_update(username='u1', password='qweqwe',
 
                                               email='u1@rhodecode.org',
 
                                               name='u1', lastname='u1').user_id
 
        u2 = UserModel().create_or_update(username='u2', password='qweqwe',
 
                                               email='u2@rhodecode.org',
 
                                               name='u2', lastname='u2').user_id
 

	
 
        response = self.app.get(url('notifications'))
 
        self.assertTrue('''<div class="table">No notifications here yet</div>'''
 
                        in response.body)
 

	
 
        cur_user = self._get_logged_user()
 

	
 
        NotificationModel().create(created_by=u1, subject=u'test',
 
        NotificationModel().create(created_by=u1, subject=u'test_notification_1',
 
                                   body=u'notification_1',
 
                                   recipients=[cur_user])
 
        Session().commit()
 
        response = self.app.get(url('notifications'))
 

	
 
        self.assertTrue(u'notification_1' in response.body)
 

	
 
        User.delete(u1)
 
        User.delete(u2)
 
        self.assertTrue(u'test_notification_1' in response.body)
 

	
 
#    def test_index_as_xml(self):
 
#        response = self.app.get(url('formatted_notifications', format='xml'))
 
#
 
#    def test_create(self):
 
#        response = self.app.post(url('notifications'))
 
@@ -59,33 +60,35 @@ class TestNotificationsController(TestCo
 
                                               email='u1@rhodecode.org',
 
                                               name='u1', lastname='u1')
 
        u2 = UserModel().create_or_update(username='u2', password='qweqwe',
 
                                               email='u2@rhodecode.org',
 
                                               name='u2', lastname='u2')
 

	
 
        # make two notifications 
 
        # make notifications
 
        notification = NotificationModel().create(created_by=cur_user,
 
                                                  subject=u'test',
 
                                                  body=u'hi there',
 
                                                  recipients=[cur_user, u1, u2])
 

	
 
        Session().commit()
 
        u1 = User.get(u1.user_id)
 
        u2 = User.get(u2.user_id)
 

	
 
        # check DB
 
        self.assertEqual(u1.notifications, [notification])
 
        self.assertEqual(u2.notifications, [notification])
 
        get_notif = lambda un:[x.notification for x in un]
 
        self.assertEqual(get_notif(cur_user.notifications), [notification])
 
        self.assertEqual(get_notif(u1.notifications), [notification])
 
        self.assertEqual(get_notif(u2.notifications), [notification])
 
        cur_usr_id = cur_user.user_id
 
        response = self.app.delete(url('notification',
 
                                       notification_id=cur_usr_id))
 

	
 

	
 
        cur_user = self._get_logged_user()
 
        self.assertEqual(cur_user.notifications, [])
 
        response = self.app.delete(url('notification',
 
                                       notification_id=
 
                                       notification.notification_id))
 

	
 
        User.delete(u1.user_id)
 
        User.delete(u2.user_id)
 
        cur_user = User.get(cur_usr_id)
 
        self.assertEqual(cur_user.notifications, [])
 

	
 

	
 
#    def test_delete_browser_fakeout(self):
 
#        response = self.app.post(url('notification', notification_id=1), params=dict(_method='delete'))
 

	
 
    def test_show(self):
 
@@ -97,13 +100,13 @@ class TestNotificationsController(TestCo
 
        u2 = UserModel().create_or_update(username='u2', password='qweqwe',
 
                                               email='u2@rhodecode.org',
 
                                               name='u2', lastname='u2')
 

	
 
        notification = NotificationModel().create(created_by=cur_user,
 
                                                  subject='test',
 
                                                  body='hi there',
 
                                                  body=u'hi there',
 
                                                  recipients=[cur_user, u1, u2])
 

	
 
        response = self.app.get(url('notification',
 
                                    notification_id=notification.notification_id))
 

	
 
#    def test_show_as_xml(self):
 
@@ -111,7 +114,6 @@ class TestNotificationsController(TestCo
 
#
 
#    def test_edit(self):
 
#        response = self.app.get(url('edit_notification', notification_id=1))
 
#
 
#    def test_edit_as_xml(self):
 
#        response = self.app.get(url('formatted_edit_notification', notification_id=1, format='xml'))
 

	
rhodecode/tests/functional/test_admin_repos.py
Show inline comments
 
@@ -33,13 +33,13 @@ class TestAdminReposController(TestContr
 
                                                'description':description,
 
                                                'private':private})
 

	
 
        self.checkSessionFlash(response, 'created repository %s' % (repo_name))
 

	
 
        #test if the repo was created in the database
 
        new_repo = self.sa.query(Repository).filter(Repository.repo_name ==
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name ==
 
                                                    repo_name).one()
 

	
 
        self.assertEqual(new_repo.repo_name, repo_name)
 
        self.assertEqual(new_repo.description, description)
 

	
 
        #test if repository is visible in the list ?
 
@@ -70,13 +70,13 @@ class TestAdminReposController(TestContr
 
                                                'description':description,
 
                                                'private':private})
 
        self.checkSessionFlash(response,
 
                               'created repository %s' % (repo_name_unicode))
 

	
 
        #test if the repo was created in the database
 
        new_repo = self.sa.query(Repository).filter(Repository.repo_name ==
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name ==
 
                                                repo_name_unicode).one()
 

	
 
        self.assertEqual(new_repo.repo_name, repo_name_unicode)
 
        self.assertEqual(new_repo.description, description_unicode)
 

	
 
        #test if repository is visible in the list ?
 
@@ -110,13 +110,13 @@ class TestAdminReposController(TestContr
 

	
 

	
 
        #test if we have a message for that repository
 
        assert '''created repository %s''' % (repo_name) in response.session['flash'][0], 'No flash message about new repo'
 

	
 
        #test if the fork was created in the database
 
        new_repo = self.sa.query(Repository).filter(Repository.repo_name == repo_name).one()
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name == repo_name).one()
 

	
 
        assert new_repo.repo_name == repo_name, 'wrong name of repo name in db'
 
        assert new_repo.description == description, 'wrong description'
 

	
 
        #test if repository is visible in the list ?
 
        response = response.follow()
 
@@ -159,13 +159,13 @@ class TestAdminReposController(TestContr
 

	
 
        #test if we have a message for that repository
 
        self.assertTrue('''created repository %s''' % (repo_name) in
 
                        response.session['flash'][0])
 

	
 
        #test if the repo was created in the database
 
        new_repo = self.sa.query(Repository).filter(Repository.repo_name ==
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name ==
 
                                                    repo_name).one()
 

	
 
        self.assertEqual(new_repo.repo_name, repo_name)
 
        self.assertEqual(new_repo.description, description)
 

	
 
        #test if repository is visible in the list ?
 
@@ -179,13 +179,13 @@ class TestAdminReposController(TestContr
 
        self.assertTrue('''deleted repository %s''' % (repo_name) in
 
                        response.session['flash'][0])
 

	
 
        response.follow()
 

	
 
        #check if repo was deleted from db
 
        deleted_repo = self.sa.query(Repository).filter(Repository.repo_name
 
        deleted_repo = self.Session().query(Repository).filter(Repository.repo_name
 
                                                        == repo_name).scalar()
 

	
 
        self.assertEqual(deleted_repo, None)
 

	
 

	
 
    def test_delete_repo_with_group(self):
rhodecode/tests/functional/test_admin_settings.py
Show inline comments
 
@@ -142,13 +142,13 @@ class TestAdminSettingsController(TestCo
 
                                             name=new_name,
 
                                             lastname=new_lastname,
 
                                             email=new_email,))
 
        response.follow()
 

	
 
        assert 'Your account was updated successfully' in response.session['flash'][0][1], 'no flash message about success of change'
 
        user = self.sa.query(User).filter(User.username == 'test_admin').one()
 
        user = self.Session().query(User).filter(User.username == 'test_admin').one()
 
        assert user.email == new_email , 'incorrect user email after update got %s vs %s' % (user.email, new_email)
 
        assert user.name == new_name, 'updated field mismatch %s vs %s' % (user.name, new_name)
 
        assert user.lastname == new_lastname, 'updated field mismatch %s vs %s' % (user.lastname, new_lastname)
 
        assert check_password(new_password, user.password) is True, 'password field mismatch %s vs %s' % (user.password, new_password)
 

	
 
        #bring back the admin settings
 
@@ -168,13 +168,13 @@ class TestAdminSettingsController(TestCo
 
                                                            email=old_email,))
 

	
 
        response.follow()
 
        self.checkSessionFlash(response,
 
                               'Your account was updated successfully')
 

	
 
        user = self.sa.query(User).filter(User.username == 'test_admin').one()
 
        user = self.Session().query(User).filter(User.username == 'test_admin').one()
 
        assert user.email == old_email , 'incorrect user email after update got %s vs %s' % (user.email, old_email)
 

	
 
        assert user.email == old_email , 'incorrect user email after update got %s vs %s' % (user.email, old_email)
 
        assert user.name == old_name, 'updated field mismatch %s vs %s' % (user.name, old_name)
 
        assert user.lastname == old_lastname, 'updated field mismatch %s vs %s' % (user.lastname, old_lastname)
 
        assert check_password(old_password, user.password) is True , 'password updated field mismatch %s vs %s' % (user.password, old_password)
rhodecode/tests/functional/test_admin_users.py
Show inline comments
 
@@ -29,13 +29,13 @@ class TestAdminUsersController(TestContr
 
                                               'lastname':lastname,
 
                                               'email':email})
 

	
 

	
 
        assert '''created user %s''' % (username) in response.session['flash'][0], 'No flash message about new user'
 

	
 
        new_user = self.sa.query(User).filter(User.username == username).one()
 
        new_user = self.Session().query(User).filter(User.username == username).one()
 

	
 

	
 
        assert new_user.username == username, 'wrong info about username'
 
        assert check_password(password, new_user.password) == True , 'wrong info about password'
 
        assert new_user.name == name, 'wrong info about name'
 
        assert new_user.lastname == lastname, 'wrong info about lastname'
 
@@ -63,13 +63,13 @@ class TestAdminUsersController(TestContr
 

	
 
        assert """<span class="error-message">Invalid username</span>""" in response.body
 
        assert """<span class="error-message">Please enter a value</span>""" in response.body
 
        assert """<span class="error-message">An email address must contain a single @</span>""" in response.body
 

	
 
        def get_user():
 
            self.sa.query(User).filter(User.username == username).one()
 
            self.Session().query(User).filter(User.username == username).one()
 

	
 
        self.assertRaises(NoResultFound, get_user), 'found user in database'
 

	
 
    def test_new(self):
 
        response = self.app.get(url('new_user'))
 

	
 
@@ -97,13 +97,13 @@ class TestAdminUsersController(TestContr
 
                                               'active':True,
 
                                               'lastname':lastname,
 
                                               'email':email})
 

	
 
        response = response.follow()
 

	
 
        new_user = self.sa.query(User).filter(User.username == username).one()
 
        new_user = self.Session().query(User).filter(User.username == username).one()
 
        response = self.app.delete(url('user', id=new_user.user_id))
 

	
 
        assert """successfully deleted user""" in response.session['flash'][0], 'No info about user deletion'
 

	
 

	
 
    def test_delete_browser_fakeout(self):
rhodecode/tests/functional/test_admin_users_groups.py
Show inline comments
 
@@ -49,19 +49,19 @@ class TestAdminUsersGroupsController(Tes
 
        response.follow()
 

	
 
        self.checkSessionFlash(response,
 
                               'created users group %s' % users_group_name)
 

	
 

	
 
        gr = self.sa.query(UsersGroup)\
 
        gr = self.Session().query(UsersGroup)\
 
                           .filter(UsersGroup.users_group_name ==
 
                                   users_group_name).one()
 

	
 
        response = self.app.delete(url('users_group', id=gr.users_group_id))
 

	
 
        gr = self.sa.query(UsersGroup)\
 
        gr = self.Session().query(UsersGroup)\
 
                           .filter(UsersGroup.users_group_name ==
 
                                   users_group_name).scalar()
 

	
 
        self.assertEqual(gr, None)
 

	
 

	
rhodecode/tests/functional/test_journal.py
Show inline comments
 
@@ -13,16 +13,16 @@ class TestJournalController(TestControll
 
        assert """ <span id="follow_toggle_1" class="following" title="Stop following this repository""" in response.body, 'no info about stop follwoing repo id 1'
 

	
 
        assert """<div class="journal_day">%s</div>""" % datetime.date.today() in response.body, 'no info about action journal day'
 

	
 
    def test_stop_following_repository(self):
 
        session = self.log_user()
 
#        usr = self.sa.query(User).filter(User.username == 'test_admin').one()
 
#        repo = self.sa.query(Repository).filter(Repository.repo_name == HG_REPO).one()
 
#        usr = self.Session().query(User).filter(User.username == 'test_admin').one()
 
#        repo = self.Session().query(Repository).filter(Repository.repo_name == HG_REPO).one()
 
#
 
#        followings = self.sa.query(UserFollowing)\
 
#        followings = self.Session().query(UserFollowing)\
 
#            .filter(UserFollowing.user == usr)\
 
#            .filter(UserFollowing.follows_repository == repo).all()
 
#
 
#        assert len(followings) == 1, 'Not following any repository'
 
#
 
#        response = self.app.post(url(controller='journal',
rhodecode/tests/functional/test_login.py
Show inline comments
 
@@ -189,13 +189,13 @@ class TestLoginController(TestController
 
                                             'email':email,
 
                                             'name':name,
 
                                             'lastname':lastname})
 
        self.assertEqual(response.status , '302 Found')
 
        assert 'You have successfully registered into rhodecode' in response.session['flash'][0], 'No flash message about user registration'
 

	
 
        ret = self.sa.query(User).filter(User.username == 'test_regular4').one()
 
        ret = self.Session().query(User).filter(User.username == 'test_regular4').one()
 
        assert ret.username == username , 'field mismatch %s %s' % (ret.username, username)
 
        assert check_password(password, ret.password) == True , 'password mismatch'
 
        assert ret.email == email , 'field mismatch %s %s' % (ret.email, email)
 
        assert ret.name == name , 'field mismatch %s %s' % (ret.name, name)
 
        assert ret.lastname == lastname , 'field mismatch %s %s' % (ret.lastname, lastname)
 

	
 
@@ -221,14 +221,14 @@ class TestLoginController(TestController
 
        new.username = username
 
        new.password = password
 
        new.email = email
 
        new.name = name
 
        new.lastname = lastname
 
        new.api_key = generate_api_key(username)
 
        self.sa.add(new)
 
        self.sa.commit()
 
        self.Session().add(new)
 
        self.Session().commit()
 

	
 
        response = self.app.post(url(controller='login',
 
                                     action='password_reset'),
 
                                 {'email':email, })
 

	
 
        self.checkSessionFlash(response, 'Your password reset link was sent')
rhodecode/tests/functional/test_settings.py
Show inline comments
 
@@ -29,13 +29,13 @@ class TestSettingsController(TestControl
 

	
 
        #test if we have a message that fork is ok
 
        assert 'forked %s repository as %s' \
 
                      % (repo_name, fork_name) in response.session['flash'][0], 'No flash message about fork'
 

	
 
        #test if the fork was created in the database
 
        fork_repo = self.sa.query(Repository).filter(Repository.repo_name == fork_name).one()
 
        fork_repo = self.Session().query(Repository).filter(Repository.repo_name == fork_name).one()
 

	
 
        assert fork_repo.repo_name == fork_name, 'wrong name of repo name in new db fork repo'
 
        assert fork_repo.fork.repo_name == repo_name, 'wrong fork parrent'
 

	
 

	
 
        #test if fork is visible in the list ?
rhodecode/tests/functional/test_summary.py
Show inline comments
 
@@ -40,8 +40,8 @@ class TestSummaryController(TestControll
 
        self.assertTrue("""<input type="text" id="clone_url" readonly="readonly" value="hg clone http://test_admin@localhost:80/%s" size="70"/>""" % HG_REPO in response.body)
 

	
 

	
 
    def _enable_stats(self):
 
        r = Repository.get_by_repo_name(HG_REPO)
 
        r.enable_statistics = True
 
        self.sa.add(r)
 
        self.sa.commit()
 
        self.Session().add(r)
 
        self.Session().commit()
rhodecode/tests/test_libs.py
Show inline comments
 
@@ -100,6 +100,17 @@ class TestLibs(unittest.TestCase):
 
            ('-1', False),
 
            ('', False), ]
 

	
 
        for case in test_cases:
 
            self.assertEqual(str2bool(case[0]), case[1])
 

	
 

	
 
    def test_mention_extractor(self):
 
        from rhodecode.lib import extract_mentioned_users
 
        sample = ("@first hi there @marcink here's my email marcin@email.com "
 
                  "@lukaszb check it pls @ ttwelve @D[] @one@two@three "
 
                  "@MARCIN    @maRCiN @2one_more22")
 
        s = ['2one_more22', 'D', 'MARCIN', 'first', 'lukaszb',
 
             'maRCiN', 'marcink', 'one']
 
        self.assertEqual(s, extract_mentioned_users(sample))
 

	
 

	
rhodecode/tests/test_models.py
Show inline comments
 
import os
 
import unittest
 
from rhodecode.tests import *
 

	
 
from rhodecode.model.repos_group import ReposGroupModel
 
from rhodecode.model.repo import RepoModel
 
from rhodecode.model.db import RepoGroup, User, Notification, UserNotification
 
from rhodecode.model.db import RepoGroup, User, Notification, UserNotification, \
 
    UsersGroup, UsersGroupMember
 
from sqlalchemy.exc import IntegrityError
 
from rhodecode.model.user import UserModel
 

	
 
from rhodecode.model import meta
 

	
 
Session = meta.Session()
 
from rhodecode.model.meta import Session
 
from rhodecode.model.notification import NotificationModel
 
from rhodecode.model.users_group import UsersGroupModel
 

	
 
class TestReposGroups(unittest.TestCase):
 

	
 
    def setUp(self):
 
        self.g1 = self.__make_group('test1', skip_if_exists=True)
 
        self.g2 = self.__make_group('test2', skip_if_exists=True)
 
@@ -152,74 +153,177 @@ class TestReposGroups(unittest.TestCase)
 
        self.__update_group(g1.group_id, 'g1', parent_id=g2.group_id)
 
        self.assertTrue(self.__check_path('g2', 'g1'))
 

	
 
        # test repo
 
        self.assertEqual(r.repo_name, os.path.join('g2', 'g1', r.just_name))
 

	
 
class TestUser(unittest.TestCase):
 

	
 
    def test_create_and_remove(self):
 
        usr = UserModel().create_or_update(username=u'test_user', password=u'qweqwe',
 
                                     email=u'u232@rhodecode.org',
 
                                     name=u'u1', lastname=u'u1')
 
        self.assertEqual(User.get_by_username(u'test_user'), usr)
 

	
 
        # make users group
 
        users_group = UsersGroupModel().create_('some_example_group')
 
        Session().commit()
 
        UsersGroupModel().add_user_to_group(users_group, usr)
 

	
 
        self.assertEqual(UsersGroup.get(users_group.users_group_id), users_group)
 
        self.assertEqual(UsersGroupMember.query().count(), 1)
 
        UserModel().delete(usr.user_id)
 

	
 
        self.assertEqual(UsersGroupMember.query().all(), [])
 

	
 

	
 
class TestNotifications(unittest.TestCase):
 

	
 

	
 

	
 
    def setUp(self):
 
        self.u1 = UserModel().create_or_update(username=u'u1', password=u'qweqwe',
 
    def __init__(self, methodName='runTest'):
 
        self.u1 = UserModel().create_or_update(username=u'u1',
 
                                        password=u'qweqwe',
 
                                               email=u'u1@rhodecode.org',
 
                                               name=u'u1', lastname=u'u1')
 
        self.u2 = UserModel().create_or_update(username=u'u2', password=u'qweqwe',
 
                                        name=u'u1', lastname=u'u1').user_id
 
        self.u2 = UserModel().create_or_update(username=u'u2',
 
                                        password=u'qweqwe',
 
                                               email=u'u2@rhodecode.org',
 
                                               name=u'u2', lastname=u'u3')
 
        self.u3 = UserModel().create_or_update(username=u'u3', password=u'qweqwe',
 
                                        name=u'u2', lastname=u'u3').user_id
 
        self.u3 = UserModel().create_or_update(username=u'u3',
 
                                        password=u'qweqwe',
 
                                               email=u'u3@rhodecode.org',
 
                                               name=u'u3', lastname=u'u3')
 
    def tearDown(self):
 
        User.delete(self.u1.user_id)
 
        User.delete(self.u2.user_id)
 
        User.delete(self.u3.user_id)
 
                                        name=u'u3', lastname=u'u3').user_id
 
        super(TestNotifications, self).__init__(methodName=methodName)
 

	
 
    def _clean_notifications(self):
 
        for n in Notification.query().all():
 
            Session().delete(n)
 

	
 
        Session().commit()
 
        self.assertEqual(Notification.query().all(), [])
 

	
 

	
 
    def test_create_notification(self):
 
        self.assertEqual([], Notification.query().all())
 
        self.assertEqual([], UserNotification.query().all())
 

	
 
        usrs = [self.u1, self.u2]
 
        notification = Notification.create(created_by=self.u1,
 
        notification = NotificationModel().create(created_by=self.u1,
 
                                           subject=u'subj', body=u'hi there',
 
                                           recipients=usrs)
 
        Session.commit()
 

	
 

	
 
        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)
 

	
 
        unotification = UserNotification.query()\
 
            .filter(UserNotification.notification == notification).all()
 

	
 
        self.assertEqual(notifications[0].recipients, [self.u1, self.u2])
 
        self.assertEqual(notifications[0].recipients, [u1, u2])
 
        self.assertEqual(notification.notification_id,
 
                         notifications[0].notification_id)
 
        self.assertEqual(len(unotification), len(usrs))
 
        self.assertEqual([x.user.user_id for x in unotification],
 
                         [x.user_id for x in usrs])
 
        self.assertEqual([x.user.user_id for x in unotification], usrs)
 

	
 
        self._clean_notifications()
 

	
 
    def test_user_notifications(self):
 
        notification1 = Notification.create(created_by=self.u1,
 
                                            subject=u'subj', body=u'hi there',
 
        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])
 
        notification2 = Notification.create(created_by=self.u1,
 
                                            subject=u'subj', body=u'hi there',
 
        Session().commit()
 
        notification2 = NotificationModel().create(created_by=self.u1,
 
                                            subject=u'subj', body=u'hi there2',
 
                                            recipients=[self.u3])
 
        self.assertEqual(self.u3.notifications, [notification1, notification2])
 
        Session().commit()
 
        u3 = Session().query(User).get(self.u3)
 

	
 
        self.assertEqual(sorted([x.notification for x in u3.notifications]),
 
                         sorted([notification2, notification1]))
 
        self._clean_notifications()
 

	
 
    def test_delete_notifications(self):
 
        notification = Notification.create(created_by=self.u1,
 
        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()
 
        Session().commit()
 
        notifications = Notification.query().all()
 
        self.assertTrue(notification in notifications)
 

	
 
        Notification.delete(notification.notification_id)
 
        Session.commit()
 
        Session().commit()
 

	
 
        notifications = Notification.query().all()
 
        self.assertFalse(notification in notifications)
 

	
 
        un = UserNotification.query().filter(UserNotification.notification
 
                                             == notification).all()
 
        self.assertEqual(un, [])
 

	
 
        self._clean_notifications()
 
    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()
 

	
 
        unotification = UserNotification.query()\
 
                            .filter(UserNotification.notification ==
 
                                    notification)\
 
                            .filter(UserNotification.user_id == self.u3)\
 
                            .scalar()
 

	
 
        self.assertEqual(unotification, None)
 
        self._clean_notifications()
 

	
 
    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)
 
        self._clean_notifications()
0 comments (0 inline, 0 general)