Exemple #1
0
    def setUp(self):
        self.env = EnvironmentStub(default_data=True,
                                   enable=['trac.*', 'tracvote.*'])
        self.env.path = tempfile.mkdtemp()
        self.perm = PermissionSystem(self.env)
        self.req = Mock()

        self.db = self.env.get_db_cnx()
        self.votes = VoteSystem(self.env)
        # Current tracvotes schema is setup with enabled component anyway.
        #   Revert these changes for getting default permissions inserted.
        self._revert_schema_init()
        self.votes.upgrade_environment(self.db)
Exemple #2
0
class VoteSystemTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(default_data=True,
                                   enable=['trac.*', 'tracvote.*'])
        self.env.path = tempfile.mkdtemp()
        self.perm = PermissionSystem(self.env)
        self.req = Mock()

        self.db = self.env.get_db_cnx()
        self.votes = VoteSystem(self.env)
        # Current tracvotes schema is setup with enabled component anyway.
        #   Revert these changes for getting default permissions inserted.
        self._revert_schema_init()
        self.votes.upgrade_environment(self.db)

    def tearDown(self):
        self.db.close()
        # Really close db connections.
        self.env.shutdown()
        shutil.rmtree(self.env.path)

    # Helpers

    def _revert_schema_init(self):
        cursor = self.db.cursor()
        cursor.execute("DROP TABLE IF EXISTS votes")
        cursor.execute("DELETE FROM system WHERE name='vote_version'")
        cursor.execute("DELETE FROM permission WHERE action %s"
                       % self.db.like(), ('VOTE_%',))

    # Tests

    def test_available_actions_no_perms(self):
        self.assertTrue(_ACTIONS['view'] in PermissionCache(self.env))
        self.assertFalse(_ACTIONS['modify'] in PermissionCache(self.env))

    def test_available_actions_full_perms(self):
        perm_map = dict(voter='VOTE_MODIFY', admin='TRAC_ADMIN')
        for user in perm_map:
            self.perm.grant_permission(user, perm_map[user])
            for action in _ACTIONS.values():
                self.assertTrue(action in PermissionCache(self.env,
                                                          username=user))

    def test_resource_provider(self):
        self.assertTrue(self.votes in Chrome(self.env).template_providers)
