Example #1
0
    def test_test_context_broken_app(self):
        from webtest import TestApp
        from tg import AppConfig, config
        from tg.request_local import context

        app = TestApp(
            AppConfig(minimal=True, root_controller=None).make_wsgi_app())

        try:
            with test_context(app):
                raise RuntimeError('This is an error')
        except RuntimeError:
            pass
        else:
            assert False, 'Should have raised RuntimeError...'

        with test_context(app):
            config._pop_object()
        # Check that context got cleaned up even though config caused an exception
        assert not context._object_stack()

        with test_context(app):
            context._pop_object()
        # Check that config got cleaned up even though context caused an exception
        assert not config._object_stack()
Example #2
0
    def test_test_context_broken_app(self):
        from webtest import TestApp
        from tg import AppConfig, config
        from tg.request_local import context

        app = TestApp(AppConfig(
            minimal=True,
            root_controller=None
        ).make_wsgi_app())

        try:
            with test_context(app):
                raise RuntimeError('This is an error')
        except RuntimeError:
            pass
        else:
            assert False, 'Should have raised RuntimeError...'

        with test_context(app):
            config._pop_object()
        # Check that context got cleaned up even though config caused an exception
        assert not context._object_stack()

        with test_context(app):
            context._pop_object()
        # Check that config got cleaned up even though context caused an exception
        assert not config._object_stack()
Example #3
0
 def test_age_in_future(self, age_args, expected):
     from kallithea.lib.utils2 import age
     from dateutil import relativedelta
     with test_context(self.app):
         n = datetime.datetime(year=2012, month=5, day=17)
         delt = lambda *args, **kwargs: relativedelta.relativedelta(*args, **kwargs)
         assert age(n + delt(**age_args), now=n) == expected
    def test_delete_ips(self, auto_clear_ip_permissions):
        self.log_user()
        default_user_id = User.get_default_user().user_id

        ## first add
        new_ip = '127.0.0.0/24'
        with test_context(self.app):
            user_model = UserModel()
            ip_obj = user_model.add_extra_ip(default_user_id, new_ip)
            Session().commit()

        ## double check that add worked
        # IP permissions are cached, need to invalidate this cache explicitly
        invalidate_all_caches()
        self.app.get(url('admin_permissions_ips'), status=302)
        # REMOTE_ADDR must match 127.0.0.0/24
        response = self.app.get(url('admin_permissions_ips'),
                                extra_environ={'REMOTE_ADDR': '127.0.0.1'})
        response.mustcontain('127.0.0.0/24')
        response.mustcontain('127.0.0.0 - 127.0.0.255')

        ## now delete
        response = self.app.post(
            url('edit_user_ips_delete', id=default_user_id),
            params=dict(del_ip_id=ip_obj.ip_id,
                        _authentication_token=self.authentication_token()),
            extra_environ={'REMOTE_ADDR': '127.0.0.1'})

        # IP permissions are cached, need to invalidate this cache explicitly
        invalidate_all_caches()

        response = self.app.get(url('admin_permissions_ips'))
        response.mustcontain('All IP addresses are allowed')
        response.mustcontain(no=['127.0.0.0/24'])
        response.mustcontain(no=['127.0.0.0 - 127.0.0.255'])
    def test_show(self, create_test_user):
        self.log_user()
        with test_context(self.app):
            cur_user = self._get_logged_user()
            u1 = create_test_user(dict(username='******', password='******',
                                       email='*****@*****.**',
                                       firstname=u'u1', lastname=u'u1',
                                       active=True))
            u2 = create_test_user(dict(username='******', password='******',
                                       email='*****@*****.**',
                                       firstname=u'u2', lastname=u'u2',
                                       active=True))
            Session().commit()

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

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

        response.mustcontain(subject)
        response.mustcontain(notif_body)
