view test/test_actions.py @ 3682:193f316dbbe9

More transitive-property support. - Implemented transitive properties in sort and group specs. Sort/group specs can now be lists of specs. - All regression tests except for one metakit backend test related to metakit having no representation of NULL pass - Fixed more PEP 8 whitespace peeves (and probably introduced some new ones :-) - Moved Proptree from support.py to hyperdb.py due to circular import - Moved some proptree-specific methods from Class to Proptree - Added a test for sorting by ids -> should be numeric sort (which now really works for all backends) - Added "required" attribute to all property classes in hyperdb (e.g., String, Link,...), see Feature Requests [SF#539081] -> factored common stuff to _Type. Note that I also converted to a new-style class when I was at it. Bad: The repr changes for new-style classes which made some SQL backends break (!) because the repr of Multilink is used in the schema storage. Fixed the repr to be independent of the class type. - Added get_required_props to Class. Todo: should also automagically make the key property required... - Add a sort_repr method to property classes. This defines the sort-order. Individual backends may use diffent routines if the outcome is the same. This one has a special case for id properties to make the sorting numeric. Using these methods isn't mandatory in backends as long as the sort-order is correct. - Multilink sorting takes orderprop into account. It used to sort by ids. You can restore the old behaviour by specifying id as the orderprop of the Multilink if you really need that. - If somebody specified a Link or Multilink as orderprop, we sort by labelprop of that class -- not transitively by orderprop. I've resited the tempation to implement recursive orderprop here: There could even be loops if several classes specify a Link or Multilink as the orderprop... - Fixed a bug in Metakit-Backend: When sorting by Links, the backend would do a natural join to the Link class. It would rename the "id" attribute before joining but *not* all the other attributes of the joined class. So in one test-case we had a name-clash with priority.name and status.name when sorting *and* grouping by these attributes. Depending on the order of joining this would produce a name-clash with broken sort-results (and broken display if the original class has an attribute that clashes). I'm now doing the sorting of Links in the generic filter method for the metakit backend. I've left the dead code in the metakit-backend since correctly implementing this in the backend will probably be more efficient. - updated doc/design.html with the new docstring of filter.
author Ralf Schlatterbeck <schlatterbeck@users.sourceforge.net>
date Mon, 21 Aug 2006 12:19:48 +0000
parents 53987aa153d2
children 0dd05c9e5fff
line wrap: on
line source

from __future__ import nested_scopes

import unittest
from cgi import FieldStorage, MiniFieldStorage

from roundup import hyperdb
from roundup.date import Date, Interval
from roundup.cgi.actions import *
from roundup.cgi.exceptions import Redirect, Unauthorised, SeriousError

from mocknull import MockNull

def true(*args, **kwargs):
    return 1

class ActionTestCase(unittest.TestCase):
    def setUp(self):
        self.form = FieldStorage()
        self.client = MockNull()
        self.client.form = self.form
        class TemplatingUtils:
            pass
        self.client.instance.interfaces.TemplatingUtils = TemplatingUtils

class ShowActionTestCase(ActionTestCase):
    def assertRaisesMessage(self, exception, callable, message, *args,
                            **kwargs):
        """An extension of assertRaises, which also checks the exception
        message. We need this because we rely on exception messages when
        redirecting.
        """
        try:
            callable(*args, **kwargs)
        except exception, msg:
            self.assertEqual(str(msg), message)
        else:
            if hasattr(exception, '__name__'):
                excName = exception.__name__
            else:
                excName = str(exception)
            raise self.failureException, excName

    def testShowAction(self):
        self.client.base = 'BASE/'

        action = ShowAction(self.client)
        self.assertRaises(ValueError, action.handle)

        self.form.value.append(MiniFieldStorage('@type', 'issue'))
        self.assertRaises(SeriousError, action.handle)

        self.form.value.append(MiniFieldStorage('@number', '1'))
        self.assertRaisesMessage(Redirect, action.handle, 'BASE/issue1')

    def testShowActionNoType(self):
        action = ShowAction(self.client)
        self.assertRaises(ValueError, action.handle)
        self.form.value.append(MiniFieldStorage('@number', '1'))
        self.assertRaisesMessage(ValueError, action.handle,
            'No type specified')

class RetireActionTestCase(ActionTestCase):
    def testRetireAction(self):
        self.client.db.security.hasPermission = true
        self.client.ok_message = []
        RetireAction(self.client).handle()
        self.assert_(len(self.client.ok_message) == 1)

    def testNoPermission(self):
        self.assertRaises(Unauthorised, RetireAction(self.client).execute)

    def testDontRetireAdminOrAnonymous(self):
        self.client.db.security.hasPermission=true
        # look up the user class
        self.client.classname = 'user'
        # but always look up admin, regardless of nodeid
        self.client.db.user.get = lambda a,b: 'admin'
        self.assertRaises(ValueError, RetireAction(self.client).handle)
        # .. or anonymous
        self.client.db.user.get = lambda a,b: 'anonymous'
        self.assertRaises(ValueError, RetireAction(self.client).handle)

class SearchActionTestCase(ActionTestCase):
    def setUp(self):
        ActionTestCase.setUp(self)
        self.action = SearchAction(self.client)

class StandardSearchActionTestCase(SearchActionTestCase):
    def testNoPermission(self):
        self.assertRaises(Unauthorised, self.action.execute)

    def testQueryName(self):
        self.assertEqual(self.action.getQueryName(), '')

        self.form.value.append(MiniFieldStorage('@queryname', 'foo'))
        self.assertEqual(self.action.getQueryName(), 'foo')

class FakeFilterVarsTestCase(SearchActionTestCase):
    def setUp(self):
        SearchActionTestCase.setUp(self)
        self.client.db.classes.get_transitive_prop = lambda x: \
            hyperdb.Multilink('foo')

    def assertFilterEquals(self, expected):
        self.action.fakeFilterVars()
        self.assertEqual(self.form.getvalue('@filter'), expected)

    def testEmptyMultilink(self):
        self.form.value.append(MiniFieldStorage('foo', ''))
        self.form.value.append(MiniFieldStorage('foo', ''))

        self.assertFilterEquals(None)

    def testNonEmptyMultilink(self):
        self.form.value.append(MiniFieldStorage('foo', ''))
        self.form.value.append(MiniFieldStorage('foo', '1'))

        self.assertFilterEquals('foo')

    def testEmptyKey(self):
        self.form.value.append(MiniFieldStorage('foo', ''))
        self.assertFilterEquals(None)

    def testStandardKey(self):
        self.form.value.append(MiniFieldStorage('foo', '1'))
        self.assertFilterEquals('foo')

    def testStringKey(self):
        self.client.db.classes.getprops = lambda: {'foo': hyperdb.String()}
        self.form.value.append(MiniFieldStorage('foo', 'hello'))
        self.assertFilterEquals('foo')

    def testTokenizedStringKey(self):
        self.client.db.classes.get_transitive_prop = lambda x: hyperdb.String()
        self.form.value.append(MiniFieldStorage('foo', 'hello world'))

        self.assertFilterEquals('foo')

        # The single value gets replaced with the tokenized list.
        self.assertEqual([x.value for x in self.form['foo']],
            ['hello', 'world'])

class CollisionDetectionTestCase(ActionTestCase):
    def setUp(self):
        ActionTestCase.setUp(self)
        self.action = EditItemAction(self.client)
        self.now = Date('.')
        # round off for testing
        self.now.second = int(self.now.second)

    def testLastUserActivity(self):
        self.assertEqual(self.action.lastUserActivity(), None)

        self.client.form.value.append(
            MiniFieldStorage('@lastactivity', str(self.now)))
        self.assertEqual(self.action.lastUserActivity(), self.now)

    def testLastNodeActivity(self):
        self.action.classname = 'issue'
        self.action.nodeid = '1'

        def get(nodeid, propname):
            self.assertEqual(nodeid, '1')
            self.assertEqual(propname, 'activity')
            return self.now
        self.client.db.issue.get = get

        self.assertEqual(self.action.lastNodeActivity(), self.now)

    def testCollision(self):
        # fake up an actual change
        self.action.classname = 'test'
        self.action.nodeid = '1'
        self.client.parsePropsFromForm = lambda: ({('test','1'):{1:1}}, [])
        self.failUnless(self.action.detectCollision(self.now,
            self.now + Interval("1d")))
        self.failIf(self.action.detectCollision(self.now,
            self.now - Interval("1d")))
        self.failIf(self.action.detectCollision(None, self.now))

class LoginTestCase(ActionTestCase):
    def setUp(self):
        ActionTestCase.setUp(self)
        self.client.error_message = []

        # set the db password to 'right'
        self.client.db.user.get = lambda a,b: 'right'

        # unless explicitly overridden, we should never get here
        self.client.opendb = lambda a: self.fail(
            "Logged in, but we shouldn't be.")

    def assertLoginLeavesMessages(self, messages, username=None, password=None):
        if username is not None:
            self.form.value.append(MiniFieldStorage('__login_name', username))
        if password is not None:
            self.form.value.append(
                MiniFieldStorage('__login_password', password))

        LoginAction(self.client).handle()
        self.assertEqual(self.client.error_message, messages)

    def testNoUsername(self):
        self.assertLoginLeavesMessages(['Username required'])

    def testInvalidUsername(self):
        def raiseKeyError(a):
            raise KeyError
        self.client.db.user.lookup = raiseKeyError
        self.assertLoginLeavesMessages(['Invalid login'], 'foo')

    def testInvalidPassword(self):
        self.assertLoginLeavesMessages(['Invalid login'], 'foo', 'wrong')

    def testNoWebAccess(self):
        self.assertLoginLeavesMessages(['You do not have permission to login'],
                                        'foo', 'right')

    def testCorrectLogin(self):
        self.client.db.security.hasPermission = lambda *args, **kwargs: True

        def opendb(username):
            self.assertEqual(username, 'foo')
        self.client.opendb = opendb

        self.assertLoginLeavesMessages([], 'foo', 'right')

def test_suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(RetireActionTestCase))
    suite.addTest(unittest.makeSuite(StandardSearchActionTestCase))
    suite.addTest(unittest.makeSuite(FakeFilterVarsTestCase))
    suite.addTest(unittest.makeSuite(ShowActionTestCase))
    suite.addTest(unittest.makeSuite(CollisionDetectionTestCase))
    suite.addTest(unittest.makeSuite(LoginTestCase))
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    unittest.main(testRunner=runner)

# vim: set et sts=4 sw=4 :

Roundup Issue Tracker: http://roundup-tracker.org/