Exemple #3
0
class VoteSystemTestCase(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentStub(default_data=True,
                                   enable=['trac.*', 'tracvote.*'])
        self.env.path = tempfile.mkdtemp()
        self.perm = PermissionSystem(self.env)
        self.req = Mock()

        self.db = self.env.get_db_cnx()
        self.votes = VoteSystem(self.env)
        # Current tracvotes schema is setup with enabled component anyway.
        #   Revert these changes for getting default permissions inserted.
        self._revert_schema_init()
        self.votes.upgrade_environment(self.db)

    def tearDown(self):
        self.db.close()
        # Really close db connections.
        self.env.shutdown()
        shutil.rmtree(self.env.path)

    # Helpers

    def _revert_schema_init(self):
        cursor = self.db.cursor()
        cursor.execute("DROP TABLE IF EXISTS votes")
        cursor.execute("DELETE FROM system WHERE name='vote_version'")
        cursor.execute(
            "DELETE FROM permission WHERE action %s" % self.db.like(),
            ('VOTE_%', ))

    # Tests

    def test_available_actions_no_perms(self):
        self.assertTrue(_ACTIONS['view'] in PermissionCache(self.env))
        self.assertFalse(_ACTIONS['modify'] in PermissionCache(self.env))

    def test_available_actions_full_perms(self):
        perm_map = dict(voter='VOTE_MODIFY', admin='TRAC_ADMIN')
        for user in perm_map:
            self.perm.grant_permission(user, perm_map[user])
            for action in _ACTIONS.values():
                self.assertTrue(
                    action in PermissionCache(self.env, username=user))

    def test_resource_provider(self):
        self.assertTrue(self.votes in Chrome(self.env).template_providers)
Exemple #4
0
    def setUp(self):
        self.env = EnvironmentStub(default_data=True,
                                   enable=['trac.*', 'tracvote.*'])
        self.env.path = tempfile.mkdtemp()
        self.perm = PermissionSystem(self.env)
        self.req = Mock()

        self.db = self.env.get_db_cnx()
        self.votes = VoteSystem(self.env)
        # Current tracvotes schema is setup with enabled component anyway.
        #   Revert these changes for getting default permissions inserted.
        self._revert_schema_init()
        self.votes.upgrade_environment(self.db)
Exemple #5
0
 def setUp(self):
     self.env = EnvironmentStub(enable=['trac.*'])
     self.env.path = tempfile.mkdtemp()
     self.db_mgr = DatabaseManager(self.env)
     self.db = self.env.get_db_cnx()
     self.votes = VoteSystem(self.env)
Exemple #6
0
class EnvironmentSetupTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(enable=['trac.*'])
        self.env.path = tempfile.mkdtemp()
        self.db_mgr = DatabaseManager(self.env)
        self.db = self.env.get_db_cnx()
        self.votes = VoteSystem(self.env)

    def tearDown(self):
        self.db.close()
        # Really close db connections.
        self.env.shutdown()
        shutil.rmtree(self.env.path)

    # Helpers

    def _schema_init(self, schema=None):
        cursor = self.db.cursor()
        cursor.execute("DROP TABLE IF EXISTS votes")
        if schema:
            connector = self.db_mgr._get_connector()[0]
            for table in schema:
                for stmt in connector.to_sql(table):
                    cursor.execute(stmt)

    def _verify_curr_schema(self):
        self.assertFalse(self.votes.environment_needs_upgrade(self.db))
        cursor = self.db.cursor()
        cursor.execute('SELECT * FROM votes')
        cols = get_column_names(cursor)
        self.assertTrue('resource' not in cols)
        self.assertEquals(['realm', 'resource_id', 'version', 'username',
                           'vote', 'time', 'changetime'], cols)
        cursor.execute("""
            SELECT value
              FROM system
             WHERE name='vote_version'
        """)
        schema_ver = int(cursor.fetchone()[0])
        self.assertEquals(self.votes.schema_version, schema_ver)

    def _verify_schema_unregistered(self):
        cursor = self.db.cursor()
        cursor.execute("""
            SELECT value
              FROM system
             WHERE name='vote_version'
        """)
        self.assertFalse(cursor.fetchone())

    # Tests

    def test_new_install(self):
        # Current tracvotes schema is setup with enabled component anyway.
        #   Revert these changes for clean install testing.
        self._schema_init()

        self.assertEquals(0, self.votes.get_schema_version(self.db))
        self.assertTrue(self.votes.environment_needs_upgrade(self.db))

        self.votes.upgrade_environment(self.db)
        self._verify_curr_schema()

    def test_upgrade_v1_to_current(self):
        # The initial db schema from r2963 - 02-Jan-2008 by Alec Thomas.
        schema = [
            Table('votes', key=('resource', 'username', 'vote'))[
                Column('resource'),
                Column('username'),
                Column('vote', 'int'),
                ]
            ]
        self._schema_init(schema)

        # Populate tables with test data.
        cursor = self.db.cursor()
        cursor.executemany("""
            INSERT INTO votes
                   (resource,username,vote)
            VALUES (%s,%s,%s)
        """, (('ticket/1','user',-1), ('ticket/2','user',1),
              ('wiki/DeletedPage','user',-1), ('wiki/ExistingPage','user',1)))
        # Resources must exist for successful data migration.
        t = Ticket(self.env, db=self.db)
        t['summary'] = 'test ticket'
        t.insert()
        w = WikiPage(self.env, 'ExistingPage')
        w.text = 'content'
        w.save('author', 'comment', '::1')
        self._verify_schema_unregistered()
        self.assertEquals(1, self.votes.get_schema_version(self.db))
        self.assertTrue(self.votes.environment_needs_upgrade(self.db))

        # Data migration and registration of unversioned schema.
        self.votes.upgrade_environment(self.db)
        self._verify_curr_schema()

        cursor.execute('SELECT * FROM votes')
        votes = cursor.fetchall()
        t_votes = [id for realm,id,ver,u,v,t,c in votes if realm == 'ticket']
        w_votes = [id for realm,id,ver,u,v,t,c in votes if realm == 'wiki']
        self.assertTrue('1' in t_votes)
        if resource_check:
            self.assertFalse('2' in t_votes)
            self.assertFalse('DeletedPage' in w_votes)
        self.assertTrue('ExistingPage' in w_votes)
Exemple #7
0
    def fetch_hacks(self, req, data, types, releases):
        """Return a list of hacks in the form

        [votes, rank, resource, tags, title]
        """
        tag_system = TagSystem(self.env)
        vote_system = VoteSystem(self.env)

        query = 'realm:wiki (%s) (%s)' % \
                (' or '.join(releases), ' or '.join(types))
        self.env.log.debug(query)
        tagged = tag_system.query(req, query)

        # Limit
        try:
            limit = int(req.args.get('limit', self.limit))
            data['limit_message'] = 'top %s' % limit
        except ValueError:
            data['limit_message'] = 'all'
            limit = 9999
        data['limit'] = limit

        # Query
        q = req.args.get('q', '')
        data['query'] = q
        query = Query(q.lower())

        # Build hacks list
        hacks = []
        for resource, tags in tagged:
            page = WikiPage(self.env, resource.id)
            if q:
                text = page.name.lower() + page.text.lower() + ' '.join(tags)
                if not query(text):
                    continue
            _, count, _ = vote_system.get_vote_counts(resource)
            match = self.title_extract.search(page.text)
            count_string = pluralise(count, 'vote')
            if match:
                title = '%s (%s)' % (match.group(1).strip(), count_string)
            else:
                title = '%s' % count_string
            hacks.append([count, None, resource, tags, title])

        # Rank
        total_hack_count = len(hacks)
        hacks = sorted(hacks, key=lambda i: -i[0])
        remainder = hacks[limit:]
        hacks = hacks[:limit] + random.sample(remainder,
                                              min(limit, len(remainder)))

        # Navigation
        #if len(hacks) >= limit:
        #    add_ctxtnav(req, builder.a('More', href='?action=more'))
        #    limit = len(hacks)
        #    data['limit'] = data['limit_message'] = limit
        #else:
        #    add_ctxtnav(req, 'More')
        #if q or limit != self.limit:
        #    add_ctxtnav(req, builder.a('Default', href='?action=default'))
        #else:
        #    add_ctxtnav(req, 'Default')
        #if total_hack_count > limit:
        #    add_ctxtnav(req, builder.a('All', href='?action=all'))
        #else:
        #    add_ctxtnav(req, 'All')
        #if limit > 10:
        #    limit = min(limit, len(hacks))
        #    add_ctxtnav(req, builder.a('Less', href='?action=less'))
        #else:
        #    add_ctxtnav(req, 'Less')
        #for i, hack in enumerate(hacks):
        #    hack[1] = i
        return hacks
Exemple #8
0
 def setUp(self):
     self.env = EnvironmentStub(enable=['trac.*'])
     self.env.path = tempfile.mkdtemp()
     self.db_mgr = DatabaseManager(self.env)
     self.db = self.env.get_db_cnx()
     self.votes = VoteSystem(self.env)
Exemple #9
0
class EnvironmentSetupTestCase(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentStub(enable=['trac.*'])
        self.env.path = tempfile.mkdtemp()
        self.db_mgr = DatabaseManager(self.env)
        self.db = self.env.get_db_cnx()
        self.votes = VoteSystem(self.env)

    def tearDown(self):
        self.db.close()
        # Really close db connections.
        self.env.shutdown()
        shutil.rmtree(self.env.path)

    # Helpers

    def _schema_init(self, schema=None):
        cursor = self.db.cursor()
        cursor.execute("DROP TABLE IF EXISTS votes")
        if schema:
            connector = self.db_mgr._get_connector()[0]
            for table in schema:
                for stmt in connector.to_sql(table):
                    cursor.execute(stmt)

    def _verify_curr_schema(self):
        self.assertFalse(self.votes.environment_needs_upgrade(self.db))
        cursor = self.db.cursor()
        cursor.execute('SELECT * FROM votes')
        cols = get_column_names(cursor)
        self.assertTrue('resource' not in cols)
        self.assertEquals([
            'realm', 'resource_id', 'version', 'username', 'vote', 'time',
            'changetime'
        ], cols)
        cursor.execute("""
            SELECT value
              FROM system
             WHERE name='vote_version'
        """)
        schema_ver = int(cursor.fetchone()[0])
        self.assertEquals(self.votes.schema_version, schema_ver)

    def _verify_schema_unregistered(self):
        cursor = self.db.cursor()
        cursor.execute("""
            SELECT value
              FROM system
             WHERE name='vote_version'
        """)
        self.assertFalse(cursor.fetchone())

    # Tests

    def test_new_install(self):
        # Current tracvotes schema is setup with enabled component anyway.
        #   Revert these changes for clean install testing.
        self._schema_init()

        self.assertEquals(0, self.votes.get_schema_version(self.db))
        self.assertTrue(self.votes.environment_needs_upgrade(self.db))

        self.votes.upgrade_environment(self.db)
        self._verify_curr_schema()

    def test_upgrade_v1_to_current(self):
        # The initial db schema from r2963 - 02-Jan-2008 by Alec Thomas.
        schema = [
            Table('votes', key=('resource', 'username',
                                'vote'))[Column('resource'),
                                         Column('username'),
                                         Column('vote', 'int'), ]
        ]
        self._schema_init(schema)

        # Populate tables with test data.
        cursor = self.db.cursor()
        cursor.executemany(
            """
            INSERT INTO votes
                   (resource,username,vote)
            VALUES (%s,%s,%s)
        """, (('ticket/1', 'user', -1), ('ticket/2', 'user', 1),
              ('wiki/DeletedPage', 'user', -1),
              ('wiki/ExistingPage', 'user', 1)))
        # Resources must exist for successful data migration.
        t = Ticket(self.env, db=self.db)
        t['summary'] = 'test ticket'
        t.insert()
        w = WikiPage(self.env, 'ExistingPage')
        w.text = 'content'
        w.save('author', 'comment', '::1')
        self._verify_schema_unregistered()
        self.assertEquals(1, self.votes.get_schema_version(self.db))
        self.assertTrue(self.votes.environment_needs_upgrade(self.db))

        # Data migration and registration of unversioned schema.
        self.votes.upgrade_environment(self.db)
        self._verify_curr_schema()

        cursor.execute('SELECT * FROM votes')
        votes = cursor.fetchall()
        t_votes = [
            id for realm, id, ver, u, v, t, c in votes if realm == 'ticket'
        ]
        w_votes = [
            id for realm, id, ver, u, v, t, c in votes if realm == 'wiki'
        ]
        self.assertTrue('1' in t_votes)
        if resource_check:
            self.assertFalse('2' in t_votes)
            self.assertFalse('DeletedPage' in w_votes)
        self.assertTrue('ExistingPage' in w_votes)
Exemple #10
0
 def style(self, ticket, req, **style):
     votesystem = VoteSystem(self.env)
     votes = votesystem.get_vote_counts('ticket/%s' % ticket.id)[1]
     max_votes = votesystem.get_max_votes('ticket')
     size = self.marker_radius(votes, max_votes)
     return { 'pointRadius': str(int(size)) }