Example #6
0
    def test_delete_ip(self, auto_clear_ip_permissions):
        self.log_user()
        user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
        user_id = user.user_id
        ip = '127.0.0.1/32'
        ip_range = '127.0.0.1 - 127.0.0.1'
        with test_context(self.app):
            new_ip = UserModel().add_extra_ip(user_id, ip)
            Session().commit()
        new_ip_id = new_ip.ip_id

        response = self.app.get(base.url('edit_user_ips', id=user_id))
        response.mustcontain(ip)
        response.mustcontain(ip_range)

        self.app.post(
            base.url('edit_user_ips_delete', id=user_id),
            params=dict(
                del_ip_id=new_ip_id,
                _session_csrf_secret_token=self.session_csrf_secret_token()))

        response = self.app.get(base.url('edit_user_ips', id=user_id))
        response.mustcontain('All IP addresses are allowed')
        response.mustcontain(no=[ip])
        response.mustcontain(no=[ip_range])
Example #7
0
    def test_create_err(self):
        self.log_user()
        username = '******'
        password = ''
        name = 'name'
        lastname = 'lastname'
        email = 'errmail.example.com'

        response = self.app.post(
            base.url('new_user'), {
                'username': username,
                'password': password,
                'name': name,
                'active': False,
                'lastname': lastname,
                'email': email,
                '_session_csrf_secret_token': self.session_csrf_secret_token()
            })

        with test_context(self.app):
            msg = validators.ValidUsername(
                False, {})._messages['system_invalid_username']
        msg = h.html_escape(msg % {'username': '******'})
        response.mustcontain("""<span class="error-message">%s</span>""" % msg)
        response.mustcontain(
            """<span class="error-message">Please enter a value</span>""")
        response.mustcontain(
            """<span class="error-message">An email address must contain a single @</span>"""
        )

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

        with pytest.raises(NoResultFound):
            get_user(), 'found user in database'
Example #8
0
def test_context_fixture(app_fixture):
    """
    Encompass the entire test using this fixture in a test_context,
    making sure that certain functionality still works even if no call to
    self.app.get/post has been made.
    The typical error message indicating you need a test_context is:
        TypeError: No object (name: context) has been registered for this thread

    The standard way to fix this is simply using the test_context context
    manager directly inside your test:
        with test_context(self.app):
            <actions>
    but if test setup code (xUnit-style or pytest fixtures) also needs to be
    executed inside the test context, that method is not possible.
    Even if there is no such setup code, the fixture may reduce code complexity
    if the entire test needs to run inside a test context.

    To apply this fixture (like any other fixture) to all test methods of a
    class, use the following class decorator:
        @pytest.mark.usefixtures("test_context_fixture")
        class TestFoo(TestController):
            ...
    """
    with test_context(app_fixture):
        yield
Example #9
0
 def create_pullrequest(self,
                        testcontroller,
                        repo_name,
                        pr_src_rev,
                        pr_dst_rev,
                        title='title'):
     org_ref = 'branch:stable:%s' % pr_src_rev
     other_ref = 'branch:default:%s' % pr_dst_rev
     with test_context(
             testcontroller.app):  # needed to be able to mock request user
         org_repo = other_repo = Repository.get_by_repo_name(repo_name)
         owner_user = User.get_by_username(TEST_USER_ADMIN_LOGIN)
         reviewers = [User.get_by_username(TEST_USER_REGULAR_LOGIN)]
         request.authuser = AuthUser(dbuser=owner_user)
         # creating a PR sends a message with an absolute URL - without routing that requires mocking
         with mock.patch.object(
                 helpers, 'url',
             (lambda arg, qualified=False, **kwargs:
              ('https://localhost' if qualified else '') + '/fake/' + arg)):
             cmd = CreatePullRequestAction(org_repo, other_repo, org_ref,
                                           other_ref, title,
                                           'No description', owner_user,
                                           reviewers)
             pull_request = cmd.execute()
         Session().commit()
     return pull_request.pull_request_id
