Hi,
Just added the bare basics of a multi product plugin - the schema, table
generation and so on. Still requires installation instructions. I will
also add an admin panel based very strongly on the trac template soon
(though I wouldn't mind knowing if those commits need to have an
appropriate mention of such lineage).
Quick note: this is intended to be equivalent to providing the multi
project feature but with a slight change in nomenclature.
Cheers,
Gary
On 02/10/2012 01:18 PM, gjm@apache.org wrote:
> Author: gjm
> Date: Fri Feb 10 13:18:16 2012
> New Revision: 1242755
>
> URL: http://svn.apache.org/viewvc?rev=1242755&view=rev
> Log:
> multiproduct: db tables for product and product resource mapping tables and some limited
unittesting
>
> Added:
> incubator/bloodhound/trunk/bloodhound_multiproduct/
> incubator/bloodhound/trunk/bloodhound_multiproduct/LICENSE (with props)
> incubator/bloodhound/trunk/bloodhound_multiproduct/NOTICE (with props)
> incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/
> incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/__init__.py (with
props)
> incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/model.py (with
props)
> incubator/bloodhound/trunk/bloodhound_multiproduct/setup.py (with props)
> incubator/bloodhound/trunk/bloodhound_multiproduct/tests/
> incubator/bloodhound/trunk/bloodhound_multiproduct/tests/__init__.py (with props)
> incubator/bloodhound/trunk/bloodhound_multiproduct/tests/model.py (with props)
>
> Added: incubator/bloodhound/trunk/bloodhound_multiproduct/LICENSE
> URL: http://svn.apache.org/viewvc/incubator/bloodhound/trunk/bloodhound_multiproduct/LICENSE?rev=1242755&view=auto
> ==============================================================================
> --- incubator/bloodhound/trunk/bloodhound_multiproduct/LICENSE (added)
> +++ incubator/bloodhound/trunk/bloodhound_multiproduct/LICENSE Fri Feb 10 13:18:16 2012
> @@ -0,0 +1,202 @@
> +
> + Apache License
> + Version 2.0, January 2004
> + http://www.apache.org/licenses/
> +
> + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
> +
> + 1. Definitions.
> +
> + "License" shall mean the terms and conditions for use, reproduction,
> + and distribution as defined by Sections 1 through 9 of this document.
> +
> + "Licensor" shall mean the copyright owner or entity authorized by
> + the copyright owner that is granting the License.
> +
> + "Legal Entity" shall mean the union of the acting entity and all
> + other entities that control, are controlled by, or are under common
> + control with that entity. For the purposes of this definition,
> + "control" means (i) the power, direct or indirect, to cause the
> + direction or management of such entity, whether by contract or
> + otherwise, or (ii) ownership of fifty percent (50%) or more of the
> + outstanding shares, or (iii) beneficial ownership of such entity.
> +
> + "You" (or "Your") shall mean an individual or Legal Entity
> + exercising permissions granted by this License.
> +
> + "Source" form shall mean the preferred form for making modifications,
> + including but not limited to software source code, documentation
> + source, and configuration files.
> +
> + "Object" form shall mean any form resulting from mechanical
> + transformation or translation of a Source form, including but
> + not limited to compiled object code, generated documentation,
> + and conversions to other media types.
> +
> + "Work" shall mean the work of authorship, whether in Source or
> + Object form, made available under the License, as indicated by a
> + copyright notice that is included in or attached to the work
> + (an example is provided in the Appendix below).
> +
> + "Derivative Works" shall mean any work, whether in Source or Object
> + form, that is based on (or derived from) the Work and for which the
> + editorial revisions, annotations, elaborations, or other modifications
> + represent, as a whole, an original work of authorship. For the purposes
> + of this License, Derivative Works shall not include works that remain
> + separable from, or merely link (or bind by name) to the interfaces of,
> + the Work and Derivative Works thereof.
> +
> + "Contribution" shall mean any work of authorship, including
> + the original version of the Work and any modifications or additions
> + to that Work or Derivative Works thereof, that is intentionally
> + submitted to Licensor for inclusion in the Work by the copyright owner
> + or by an individual or Legal Entity authorized to submit on behalf of
> + the copyright owner. For the purposes of this definition, "submitted"
> + means any form of electronic, verbal, or written communication sent
> + to the Licensor or its representatives, including but not limited to
> + communication on electronic mailing lists, source code control systems,
> + and issue tracking systems that are managed by, or on behalf of, the
> + Licensor for the purpose of discussing and improving the Work, but
> + excluding communication that is conspicuously marked or otherwise
> + designated in writing by the copyright owner as "Not a Contribution."
> +
> + "Contributor" shall mean Licensor and any individual or Legal Entity
> + on behalf of whom a Contribution has been received by Licensor and
> + subsequently incorporated within the Work.
> +
> + 2. Grant of Copyright License. Subject to the terms and conditions of
> + this License, each Contributor hereby grants to You a perpetual,
> + worldwide, non-exclusive, no-charge, royalty-free, irrevocable
> + copyright license to reproduce, prepare Derivative Works of,
> + publicly display, publicly perform, sublicense, and distribute the
> + Work and such Derivative Works in Source or Object form.
> +
> + 3. Grant of Patent License. Subject to the terms and conditions of
> + this License, each Contributor hereby grants to You a perpetual,
> + worldwide, non-exclusive, no-charge, royalty-free, irrevocable
> + (except as stated in this section) patent license to make, have made,
> + use, offer to sell, sell, import, and otherwise transfer the Work,
> + where such license applies only to those patent claims licensable
> + by such Contributor that are necessarily infringed by their
> + Contribution(s) alone or by combination of their Contribution(s)
> + with the Work to which such Contribution(s) was submitted. If You
> + institute patent litigation against any entity (including a
> + cross-claim or counterclaim in a lawsuit) alleging that the Work
> + or a Contribution incorporated within the Work constitutes direct
> + or contributory patent infringement, then any patent licenses
> + granted to You under this License for that Work shall terminate
> + as of the date such litigation is filed.
> +
> + 4. Redistribution. You may reproduce and distribute copies of the
> + Work or Derivative Works thereof in any medium, with or without
> + modifications, and in Source or Object form, provided that You
> + meet the following conditions:
> +
> + (a) You must give any other recipients of the Work or
> + Derivative Works a copy of this License; and
> +
> + (b) You must cause any modified files to carry prominent notices
> + stating that You changed the files; and
> +
> + (c) You must retain, in the Source form of any Derivative Works
> + that You distribute, all copyright, patent, trademark, and
> + attribution notices from the Source form of the Work,
> + excluding those notices that do not pertain to any part of
> + the Derivative Works; and
> +
> + (d) If the Work includes a "NOTICE" text file as part of its
> + distribution, then any Derivative Works that You distribute must
> + include a readable copy of the attribution notices contained
> + within such NOTICE file, excluding those notices that do not
> + pertain to any part of the Derivative Works, in at least one
> + of the following places: within a NOTICE text file distributed
> + as part of the Derivative Works; within the Source form or
> + documentation, if provided along with the Derivative Works; or,
> + within a display generated by the Derivative Works, if and
> + wherever such third-party notices normally appear. The contents
> + of the NOTICE file are for informational purposes only and
> + do not modify the License. You may add Your own attribution
> + notices within Derivative Works that You distribute, alongside
> + or as an addendum to the NOTICE text from the Work, provided
> + that such additional attribution notices cannot be construed
> + as modifying the License.
> +
> + You may add Your own copyright statement to Your modifications and
> + may provide additional or different license terms and conditions
> + for use, reproduction, or distribution of Your modifications, or
> + for any such Derivative Works as a whole, provided Your use,
> + reproduction, and distribution of the Work otherwise complies with
> + the conditions stated in this License.
> +
> + 5. Submission of Contributions. Unless You explicitly state otherwise,
> + any Contribution intentionally submitted for inclusion in the Work
> + by You to the Licensor shall be under the terms and conditions of
> + this License, without any additional terms or conditions.
> + Notwithstanding the above, nothing herein shall supersede or modify
> + the terms of any separate license agreement you may have executed
> + with Licensor regarding such Contributions.
> +
> + 6. Trademarks. This License does not grant permission to use the trade
> + names, trademarks, service marks, or product names of the Licensor,
> + except as required for reasonable and customary use in describing the
> + origin of the Work and reproducing the content of the NOTICE file.
> +
> + 7. Disclaimer of Warranty. Unless required by applicable law or
> + agreed to in writing, Licensor provides the Work (and each
> + Contributor provides its Contributions) on an "AS IS" BASIS,
> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
> + implied, including, without limitation, any warranties or conditions
> + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
> + PARTICULAR PURPOSE. You are solely responsible for determining the
> + appropriateness of using or redistributing the Work and assume any
> + risks associated with Your exercise of permissions under this License.
> +
> + 8. Limitation of Liability. In no event and under no legal theory,
> + whether in tort (including negligence), contract, or otherwise,
> + unless required by applicable law (such as deliberate and grossly
> + negligent acts) or agreed to in writing, shall any Contributor be
> + liable to You for damages, including any direct, indirect, special,
> + incidental, or consequential damages of any character arising as a
> + result of this License or out of the use or inability to use the
> + Work (including but not limited to damages for loss of goodwill,
> + work stoppage, computer failure or malfunction, or any and all
> + other commercial damages or losses), even if such Contributor
> + has been advised of the possibility of such damages.
> +
> + 9. Accepting Warranty or Additional Liability. While redistributing
> + the Work or Derivative Works thereof, You may choose to offer,
> + and charge a fee for, acceptance of support, warranty, indemnity,
> + or other liability obligations and/or rights consistent with this
> + License. However, in accepting such obligations, You may act only
> + on Your own behalf and on Your sole responsibility, not on behalf
> + of any other Contributor, and only if You agree to indemnify,
> + defend, and hold each Contributor harmless for any liability
> + incurred by, or claims asserted against, such Contributor by reason
> + of your accepting any such warranty or additional liability.
> +
> + END OF TERMS AND CONDITIONS
> +
> + APPENDIX: How to apply the Apache License to your work.
> +
> + To apply the Apache License to your work, attach the following
> + boilerplate notice, with the fields enclosed by brackets "[]"
> + replaced with your own identifying information. (Don't include
> + the brackets!) The text should be enclosed in the appropriate
> + comment syntax for the file format. We also recommend that a
> + file or class name and description of purpose be included on the
> + same "printed page" as the copyright notice for easier
> + identification within third-party archives.
> +
> + Copyright [yyyy] [name of copyright owner]
> +
> + Licensed under the Apache License, Version 2.0 (the "License");
> + you may not use this file except in compliance with the License.
> + You may obtain a copy of the License at
> +
> + http://www.apache.org/licenses/LICENSE-2.0
> +
> + Unless required by applicable law or agreed to in writing, software
> + distributed under the License is distributed on an "AS IS" BASIS,
> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> + See the License for the specific language governing permissions and
> + limitations under the License.
>
> Propchange: incubator/bloodhound/trunk/bloodhound_multiproduct/LICENSE
> ------------------------------------------------------------------------------
> svn:eol-style = native
>
> Added: incubator/bloodhound/trunk/bloodhound_multiproduct/NOTICE
> URL: http://svn.apache.org/viewvc/incubator/bloodhound/trunk/bloodhound_multiproduct/NOTICE?rev=1242755&view=auto
> ==============================================================================
> --- incubator/bloodhound/trunk/bloodhound_multiproduct/NOTICE (added)
> +++ incubator/bloodhound/trunk/bloodhound_multiproduct/NOTICE Fri Feb 10 13:18:16 2012
> @@ -0,0 +1,6 @@
> +Apache Bloodhound
> +Copyright 2012 The Apache Software Foundation
> +
> +This product includes software developed at
> +The Apache Software Foundation (http://www.apache.org/)
> +
>
> Propchange: incubator/bloodhound/trunk/bloodhound_multiproduct/NOTICE
> ------------------------------------------------------------------------------
> svn:eol-style = native
>
> Added: incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/__init__.py
> URL: http://svn.apache.org/viewvc/incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/__init__.py?rev=1242755&view=auto
> ==============================================================================
> --- incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/__init__.py (added)
> +++ incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/__init__.py Fri Feb
10 13:18:16 2012
> @@ -0,0 +1,21 @@
> +
> +# Licensed to the Apache Software Foundation (ASF) under one
> +# or more contributor license agreements. See the NOTICE file
> +# distributed with this work for additional information
> +# regarding copyright ownership. The ASF licenses this file
> +# to you under the Apache License, Version 2.0 (the
> +# "License"); you may not use this file except in compliance
> +# with the License. You may obtain a copy of the License at
> +#
> +# http://www.apache.org/licenses/LICENSE-2.0
> +#
> +# Unless required by applicable law or agreed to in writing,
> +# software distributed under the License is distributed on an
> +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
> +# KIND, either express or implied. See the License for the
> +# specific language governing permissions and limitations
> +# under the License.
> +
> +"""multiproduct module"""
> +from model import MultiProductEnvironmentProvider
> +
>
> Propchange: incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/__init__.py
> ------------------------------------------------------------------------------
> svn:eol-style = native
>
> Added: incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/model.py
> URL: http://svn.apache.org/viewvc/incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/model.py?rev=1242755&view=auto
> ==============================================================================
> --- incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/model.py (added)
> +++ incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/model.py Fri Feb
10 13:18:16 2012
> @@ -0,0 +1,298 @@
> +
> +# Licensed to the Apache Software Foundation (ASF) under one
> +# or more contributor license agreements. See the NOTICE file
> +# distributed with this work for additional information
> +# regarding copyright ownership. The ASF licenses this file
> +# to you under the Apache License, Version 2.0 (the
> +# "License"); you may not use this file except in compliance
> +# with the License. You may obtain a copy of the License at
> +#
> +# http://www.apache.org/licenses/LICENSE-2.0
> +#
> +# Unless required by applicable law or agreed to in writing,
> +# software distributed under the License is distributed on an
> +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
> +# KIND, either express or implied. See the License for the
> +# specific language governing permissions and limitations
> +# under the License.
> +
> +"""Models to support multi-product"""
> +from trac.core import Component, TracError, implements
> +from trac.resource import ResourceNotFound
> +from trac.db import Table, Column, DatabaseManager
> +from trac.env import IEnvironmentSetupParticipant
> +
> +DB_VERSION = 1
> +DB_SYSTEM_KEY = 'bloodhound_multi_product_version'
> +PLUGIN_NAME = 'Bloodhound multi product'
> +class ModelBase(object):
> + """Base class for the models to factor out common features
> + Derived classes should provide a meta dictionary to describe the table like:
> +
> + _meta = {'table_name':'mytable',
> + 'object_name':'WhatIWillCallMyselfInMessages',
> + 'key_fields':['id','id2'],
> + 'non_key_fields':['thing','anotherthing'],
> + }
> + """
> +
> + def __init__(self, env, keys=None):
> + """Initialisation requires an environment to be specified.
> + If keys are provided, the Model will initialise from the database
> + """
> + # make this impossible to instantiate without telling the class details
> + # about itself in the self.meta dictionary
> + self._old_data = {}
> + self._data = {}
> + self._exists = False
> + self._env = env
> + self._all_fields = self._meta['key_fields'] + self._meta['non_key_fields']
> + if keys is not None:
> + self._get_row(keys)
> + else:
> + self._update_from_row(None)
> +
> + def __getattr__(self, name):
> + """Overridden to allow table.field style field access."""
> + try:
> + if name in self._all_fields:
> + return self._data[name]
> + except KeyError:
> + raise AttributeError(name)
> + raise AttributeError(name)
> +
> + def __setattr__(self, name, value):
> + """Overridden to allow table.field = value style field setting."""
> + data = self.__dict__.get('data')
> + fields = self.__dict__.get('fields')
> +
> + if data and fields and name in fields:
> + self._data[name] = value
> + else:
> + dict.__setattr__(self, name, value)
> +
> +
> + def _update_from_row(self, row = None):
> + """uses a provided database row to update the model"""
> + fields = self._meta['key_fields']+self._meta['non_key_fields']
> + self._exists = row is not None
> + if row is None:
> + row = [None]*len(fields)
> + self._data = dict([(fields[i], row[i]) for i in range(len(row))])
> + self._old_data = {}
> + self._old_data.update(self._data)
> +
> + def _get_row(self, keys):
> + """queries the database and stores the result in the model"""
> + row = None
> + key_fields = self._meta['key_fields']
> + where = ','.join(['%s="%s"' % (k, keys[k]) for k in key_fields])
> + fields = ','.join(self._meta['key_fields']+self._meta['non_key_fields'])
> + sdata = {'fields':fields,
> + 'where':where}
> + sdata.update(self._meta)
> +
> + sql = """SELECT %(fields)s FROM %(table_name)s
> + WHERE %(where)s""" % sdata
> + with self._env.db_query as db:
> + for row in db(sql):
> + self._update_from_row(row)
> + break
> + else:
> + raise ResourceNotFound('No %(object_name)s with %(where)s' %
> + sdata)
> +
> + def delete(self):
> + """Deletes the matching record from the database"""
> + if not self._exists:
> + raise TracError('%(object_name)s does not exist' % self._meta)
> + sdata = {'where':','.join(['%s="%s"' % (k, self._data[k])
> + for k in self._meta['key_fields']])}
> + sdata.update(self._meta)
> + sql = """DELETE FROM %(table_name)s
> + WHERE %(where)s""" % sdata
> + with self._env.db_transaction as db:
> + db(sql)
> + self._exists = False
> + self._data = dict([(k, None) for k in self._data.keys()])
> + self._old_data.update(self._data)
> +
> + def insert(self):
> + """Create new record in the database"""
> + if self._exists or len(self.select(self._env,
> + dict([(k,self._data[k])
> + for k in self._meta['key_fields']]))):
> + sdata = {'keys':','.join(['%s="%s"' % (k, self._data[k])
> + for k in self._meta['key_fields']])}
> + sdata.update(self._meta)
> + raise TracError('%(object_name)s %(keys)s already exists' %
> + sdata)
> +
> + for key in self._meta['key_fields']:
> + if not self._data[key]:
> + sdata = {'key':key}
> + sdata.update(self._meta)
> + raise TracError('%(key)s required for %(object_name)s' %
> + sdata)
> + fields = self._meta['key_fields']+self._meta['non_key_fields']
> + sdata = {'fields':','.join(fields),
> + 'values':','.join(['"%s"' % self._data[f] for f in fields])}
> + sdata.update(self._meta)
> +
> + sql = """INSERT INTO %(table_name)s (%(fields)s)
> + VALUES (%(values)s)""" % sdata
> + with self._env.db_transaction as db:
> + db(sql)
> + self._exists = True
> + self._old_data.update(self._data)
> +
> + def update(self):
> + """Update the matching record in the database"""
> + if not self._exists:
> + raise TracError('%(object_name)s does not exist' % self._meta)
> + for key in self._meta['key_fields']:
> + if self._data[key] != self._old_data[key]:
> + raise TracError('%s cannot be changed' % key)
> +
> + sdata = {'where':','.join(['%s="%s"' % (k, self._data[k])
> + for k in self._meta['key_fields']]),
> + 'values':','.join(['%s="%s"' % (k, self._data[k])
> + for k in self._meta['non_key_fields']])}
> + sdata.update(self._meta)
> + sql = """UPDATE %(table_name)s SET %(values)s
> + WHERE %(where)s""" % sdata
> + with self._env.db_transaction as db:
> + db(sql)
> + self._old_data.update(self._data)
> +
> + @classmethod
> + def select(cls, env, where=None):
> + """Query the database to get a set of records back"""
> + rows = []
> + fields = cls._meta['key_fields']+cls._meta['non_key_fields']
> +
> + sdata = {'fields':','.join(fields),}
> + sdata.update(cls._meta)
> + sql = 'SELECT %(fields)s FROM %(table_name)s' % sdata
> + wherestr = ''
> + if where is not None:
> + wherestr = ' WHERE ' + ','.join(['%s="%s"' % (k, v)
> + for k, v in where.iteritems()])
> + for row in env.db_query(sql+wherestr):
> + # we won't know which class we need until called
> + model = cls.__new__(cls)
> + data = dict([(fields[i], row[i]) for i in range(len(fields))])
> + model.__init__(env, data)
> + rows.append(model)
> + return rows
> +
> +class Product(ModelBase):
> + """The Product table"""
> + _meta = {'table_name':'bloodhound_product',
> + 'object_name':'Product',
> + 'key_fields':['prefix',],
> + 'non_key_fields':['name', 'description', 'owner'],
> + }
> +
> + def delete(self, resources_to=None):
> + """ override the delete method so that we can move references to this
> + object to a new product """
> + if resources_to is not None:
> + new_product = Product(self._env, resources_to)
> + if not new_product._exists:
> + sdata = {'new_table':resources_to}
> + sdata.update(self._meta)
> + raise TracError('%(object_name)s %(new_table)s does not exist' %
> + sdata)
> + super(Product, self).delete()
> + #find and update all resources that should move
> + where = {'product_id':self._data['prefix']}
> + for prm in ProductResourceMap.select(self._env, where=where):
> + prm._data['product_id'] = resources_to
> + prm.update()
> +
> +
> +class ProductResourceMap(ModelBase):
> + """Table representing the mapping of resources to their product"""
> + _meta = {'table_name':'bloodhound_productresourcemap',
> + 'object_name':'ProductResourceMapping',
> + 'key_fields':['id',],
> + 'non_key_fields':['product_id','resource_type','resource_id',],
> + }
> +
> + def reparent_resource(self, product=None):
> + """a specific function to update a record when it is to move product"""
> + if product is not None:
> + new_product = Product(self._env, product)
> + if not new_product._exists:
> + sdata = {'new_table':product}
> + sdata.update(self.meta)
> + raise TracError('%(object_name)s %(new_table)s does not exist' %
> + sdata)
> + self._data['product_id'] = product
> + self.update()
> +
> +class MultiProductEnvironmentProvider(Component):
> + """Provides the means to create the db tables"""
> +
> + implements(IEnvironmentSetupParticipant)
> +
> + SCHEMA = [
> + Table('bloodhound_product', key = 'prefix') [
> + Column('prefix'),
> + Column('name'),
> + Column('description'),
> + Column('owner'),
> + ],
> + Table('bloodhound_productresourcemap', key = 'id') [
> + Column('id', auto_increment=True),
> + Column('product_id'),
> + Column('resource_type'),
> + Column('resource_id'),
> + ]
> + ]
> +
> + def get_version(self):
> + """Finds the current version of the bloodhound database schema"""
> + rows = self.env.db_query("""
> + SELECT value FROM system WHERE name = '%s'
> + """ % DB_SYSTEM_KEY)
> + return int(rows[0][0]) if rows else -1
> +
> + # IEnvironmentSetupParticipant methods
> + def environment_created(self):
> + """Insertion of any default data into the database."""
> + self.log.debug("creating environment for %s plugin." % PLUGIN_NAME)
> +
> + def environment_needs_upgrade(self, db_dummy=None):
> + """Detects if the installed db version matches the running system"""
> + db_installed_version = self.get_version()
> +
> + if db_installed_version> DB_VERSION:
> + raise TracError('''Current db version (%d) newer than supported by
> + this version of the %s (%d).''' % (db_installed_version,
> + PLUGIN_NAME,
> + DB_VERSION))
> + return db_installed_version< DB_VERSION
> +
> + def upgrade_environment(self, db_dummy=None):
> + """Installs or updates tables to current version"""
> + self.log.debug("upgrading existing environment for %s plugin." %
> + PLUGIN_NAME)
> + db_installed_version = self.get_version()
> + #cursor = db.cursor()
> + with self.env.db_transaction as db:
> + if db_installed_version< 0:
> + # Initial installation
> + db("""
> + INSERT INTO system (name, value) VALUES ('%s','%s')
> + """ % (DB_SYSTEM_KEY, DB_VERSION))
> + self.log.debug("creating initial db tables for %s plugin." %
> + PLUGIN_NAME)
> +
> + db_connector, _ = DatabaseManager(self.env)._get_connector()
> + for table in self.SCHEMA:
> + for statement in db_connector.to_sql(table):
> + db(statement)
> + db_installed_version = self.get_version()
> +
>
> Propchange: incubator/bloodhound/trunk/bloodhound_multiproduct/multiproduct/model.py
> ------------------------------------------------------------------------------
> svn:eol-style = native
>
> Added: incubator/bloodhound/trunk/bloodhound_multiproduct/setup.py
> URL: http://svn.apache.org/viewvc/incubator/bloodhound/trunk/bloodhound_multiproduct/setup.py?rev=1242755&view=auto
> ==============================================================================
> --- incubator/bloodhound/trunk/bloodhound_multiproduct/setup.py (added)
> +++ incubator/bloodhound/trunk/bloodhound_multiproduct/setup.py Fri Feb 10 13:18:16 2012
> @@ -0,0 +1,29 @@
> +
> +# Licensed to the Apache Software Foundation (ASF) under one
> +# or more contributor license agreements. See the NOTICE file
> +# distributed with this work for additional information
> +# regarding copyright ownership. The ASF licenses this file
> +# to you under the Apache License, Version 2.0 (the
> +# "License"); you may not use this file except in compliance
> +# with the License. You may obtain a copy of the License at
> +#
> +# http://www.apache.org/licenses/LICENSE-2.0
> +#
> +# Unless required by applicable law or agreed to in writing,
> +# software distributed under the License is distributed on an
> +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
> +# KIND, either express or implied. See the License for the
> +# specific language governing permissions and limitations
> +# under the License.
> +
> +"""setup for multi product plugin"""
> +from setuptools import setup
> +
> +setup(
> + name = 'BloodhoundMultiProduct',
> + version = '0.0.1',
> + packages = ['multiproduct', 'tests',],
> + entry_points = {'trac.plugins':['multiproduct = multiproduct',],},
> + test_suite = "tests",
> +)
> +
>
> Propchange: incubator/bloodhound/trunk/bloodhound_multiproduct/setup.py
> ------------------------------------------------------------------------------
> svn:eol-style = native
>
> Added: incubator/bloodhound/trunk/bloodhound_multiproduct/tests/__init__.py
> URL: http://svn.apache.org/viewvc/incubator/bloodhound/trunk/bloodhound_multiproduct/tests/__init__.py?rev=1242755&view=auto
> ==============================================================================
> (empty)
>
> Propchange: incubator/bloodhound/trunk/bloodhound_multiproduct/tests/__init__.py
> ------------------------------------------------------------------------------
> svn:eol-style = native
>
> Added: incubator/bloodhound/trunk/bloodhound_multiproduct/tests/model.py
> URL: http://svn.apache.org/viewvc/incubator/bloodhound/trunk/bloodhound_multiproduct/tests/model.py?rev=1242755&view=auto
> ==============================================================================
> --- incubator/bloodhound/trunk/bloodhound_multiproduct/tests/model.py (added)
> +++ incubator/bloodhound/trunk/bloodhound_multiproduct/tests/model.py Fri Feb 10 13:18:16
2012
> @@ -0,0 +1,161 @@
> +
> +# Licensed to the Apache Software Foundation (ASF) under one
> +# or more contributor license agreements. See the NOTICE file
> +# distributed with this work for additional information
> +# regarding copyright ownership. The ASF licenses this file
> +# to you under the Apache License, Version 2.0 (the
> +# "License"); you may not use this file except in compliance
> +# with the License. You may obtain a copy of the License at
> +#
> +# http://www.apache.org/licenses/LICENSE-2.0
> +#
> +# Unless required by applicable law or agreed to in writing,
> +# software distributed under the License is distributed on an
> +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
> +# KIND, either express or implied. See the License for the
> +# specific language governing permissions and limitations
> +# under the License.
> +
> +"""Tests for multiproduct/model.py"""
> +import unittest
> +import os
> +import tempfile
> +import shutil
> +
> +from sqlite3 import OperationalError
> +
> +from trac.test import EnvironmentStub
> +from trac.core import TracError
> +from multiproduct.model import Product
> +from multiproduct.model import MultiProductEnvironmentProvider
> +
> +class ProductTestCase(unittest.TestCase):
> + """Unit tests covering the Product model"""
> + def setUp(self):
> + self.env = EnvironmentStub(enable=['trac.*', 'multiproduct.*'])
> + self.env.path = tempfile.mkdtemp('bh-product-tempenv')
> +
> + self.envprovider = MultiProductEnvironmentProvider(self.env)
> + try:
> + self.envprovider.upgrade_environment(self.env.db_transaction)
> + except OperationalError:
> + # table remains but database version is deleted
> + pass
> +
> + self.default_data = {'prefix':'tp',
> + 'name':'test project',
> + 'description':'a test project'}
> +
> + product = Product(self.env)
> + product._data.update(self.default_data)
> + product.insert()
> +
> + def tearDown(self):
> + shutil.rmtree(self.env.path)
> + self.env.reset_db()
> +
> + def test_select(self):
> + """tests that select can search Products by fields"""
> +
> + p2_data = {'prefix':'tp2',
> + 'name':'test project',
> + 'description':'a different test project'}
> + p3_data = {'prefix':'tp3',
> + 'name':'test project',
> + 'description':'test project'}
> +
> + product2 = Product(self.env)
> + product2._data.update(p2_data)
> + product3 = Product(self.env)
> + product3._data.update(p3_data)
> +
> + product2.insert()
> + product3.insert()
> +
> + products = list(Product.select(self.env, {'prefix':'tp'}))
> + self.assertEqual(1, len(products))
> + products = list(Product.select(self.env, {'name':'test project'}))
> + self.assertEqual(3, len(products))
> +
> + def test_update(self):
> + """tests that we can use update to push data to the database"""
> + product = list(Product.select(self.env, {'prefix':'tp'}))[0]
> + self.assertEqual('test project', product._data['name'])
> +
> + new_data = {'prefix':'tp',
> + 'name':'updated',
> + 'description':'nothing'}
> + product._data.update(new_data)
> + product.update()
> +
> + comp_product = list(Product.select(self.env, {'prefix':'tp'}))[0]
> + self.assertEqual('updated', comp_product._data['name'])
> +
> + def test_update_key_change(self):
> + """tests that we raise an error for attempting to update key fields"""
> + bad_data = {'prefix':'tp0',
> + 'name':'update',
> + 'description':'nothing'}
> + product = list(Product.select(self.env, {'prefix':'tp'}))[0]
> + product._data.update(bad_data)
> + self.assertRaises(TracError, product.update)
> +
> + def test_insert(self):
> + """test saving new Product"""
> + data = {'prefix':'new', 'name':'new', 'description':'new'}
> + product = Product(self.env)
> + product._data.update(data)
> + product.insert()
> +
> + check_products = list(Product.select(self.env, {'prefix':'new'}))
> +
> + self.assertEqual(product._data['prefix'],
> + check_products[0]._data['prefix'])
> + self.assertEqual(1, len(check_products))
> +
> + def test_insert_duplicate_key(self):
> + """test attempted saving of Product with existing key fails"""
> + dupe_key_data = {'prefix':'tp',
> + 'name':'dupe',
> + 'description':'dupe primary key'}
> + product2 = Product(self.env)
> + product2._data.update(dupe_key_data)
> + self.assertRaises(TracError, product2.insert)
> +
> + def test_delete(self):
> + """test that we are able to delete Products"""
> + product = list(Product.select(self.env, {'prefix':'tp'}))[0]
> + product.delete()
> +
> + post = list(Product.select(self.env, {'prefix':'tp'}))
> + self.assertEqual(0, len(post))
> +
> + def test_delete_twice(self):
> + """test that we error when deleting twice on the same key"""
> + product = list(Product.select(self.env, {'prefix':'tp'}))[0]
> + product.delete()
> +
> + self.assertRaises(TracError, product.delete)
> +
> + def test_field_data_get(self):
> + """tests that we can use table.field syntax to get to the field data"""
> + prefix = self.default_data['prefix']
> + name = self.default_data['name']
> + description = self.default_data['description']
> + product = list(Product.select(self.env, {'prefix':prefix}))[0]
> + self.assertEqual(prefix, product.prefix)
> + self.assertEqual(name, product.name)
> + self.assertEqual(description, product.description)
> +
> + def test_field_set(self):
> + """tests that we can use table.field = something to set field data"""
> + prefix = self.default_data['prefix']
> + product = list(Product.select(self.env, {'prefix':prefix}))[0]
> +
> + new_description = 'test change of description'
> + product.description = new_description
> + self.assertEqual(new_description, product.description)
> +
> +if __name__ == '__main_':
> + unittest.main()
> +
>
> Propchange: incubator/bloodhound/trunk/bloodhound_multiproduct/tests/model.py
> ------------------------------------------------------------------------------
> svn:eol-style = native
>
>
|