def test_load_one(self):
     pool = InstancePool()
     dbp = DBPool(self.env, pool)
     dbp.load_artifact(self.lightningMcQueen.get_id())
     lightningMcQueen = pool.get_item(self.lightningMcQueen.get_id())
     self.assertEqual(lightningMcQueen.get_id(), self.lightningMcQueen.get_id())
     self.assertEqual(len(lightningMcQueen.get_value("Wheels")), 4)
 def test_load_related(self):
     pool = InstancePool()
     dbp = DBPool(self.env, pool)
     dbp.load_artifact(self.lightningMcQueen.get_id())
     lightningMcQueen = pool.get_item(self.lightningMcQueen.get_id())
     self.assertTrue(not pool.get_item(self.Car.get_id()) is None)
     self.assertTrue(not pool.get_item(self.Vehicle.get_id()) is None)
    def expand_macro(self, formatter, name, content):
        # Example: [[ASA(42)]]
        args, kw = parse_args(content)
        args = [arg.strip() for arg in args]
        if not args or not args[0].isdigit():
            raise TracError('Custom artifact id not specified')
        args, kw = parse_args(content)
        if not args or not args[0].isdigit():
            raise TracError('Custom artifact id not specified')
        artifact_id = int(args[0])
        dbp = DBPool(self.env, InstancePool())
        try:
            dbp.load_artifact(id=artifact_id)
        except ValueError:
            return system_message("Custom Artifact not found", "No custom artifact was found for id '{0}'.".format(artifact_id))
        artifact = dbp.pool.get_item(id=artifact_id)
        artifact_url = formatter.req.href.customartifacts('artifact/{0}'.format(artifact.get_id()))
        res = Core._get_resource(artifact) if not artifact in (Entity, Instance, None) and not type(artifact)==unicode else None
        spec_name, spec_url, values = _get_artifact_details(artifact, formatter.req)

        tpl='view_artifact_dialog.html'
        data = {
            'context': Context.from_request(formatter.req, res),
            'spec_name': spec_name,
            'spec_url': spec_url,
            'artifact': artifact,
            'artifact_url': artifact_url,
            'artifacts_values': values,
        }
        return Chrome(self.env).render_template(formatter.req, tpl, data, None, fragment=True)
 def test_load_all_specs(self):
     pool = InstancePool()
     dbp = DBPool(self.env, pool)
     dbp.load_specs()
     self.assertEqual(len(pool.get_items((1,))), 2)
     self.assertTrue(not pool.get_item(self.Car.get_id()) is None)
     self.assertTrue(not pool.get_item(self.Vehicle.get_id()) is None)
    def get_search_results(self, req, terms, filters):
        if 'asa-filter' in filters:
            for a_id, attr_name, attr_value, vid, time, author in Searcher.search(self.env, terms):
                dbp = DBPool(self.env, InstancePool())
                dbp.load_artifact(a_id)
                artifact = dbp.pool.get_item(a_id)

                res = Resource('asa', a_id, vid)
                link = get_resource_url(self.env, res, req.href)
                title = unicode(artifact)
                text = u"Custom Artifact of the type {0}.".format(artifact.__class__.get_name())
                text += u" {0}: {1}".format(attr_name, shorten_result(attr_value, terms))
                yield (link, title, time, author, text)
        return
    def test_retrieve_history(self):
        # make change
        pool = InstancePool()
        dbp = DBPool(self.env, pool)
        dbp.load_artifact(self.lightningMcQueen.get_id())
        lm = pool.get_item(self.lightningMcQueen.get_id())
        lm.set_value('License', 'GO-42-42')
        dbp.save('me', 'added license information', '127.0.0.1')

        # reload and inspect
        pool = InstancePool()
        dbp = DBPool(self.env, pool)
        dbp.load_artifact(self.lightningMcQueen.get_id())
        lm = pool.get_item(self.lightningMcQueen.get_id())
        h = [(version, timestamp, author, ipnr, comment) for version, timestamp, author, ipnr, comment in dbp.get_history(lm)]
        self.assertEqual(len(h), 2)
    def build_saved_and_reloaded_pool(testcase):
        testcase.env = EnvironmentStub(enable=['trac.*', 'AdaptiveArtifacts.*', 'AdaptiveArtifacts.persistence.db.*'])
        Setup(testcase.env).upgrade_environment(testcase.env.get_db_cnx())

        # this works as far as no one inherits from MetaModelInstancesStructureAfterLoad and ModelInstancesStructureAfterLoad
        super(testcase.__class__, testcase).setUp()

        dbp = DBPool(testcase.env, testcase.pool)
        dbp.save('anonymous',"","120.0.0.1")

        new_pool = InstancePool()
        new_dbp = DBPool(testcase.env, new_pool)
        for instance in testcase.pool.get_instances_of(Instance.get_name()):
            new_dbp.load_artifact(instance.get_id())
        for entity in testcase.pool.get_instances_of(Entity.get_name()):
            new_dbp.load_spec(entity.get_name())

        testcase.pool = new_pool
    def setUp(self):
        self.env = EnvironmentStub(enable=['trac.*', 'AdaptiveArtifacts.*', 'AdaptiveArtifacts.persistence.db.*'])
        Setup(self.env).upgrade_environment(self.env.get_db_cnx())

        self.Vehicle = Entity(name="Vehicle")
        self.Car = Entity(name="Car", bases=(self.Vehicle,),
                attributes=[Attribute(name="Wheels", multiplicity=4, atype=str)]
            )
        self.lightningMcQueen = self.Car(
                values={"Wheels": ['front left wheel', 'front right wheel', 'rear left wheel', 'front right wheel']}
            )

        pool = InstancePool()
        pool.add(self.Vehicle)
        pool.add(self.Car)
        pool.add(self.lightningMcQueen)
        dbp = DBPool(self.env, pool)
        dbp.save('anonymous',"","120.0.0.1")
    def test_delete_new(self):
        pool = InstancePool()
        dbp = DBPool(self.env, pool)
        dbp.load_artifact(self.lightningMcQueen.get_id())

        sallyCarrera = self.Car()
        pool.add(sallyCarrera)

        dbp = DBPool(self.env, pool)
        dbp.delete(sallyCarrera, 'me', 'deleted stuff', '127.0.0.1')
        self.assertEqual(3, len(dbp.pool.get_items((0,1))))
    def test_load_artifacts_of_spec(self):
        # add a couple more instances
        pool = InstancePool()
        dbp = DBPool(self.env, pool)
        dbp.load_specs()
        car1 = self.Car(values={"License": "GO-42-42"})
        plane2 = self.Vehicle(values={"License": "GO-55-55"})
        pool.add(car1)
        pool.add(plane2)
        dbp.save('me', 'a couple more instances', '127.0.0.1')

        # load cars only
        pool = InstancePool()
        dbp = DBPool(self.env, pool)
        dbp.load_artifacts_of(self.Car.get_name())
        
        self.assertEqual(len(pool.get_items((0,))), 2)
        self.assertTrue(not pool.get_item(self.lightningMcQueen.get_id()) is None)
        self.assertTrue(not pool.get_item(car1.get_id()) is None)
    def post_process_request(self, req, template, data, content_type):
        Chrome(self.env).add_jquery_ui(req)
        add_javascript(req, "customartifacts/js/lib/ace/ace.js")
        add_javascript(req, "customartifacts/js/lib/ace/theme-trac_wiki.js")
        add_javascript(req, 'customartifacts/js/lib/jquery.balloon.js')

        add_javascript(req, "customartifacts/js/requests.js")
        add_javascript(req, 'customartifacts/js/tracking.js')
        add_javascript(req, "customartifacts/js/dialogs.js")
        add_javascript(req, 'customartifacts/js/util.js')
        add_javascript(req, 'customartifacts/js/uuid.js')
        add_javascript(req, 'customartifacts/js/forms.js')

        path_parts = req.environ.get('PATH_INFO', '').decode("utf-8").split("/")
        module_area = path_parts[1] if len(path_parts)>1 else None
        if module_area == 'wiki':
            from datetime import datetime
            dbp = DBPool(self.env, InstancePool())
            resource_id = u""
            if len(path_parts) > 2:
                resource_id = path_parts[2]

            if 'action' in req.args and req.args['action'] == 'edit':
                dbp.track_it("wiki", resource_id, "edit", req.authname, str(datetime.now()))
            else:
                dbp.track_it("wiki", resource_id, "view", req.authname, str(datetime.now()))

            page = WikiPage(dbp.env, resource_id)
            add_script_data(req, {'embedded_artifacts': get_embedded_artifact_ids_from_text(page.text)})

        if module_area == 'wiki' and 'action' in req.args and req.args['action'] == 'edit' or \
            module_area in ['ticket', 'newticket']:
                add_javascript(req, "customartifacts/js/wiki.js")

        add_script_data(req, {'baseurl': req.href.customartifacts()})
        add_script_data(req, {'form_token': req.form_token})
        add_stylesheet(req, 'customartifacts/css/asa.css', media='screen')
        add_stylesheet(req, 'customartifacts/css/wiki.css')
        add_stylesheet(req, 'customartifacts/css/ticket.css')
        add_stylesheet(req, 'customartifacts/css/index_page.css')

        return (template, data, content_type)
    def _get_link(self, href, artifact_id, label=None, art_attr=None):
        try:
            pool = InstancePool()
            dbp = DBPool(self.env, pool)
            dbp.load_artifact(id=artifact_id)
            artifact = pool.get_item(id=artifact_id)
            spec_name = artifact.__class__.get_name() if not artifact.__class__ is Instance else None
            if not art_attr is None:
                label = artifact.get_value(art_attr)
                if label is None:
                    return inline_system_message(u"Error: The attribute '{0}' was not found.".format(art_attr))

            if label is None:
                label = str(artifact)
            if spec_name is None:
                title = "Custom Software Artifact '%s'" % (label,)
            else:
                title = "Custom Software Artifact '%s' of type '%s'" % (label, spec_name)
        except ValueError:
            title = "Custom Software Artifact with ID '%s' does not exist" % (artifact_id,)
        return tag.a(label, href=href.customartifacts('artifact', artifact_id), class_="asa-link", title=title)
    def test_delete_unmodified(self):
        pool = InstancePool()
        dbp = DBPool(self.env, pool)
        dbp.load_artifact(self.lightningMcQueen.get_id())
        lightningMcQueen = pool.get_item(self.lightningMcQueen.get_id())
        dbp.delete(lightningMcQueen, 'me', 'deleted stuff', '127.0.0.1')
        self.assertTrue(pool.get_item(lightningMcQueen.get_id()) is None)

        pool2 = InstancePool()
        dbp2 = DBPool(self.env, pool2)
        self.assertRaises(ValueError, dbp2.load_artifact, self.lightningMcQueen.get_id())
        self.assertTrue(pool2.get_item(self.lightningMcQueen.get_id()) is None)
    def test_delete_changed(self):
        pool = InstancePool()
        dbp = DBPool(self.env, pool)
        dbp.load_artifact(self.lightningMcQueen.get_id())
        lightningMcQueen = pool.get_item(self.lightningMcQueen.get_id())
        self.lightningMcQueen.set_value('Wheels', ['front middle wheel', 'rear left wheel', 'front right wheel'])
        dbp.delete(lightningMcQueen, 'me', 'deleted stuff', '127.0.0.1')
        self.assertTrue(pool.get_item(lightningMcQueen.get_id()) is None)
        self.assertEqual(2, len(dbp.pool.get_items((0,1))))

        pool2 = InstancePool()
        dbp2 = DBPool(self.env, pool2)
        self.assertRaises(ValueError, dbp2.load_artifact, self.lightningMcQueen.get_id())
        self.assertTrue(pool2.get_item(self.lightningMcQueen.get_id()) is None)
    def _upgrade_to_0dot3(self, db):
        cursor = db.cursor()
        cursor.execute(
            "ALTER TABLE asa_artifact_wiki RENAME TO asa_artifact_wiki_references;"
        )
        for table in schema:  # TODO: fix. reference to global var
            if table.name == "asa_artifact_artifact_references":
                self._create_table(table, cursor)
                break

        from AdaptiveArtifacts.persistence.data import DBPool
        from AdaptiveArtifacts.model.pool import InstancePool
        from AdaptiveArtifacts.model.core import Instance
        dbp = DBPool(self.env, InstancePool())
        dbp.load_specs()
        dbp.load_artifacts_of(Instance.get_name())
        for artifact in dbp.pool.get_instances_of(Instance.get_name()):
            dbp.update_artifact_ref_count(artifact, db)

        cursor.execute("UPDATE system SET value='0.3' WHERE name='%s'" %
                       (self.db_key, ))
        self.log.info('Upgraded ASA tables from versions 0.1/0.2 to 0.3')
    def _upgrade_to_0dot3(self, db):
        cursor = db.cursor()
        cursor.execute("ALTER TABLE asa_artifact_wiki RENAME TO asa_artifact_wiki_references;")
        for table in schema: # TODO: fix. reference to global var
            if table.name == "asa_artifact_artifact_references":
                self._create_table(table, cursor)
                break

        from AdaptiveArtifacts.persistence.data import DBPool
        from AdaptiveArtifacts.model.pool import InstancePool
        from AdaptiveArtifacts.model.core import Instance
        dbp = DBPool(self.env, InstancePool())
        dbp.load_specs()
        dbp.load_artifacts_of(Instance.get_name())
        for artifact in dbp.pool.get_instances_of(Instance.get_name()):
            dbp.update_artifact_ref_count(artifact, db)

        cursor.execute("UPDATE system SET value='0.3' WHERE name='%s'" % (self.db_key,))
        self.log.info('Upgraded ASA tables from versions 0.1/0.2 to 0.3')
    def test_edit_spec_name(self):
        pool = InstancePool()
        dbp = DBPool(self.env, pool)
        dbp.load_spec("Car")
        Car = dbp.pool.get_item("Car")

        # create three more versions
        Car._is_modified = True
        dbp.save('me', 'a new version', '127.0.0.1')
        Car._is_modified = True
        dbp.save('me', 'a new version', '127.0.0.1')
        Car._is_modified = True
        dbp.save('me', 'a new version', '127.0.0.1')

        # so, there should be 4 versions now
        ch = [(version, timestamp, author, ipnr, comment) for version, timestamp, author, ipnr, comment in dbp.get_history(Car)]
        self.assertEqual(len(ch), 4)

        # edit the name
        Car._replace_name("Automobile")
        dbp.save('me', 'a couple more instances', '127.0.0.1')

        # querying by the new name should render 5 versions
        self.assertEqual(Car.get_name(), "Automobile")
        ch = [(version, timestamp, author, ipnr, comment) for version, timestamp, author, ipnr, comment in dbp.get_history(Car)]
        self.assertEqual(len(ch), 5)
 def get_resource_url(self, resource, href, **kwargs):
     dbp = DBPool(self.env, InstancePool())
     item = dbp.load_item(resource.id)
     return href.customartifacts('artifact/%d' % (resource.id,), action='view')
 def _update_wiki_page_ref_count(self, page):
     artifacts_ids = get_artifact_ids_from_text(page.text)
     dbp = DBPool(self.env, InstancePool())
     dbp.update_wiki_page_references(page, artifacts_ids)