Example #10
0
    def test_document_content_validator(self):
        with test_context(self.app):
            model.Output(
                title="FakeOutput",
                content="Content of the fake output",
                html='',
                _owner=self._get_user('*****@*****.**')._id,
                _category=self._get_category('Area 1')._id,
                _precondition=None,
            )
            DBSession.flush()
            output = model.Output.query.get(title="FakeOutput")

            validator = DocumentContentValidator()
            try:
                res = validator._validate_python([
                    {
                        'type': "output",
                        'content': str(output._id),
                        'title': output.title
                    },
                ])
            except ValidationError:
                assert False
            else:
                assert True
    def test_show(self, create_test_user):
        self.log_user()
        with test_context(self.app):
            cur_user = self._get_logged_user()
            u1 = create_test_user(
                dict(username='******',
                     password='******',
                     email='*****@*****.**',
                     firstname=u'u1',
                     lastname=u'u1',
                     active=True))
            u2 = create_test_user(
                dict(username='******',
                     password='******',
                     email='*****@*****.**',
                     firstname=u'u2',
                     lastname=u'u2',
                     active=True))
            Session().commit()

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

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

        response.mustcontain(subject)
        response.mustcontain(notif_body)
    def test_index(self, create_test_user):
        self.log_user()

        u1 = create_test_user(
            dict(username='******',
                 password='******',
                 email='*****@*****.**',
                 firstname=u'u1',
                 lastname=u'u1',
                 active=True))
        u1 = u1.user_id
        Session().commit()

        response = self.app.get(url('notifications'))
        response.mustcontain('<div>No notifications here yet</div>')

        with test_context(self.app):
            cur_user = self._get_logged_user()
            notif = 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'))
        response.mustcontain('id="notification_%s"' % notif.notification_id)
Example #13
0
    def test_create_delete_general_comment(self):
        with test_context(self.app):
            repo_id = Repository.get_by_repo_name(base.HG_REPO).repo_id
            revision = '9a7b4ff9e8b40bbda72fc75f162325b9baa45cda'

            self._check_comment_count(repo_id,
                                      revision,
                                      expected_len_comments=0,
                                      expected_len_inline_comments=0)

            text = 'a comment'
            new_comment = ChangesetCommentsModel().create(
                text=text,
                repo=base.HG_REPO,
                author=base.TEST_USER_REGULAR_LOGIN,
                revision=revision,
                send_email=False)

            self._check_comment_count(repo_id,
                                      revision,
                                      expected_len_comments=1,
                                      expected_len_inline_comments=0)

            ChangesetCommentsModel().delete(new_comment)

            self._check_comment_count(repo_id,
                                      revision,
                                      expected_len_comments=0,
                                      expected_len_inline_comments=0)
Example #14
0
    def test_create_notification(self):
        with test_context(self.app):
            usrs = [self.u1, self.u2]
            def send_email(recipients, subject, body='', html_body='', headers=None, author=None):
                assert recipients == ['*****@*****.**']
                assert subject == 'Test Message'
                assert body == u"hi there"
                assert '>hi there<' in html_body
                assert author.username == 'u1'
            with mock.patch.object(kallithea.lib.celerylib.tasks, 'send_email', send_email):
                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()
                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_id for x in unotification]) == set(usrs)
    def test_create_err(self):
        self.log_user()
        username = '******'
        password = ''
        name = u'name'
        lastname = u'lastname'
        email = 'errmail.example.com'

        response = self.app.post(url('new_user'),
            {'username': username,
             'password': password,
             'name': name,
             'active': False,
             'lastname': lastname,
             'email': email,
             '_authentication_token': self.authentication_token()})

        with test_context(self.app):
            msg = validators.ValidUsername(False, {})._messages['system_invalid_username']
        msg = h.html_escape(msg % {'username': '******'})
        response.mustcontain("""<span class="error-message">%s</span>""" % msg)
        response.mustcontain("""<span class="error-message">Please enter a value</span>""")
        response.mustcontain("""<span class="error-message">An email address must contain a single @</span>""")

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

        with pytest.raises(NoResultFound):
            get_user(), 'found user in database'
Example #16
0
def test_context_fixture(app_fixture):
    """
    Encompass the entire test using this fixture in a test_context,
    making sure that certain functionality still works even if no call to
    self.app.get/post has been made.
    The typical error message indicating you need a test_context is:
        TypeError: No object (name: context) has been registered for this thread

    The standard way to fix this is simply using the test_context context
    manager directly inside your test:
        with test_context(self.app):
            <actions>
    but if test setup code (xUnit-style or pytest fixtures) also needs to be
    executed inside the test context, that method is not possible.
    Even if there is no such setup code, the fixture may reduce code complexity
    if the entire test needs to run inside a test context.

    To apply this fixture (like any other fixture) to all test methods of a
    class, use the following class decorator:
        @pytest.mark.usefixtures("test_context_fixture")
        class TestFoo(TestController):
            ...
    """
    with test_context(app_fixture):
        yield
Example #17
0
def test_lurl():
    """url() can handle list parameters, with unicode too"""
    with test_context(None, '/'):
        value = lurl('/lurl')
        assert not isinstance(value, string_type)
        assert value.startswith('/lurl')
        assert str(value) == repr(value) == value.id == value.encode('utf-8').decode('utf-8') == value.__html__()
Example #18
0
def test_unicode():
    """url() can handle unicode parameters"""
    with test_context(None, '/'):
        unicodestring =  u_('àèìòù')
        eq_(url('/', params=dict(x=unicodestring)),
            '/?x=%C3%A0%C3%A8%C3%AC%C3%B2%C3%B9'
            )
    def test_delete_ips(self, auto_clear_ip_permissions):
        self.log_user()
        default_user_id = User.get_default_user().user_id

        ## first add
        new_ip = '127.0.0.0/24'
        with test_context(self.app):
            user_model = UserModel()
            ip_obj = user_model.add_extra_ip(default_user_id, new_ip)
            Session().commit()

        ## double check that add worked
        # IP permissions are cached, need to invalidate this cache explicitly
        invalidate_all_caches()
        self.app.get(url('admin_permissions_ips'), status=302)
        # REMOTE_ADDR must match 127.0.0.0/24
        response = self.app.get(url('admin_permissions_ips'),
                                extra_environ={'REMOTE_ADDR': '127.0.0.1'})
        response.mustcontain('127.0.0.0/24')
        response.mustcontain('127.0.0.0 - 127.0.0.255')

        ## now delete
        response = self.app.post(url('edit_user_ips_delete', id=default_user_id),
                                 params=dict(del_ip_id=ip_obj.ip_id,
                                             _authentication_token=self.authentication_token()),
                                 extra_environ={'REMOTE_ADDR': '127.0.0.1'})

        # IP permissions are cached, need to invalidate this cache explicitly
        invalidate_all_caches()

        response = self.app.get(url('admin_permissions_ips'))
        response.mustcontain('All IP addresses are allowed')
        response.mustcontain(no=['127.0.0.0/24'])
        response.mustcontain(no=['127.0.0.0 - 127.0.0.255'])
Example #20
0
    def test_url_object_unicodeerror(self):
        class Object(object):
            def __str__(self):
                return u_('àèìòù')

        with test_context(None, '/'):
            res = url('.', {'p1': Object()})
            assert res == '.?p1=%C3%A0%C3%A8%C3%AC%C3%B2%C3%B9'
Example #21
0
    def test_url_object_exception(self):
        class SubException(Exception):
            def __str__(self):
                return u_('àèìòù')

        with test_context(None, '/'):
            res = url('.', {'p1': SubException('a', 'b', 'c')})
            assert res == '.?p1=a+b+c', res
Example #22
0
 def test_age_in_future(self, age_args, expected):
     from kallithea.lib.utils2 import age
     from dateutil import relativedelta
     with test_context(self.app):
         n = datetime.datetime(year=2012, month=5, day=17)
         delt = lambda *args, **kwargs: relativedelta.relativedelta(
             *args, **kwargs)
         assert age(n + delt(**age_args), now=n) == expected
Example #23
0
 def test_filename_template_not_found(self):
     try:
         with test_context(self.app):
             res = self.render('this_doesnt_exists/this_doesnt_exists.xhtml', {})
     except IOError as e:
         assert 'this_doesnt_exists.xhtml not found in template paths' in str(e)
     else:
         raise AssertionError('Should have raised IOError')
Example #24
0
    def test_url_object_unicodeerror(self):
        class Object(object):
            def __str__(self):
                return u_('àèìòù')

        with test_context(None, '/'):
            res = url('.', {'p1': Object()})
            assert res == '.?p1=%C3%A0%C3%A8%C3%AC%C3%B2%C3%B9'
Example #25
0
def test_multi_values():
    with test_context(None, '/'):
        r = url("/foo", params=dict(bar=("asdf", "qwer")))
        assert r in \
                ["/foo?bar=qwer&bar=asdf", "/foo?bar=asdf&bar=qwer"], r
        r = url("/foo", params=dict(bar=[1, 2]))
        assert r in \
                ["/foo?bar=1&bar=2", "/foo?bar=2&bar=1"], r
Example #26
0
def test_lurl():
    """url() can handle list parameters, with unicode too"""
    with test_context(None, '/'):
        value = lurl('/lurl')
        assert not isinstance(value, string_type)
        assert value.startswith('/lurl')
        assert str(value) == repr(value) == value.id == value.encode(
            'utf-8').decode('utf-8') == value.__html__()
Example #27
0
 def test_dotted_template_not_found(self):
     try:
         with test_context(self.app):
             res = self.render('tests.test_stack.rendering.templates.this_doesnt_exists', {})
     except IOError as e:
         assert 'this_doesnt_exists.xhtml not found' in str(e)
     else:
         raise AssertionError('Should have raised IOError')
Example #28
0
def test_multi_values():
    with test_context(None, '/'):
        r = url("/foo", params=dict(bar=("asdf", "qwer")))
        assert r in \
                ["/foo?bar=qwer&bar=asdf", "/foo?bar=asdf&bar=qwer"], r
        r = url("/foo", params=dict(bar=[1,2]))
        assert r in \
                ["/foo?bar=1&bar=2", "/foo?bar=2&bar=1"], r
Example #29
0
    def test_url_object_exception(self):
        class SubException(Exception):
            def __str__(self):
                return u_('àèìòù')

        with test_context(None, '/'):
            res = url('.', {'p1': SubException('a', 'b', 'c')})
            assert res == '.?p1=a+b+c', res
Example #30
0
    def test_url_object(self):
        class Object(object):
            def __str__(self):
                return 'aeiou'

        with test_context(None, '/'):
            res = url('.', {'p1': Object()})
            assert res == '.?p1=aeiou'
Example #31
0
    def test_url_object(self):
        class Object(object):
            def __str__(self):
                return 'aeiou'

        with test_context(None, '/'):
            res = url('.', {'p1': Object()})
            assert res == '.?p1=aeiou'
Example #32
0
 def test_precondition_exist_invalid_id_validator(self):
     with test_context(self.app):
         validator = PreconditionExistValidator()
         try:
             res = validator._validate_python("Invalid")
         except ValidationError:
             assert True
         else:
             assert False
Example #33
0
 def test_output_not_exist_validator(self):
     with test_context(self.app):
         validator = OutputExistValidator()
         try:
             res = validator._validate_python("5757ce79c42d752bde919318")
         except ValidationError as v:
             eq_(v.message, 'Output does not exists')
         else:
             assert False
Example #34
0
 def test_document_content_validator_without_output(self):
     with test_context(self.app):
         validator = DocumentContentValidator()
         try:
             res = validator._validate_python("Buongiorno")
         except ValidationError:
             assert False
         else:
             assert True
Example #35
0
    def test_navigator_ajax(self):
        with test_context(None, '/'):
            p = Page(range(100), items_per_page=10, page=5)
            pager = p.pager(onclick='goto($page)')

            assert 'goto(1)' in pager
            assert 'goto(4)' in pager
            assert 'goto(6)' in pager
            assert 'goto(10)' in pager
Example #36
0
 def test_questionary_not_exist_validator(self):
     with test_context(self.app):
         validator = QuestionaryExistValidator()
         try:
             res = validator._validate_python("5757ce79c42d752bde919318")
         except ValidationError:
             assert True
         else:
             assert False
Example #37
0
 def test_questionary_invalid_id_validator(self):
     with test_context(self.app):
         validator = QuestionaryExistValidator()
         try:
             res = validator._validate_python("Invalid")
         except ValidationError:
             assert True
         else:
             assert False
Example #38
0
 def test_workspace_exist_validator_with_obj_not_valid(self):
     with test_context(self.app):
         validator = WorkspaceExistValidator()
         try:
             res = validator._validate_python('not_obj_id')
         except ValidationError:
             assert True
         else:
             assert False
Example #39
0
    def test_navigator_ajax(self):
        with test_context(None, '/'):
            p = Page(range(100), items_per_page=10, page=5)
            pager = p.pager(onclick='goto($page)')

            assert 'goto(1)' in pager
            assert 'goto(4)' in pager
            assert 'goto(6)' in pager
            assert 'goto(10)' in pager
Example #40
0
    def test_navigator_middle_page(self):
        with test_context(None, '/'):
            p = Page(range(100), items_per_page=10, page=5)
            pager = p.pager()

            assert '?page=1' in pager
            assert '?page=4' in pager
            assert '?page=6' in pager
            assert '?page=10' in pager
Example #41
0
 def test_kajiki_with_context_async(self):
     # tgext.asyncjob can't start an asyncjob without a context.
     with test_context(self.app):
         send_email(recipients=['*****@*****.**'],
                    sender='Marco Bosio <*****@*****.**>',
                    translation='IT',
                    mail_model_name=u'TranslateEmail',
                    data=dict(body='body', mail_title='titolo mail'),
                    send_async=True)
Example #42
0
 def test_workspace_exist_validator_with_not_existing_workspace(self):
     with test_context(self.app):
         validator = WorkspaceExistValidator()
         try:
             res = validator._validate_python('5757ce79c42d752bde919318')
         except ValidationError:
             assert True
         else:
             assert False
Example #43
0
    def test_navigator_middle_page(self):
        with test_context(None, '/'):
            p = Page(range(100), items_per_page=10, page=5)
            pager = p.pager()

            assert '?page=1' in pager
            assert '?page=4' in pager
            assert '?page=6' in pager
            assert '?page=10' in pager
Example #44
0
 def test_kajiki_with_context(self, _):
     with test_context(self.app):
         send_email(
             recipients=['*****@*****.**'],
             sender='Marco Bosio <*****@*****.**>',
             translation='IT',
             mail_model_name=u'TranslateEmail',
             data=dict(body='body', mail_title='titolo mail'),
             send_async=False,
         )
Example #45
0
 def test_filename_template_not_found(self):
     try:
         with test_context(self.app):
             res = self.render(
                 'this_doesnt_exists/this_doesnt_exists.xhtml', {})
     except IOError as e:
         assert 'this_doesnt_exists.xhtml not found in template paths' in str(
             e)
     else:
         raise AssertionError('Should have raised IOError')
Example #46
0
 def test_dotted_template_not_found(self):
     try:
         with test_context(self.app):
             res = self.render(
                 'tests.test_stack.rendering.templates.this_doesnt_exists',
                 {})
     except IOError as e:
         assert 'this_doesnt_exists.xhtml not found' in str(e)
     else:
         raise AssertionError('Should have raised IOError')
Example #47
0
    def test_test_context(self):
        with test_context(None):
            test_url = url('/test')
            assert test_url == '/test', test_url

        try:
            url('/test')
        except:
            pass
        else:
            assert False, 'Should have raised exception...'
Example #48
0
def test_lurl_as_HTTPFound_location():
    with test_context(None, '/'):
        exc = HTTPFound(location=lurl('/lurl'))

        def _fake_start_response(*args, **kw):
            pass

        resp = exc({'PATH_INFO':'/',
                    'wsgi.url_scheme': 'HTTP',
                    'REQUEST_METHOD': 'GET',
                    'SERVER_NAME': 'localhost',
                    'SERVER_PORT': '80'}, _fake_start_response)
        assert b'resource was found at http://localhost:80/lurl' in resp[0]
    def test_user_notifications(self):
        with test_context(self.app):
            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)

            assert sorted([x.notification for x in u3.notifications]) == sorted([notification2, notification1])
Example #50
0
 def create_pullrequest(self, testcontroller, repo_name, pr_src_rev, pr_dst_rev, title=u'title'):
     org_ref = 'branch:stable:%s' % pr_src_rev
     other_ref = 'branch:default:%s' % pr_dst_rev
     with test_context(testcontroller.app): # needed to be able to mock request user
         org_repo = other_repo = Repository.get_by_repo_name(repo_name)
         owner_user = User.get_by_username(TEST_USER_ADMIN_LOGIN)
         reviewers = [User.get_by_username(TEST_USER_REGULAR_LOGIN)]
         request.authuser = request.user = AuthUser(dbuser=owner_user)
         # creating a PR sends a message with an absolute URL - without routing that requires mocking
         with mock.patch.object(helpers, 'url', (lambda arg, qualified=False, **kwargs: ('https://localhost' if qualified else '') + '/fake/' + arg)):
             cmd = CreatePullRequestAction(org_repo, other_repo, org_ref, other_ref, title, u'No description', owner_user, reviewers)
             pull_request = cmd.execute()
         Session().commit()
     return pull_request.pull_request_id
Example #51
0
    def test_unit__change_datetime_timezone__ok__with_naive_and_current_user(self):  # nopep8
        user_mock = MagicMock(timezone='America/Guadeloupe')

        with test_context(self.app):
            tmpl_context.current_user = user_mock
            naive_datetime = datetime.datetime(2000, 1, 1, 0, 0, 0)

            new_datetime = h.get_with_timezone(
                datetime_object=naive_datetime,
                default_from_timezone='UTC',
                to_timezone='',  # user_mock.timezone should be used
            )

            eq_(str(new_datetime), '1999-12-31 20:00:00-04:00')
    def test_description_with_datetime(self):
        self.log_user()
        with test_context(self.app):
            cur_user = self._get_logged_user()
            subject = u'test'
            notify_body = u'hi there'
            notification = NotificationModel().create(created_by = cur_user,
                                                      subject    = subject,
                                                      body       = notify_body)

            description = NotificationModel().make_description(notification, False)
            assert description == "{0} sent message at {1}".format(
                    cur_user.username,
                    h.fmt_date(notification.created_on)
                    )
    def test_delete_notifications(self):
        with test_context(self.app):
            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()
            assert notification in notifications

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

            notifications = Notification.query().all()
            assert not notification in notifications

            un = UserNotification.query().filter(UserNotification.notification
                                                 == notification).all()
            assert un == []
    def test_notification_counter(self):
        with test_context(self.app):
            NotificationModel().create(created_by=self.u1,
                                subject=u'title', body=u'hi there_delete',
                                recipients=[self.u3, self.u1])
            Session().commit()

            assert NotificationModel().get_unread_cnt_for_user(self.u1) == 0
            assert NotificationModel().get_unread_cnt_for_user(self.u2) == 0
            assert 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()

            assert NotificationModel().get_unread_cnt_for_user(self.u1) == 0
            assert NotificationModel().get_unread_cnt_for_user(self.u2) == 1
            assert NotificationModel().get_unread_cnt_for_user(self.u3) == 2
    def test_delete_association(self):
        with test_context(self.app):
            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()

            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 == 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 != None
            u2notification = UserNotification.query() \
                                .filter(UserNotification.notification ==
                                        notification) \
                                .filter(UserNotification.user_id == self.u2) \
                                .scalar()
            assert u2notification != None
    def test_index(self, create_test_user):
        self.log_user()

        u1 = create_test_user(dict(username='******', password='******',
                                   email='*****@*****.**',
                                   firstname=u'u1', lastname=u'u1',
                                   active=True))
        u1 = u1.user_id
        Session().commit()

        response = self.app.get(url('notifications'))
        response.mustcontain('<div>No notifications here yet</div>')

        with test_context(self.app):
            cur_user = self._get_logged_user()
            notif = 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'))
        response.mustcontain('id="notification_%s"' % notif.notification_id)
    def test_my_account_update_err(self):
        self.log_user(TEST_USER_REGULAR2_LOGIN, TEST_USER_REGULAR2_PASS)

        new_email = 'newmail.pl'
        response = self.app.post(url('my_account'),
                                 params=dict(
                                            username=TEST_USER_ADMIN_LOGIN,
                                            new_password=TEST_USER_ADMIN_PASS,
                                            password_confirmation='test122',
                                            firstname=u'NewName',
                                            lastname=u'NewLastname',
                                            email=new_email,
                                            _authentication_token=self.authentication_token()))

        response.mustcontain('An email address must contain a single @')
        from kallithea.model import validators
        with test_context(self.app):
            msg = validators.ValidUsername(edit=False, old_data={}) \
                    ._messages['username_exists']
        msg = h.html_escape(msg % {'username': TEST_USER_ADMIN_LOGIN})
        response.mustcontain(msg)
    def test_delete_ip(self, auto_clear_ip_permissions):
        self.log_user()
        user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
        user_id = user.user_id
        ip = '127.0.0.1/32'
        ip_range = '127.0.0.1 - 127.0.0.1'
        with test_context(self.app):
            new_ip = UserModel().add_extra_ip(user_id, ip)
            Session().commit()
        new_ip_id = new_ip.ip_id

        response = self.app.get(url('edit_user_ips', id=user_id))
        response.mustcontain(ip)
        response.mustcontain(ip_range)

        self.app.post(url('edit_user_ips_delete', id=user_id),
                      params=dict(del_ip_id=new_ip_id, _authentication_token=self.authentication_token()))

        response = self.app.get(url('edit_user_ips', id=user_id))
        response.mustcontain('All IP addresses are allowed')
        response.mustcontain(no=[ip])
        response.mustcontain(no=[ip_range])
    def test_delete(self, create_test_user):
        self.log_user()
        cur_user = self._get_logged_user()

        with test_context(self.app):
            u1 = create_test_user(dict(username='******', password='******',
                                       email='*****@*****.**',
                                       firstname=u'u1', lastname=u'u1',
                                       active=True))
            u2 = create_test_user(dict(username='******', password='******',
                                       email='*****@*****.**',
                                       firstname=u'u2', lastname=u'u2',
                                       active=True))

            # 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
        get_notif = lambda un: [x.notification for x in un]
        assert get_notif(cur_user.notifications) == [notification]
        assert get_notif(u1.notifications) == [notification]
        assert get_notif(u2.notifications) == [notification]
        cur_usr_id = cur_user.user_id

        response = self.app.post(
            url('notification_delete', notification_id=notification.notification_id),
            params={'_authentication_token': self.authentication_token()})
        assert response.body == 'ok'

        cur_user = User.get(cur_usr_id)
        assert cur_user.notifications == []