Esempio n. 1
0
    def setUp(self):
        super(TestRelationshipAttr, self).setUp()

        m1 = RelationshipAttrTestMockModel()
        m2 = RelationshipAttrTestMockModel()
        self.rel = Relationship(source=m1, destination=m2)

        self.mapper_mock = mock.Mock(name='mapper')
        self.connection_mock = mock.Mock(name='connection')
Esempio n. 2
0
def build_cycle(cycle, current_user=None, base_date=None):
    """Build a cycle with it's child objects"""

    if not base_date:
        base_date = date.today()

    # Determine the relevant Workflow
    workflow = cycle.workflow

    # Use WorkflowOwner role when this is called via the cron job.
    if not current_user:
        for user_role in workflow.context.user_roles:
            if user_role.role.name == "WorkflowOwner":
                current_user = user_role.person
                break

    # Populate the top-level Cycle object
    cycle.context = workflow.context
    cycle.title = workflow.title
    cycle.description = workflow.description
    cycle.status = 'Assigned'

    # Populate CycleTaskGroups based on Workflow's TaskGroups
    for task_group in workflow.task_groups:
        cycle_task_group = models.CycleTaskGroup(
            context=cycle.context,
            cycle=cycle,
            task_group=task_group,
            title=task_group.title,
            description=task_group.description,
            end_date=cycle.end_date,
            modified_by=current_user,
            contact=task_group.contact,
            status="Assigned",
            sort_index=task_group.sort_index,
        )

        # preserve the old cycle creation for old workflows, so each object
        # gets its own cycle task
        if workflow.is_old_workflow:
            create_old_style_cycle(cycle, task_group, cycle_task_group,
                                   current_user, base_date)
        else:
            for task_group_task in task_group.task_group_tasks:
                cycle_task_group_object_task = _create_cycle_task(
                    task_group_task, cycle, cycle_task_group, current_user,
                    base_date)

                for task_group_object in task_group.task_group_objects:
                    object_ = task_group_object.object
                    db.session.add(
                        Relationship(source=cycle_task_group_object_task,
                                     destination=object_))

    update_cycle_dates(cycle)

    Signals.workflow_cycle_start.send(cycle.__class__,
                                      obj=cycle,
                                      new_status=cycle.status,
                                      old_status=None)
Esempio n. 3
0
def handle_relationship_post(source, destination):
    """Handle posting of special relationships.

  This function handles direct relationships that do not have a relationship
  object. A fake object is created with source and destination and auto
  mappings are then generated.

  Args:
    source: Source model of relationship
    destination: Destination model of relationship

  """
    if source is None:
        logger.warning("Automapping request listener: "
                       "no source, no mappings created")
        return
    if destination is None:
        logger.warning("Automapping request listener: "
                       "no destination, no mappings created")
        return
    relationship = Relationship(source_type=source.type,
                                source_id=source.id,
                                destination_type=destination.type,
                                destination_id=destination.id)
    AutomapperGenerator().generate_automappings(relationship)
Esempio n. 4
0
def build_cycle(workflow, cycle=None, current_user=None):
  """Build a cycle with it's child objects"""

  if not workflow.tasks:
    logger.error("Starting a cycle has failed on Workflow with "
                 "slug == '%s' and id == '%s'", workflow.slug, workflow.id)
    pusher.update_or_create_notifications(workflow, date.today(),
                                          "cycle_start_failed")
    return

  # Determine the relevant Workflow
  cycle = cycle or models.Cycle()

  # Use Admin role when this is called via the cron job.
  if not current_user:
    current_user = workflow.get_persons_for_rolename("Admin")[0]
  # Populate the top-level Cycle object
  cycle.workflow = workflow
  cycle.is_current = True
  cycle.context = workflow.context
  cycle.title = workflow.title
  cycle.description = workflow.description
  cycle.is_verification_needed = workflow.is_verification_needed
  cycle.status = models.Cycle.ASSIGNED

  # Populate CycleTaskGroups based on Workflow's TaskGroups
  for task_group in workflow.task_groups:
    cycle_task_group = models.CycleTaskGroup(
        context=cycle.context,
        cycle=cycle,
        task_group=task_group,
        title=task_group.title,
        description=task_group.description,
        end_date=cycle.end_date,
        modified_by=current_user,
        contact=task_group.contact,
        status=models.CycleTaskGroup.ASSIGNED,
        sort_index=task_group.sort_index,
    )

    # preserve the old cycle creation for old workflows, so each object
    # gets its own cycle task
    if workflow.is_old_workflow:
      create_old_style_cycle(cycle, task_group, cycle_task_group, current_user)
    else:
      for task_group_task in task_group.task_group_tasks:
        cycle_task_group_object_task = _create_cycle_task(
            task_group_task, cycle, cycle_task_group, current_user)

        for task_group_object in task_group.task_group_objects:
          object_ = task_group_object.object
          Relationship(source=cycle_task_group_object_task,
                       destination=object_)

  update_cycle_dates(cycle)
  workflow.repeat_multiplier += 1
  workflow.next_cycle_start_date = workflow.calc_next_adjusted_date(
      workflow.min_task_start_date)
  return cycle
Esempio n. 5
0
  def setUp(self):
    super(TestRelationshipAttr, self).setUp()

    m1 = RelationshipAttrTestMockModel()
    m2 = RelationshipAttrTestMockModel()
    self.rel = Relationship(source=m1, destination=m2)

    self.mapper_mock = mock.Mock(name='mapper')
    self.connection_mock = mock.Mock(name='connection')
Esempio n. 6
0
        def add_related(self, parent, _action):
            """Add/map object to parent"""
            added = []
            if _action.get("id"):
                action = self._validate(_action, self.MapRelated)
                obj = self._get(action)
            else:
                action = self._validate(_action, self.AddRelated)
                obj = self._create(parent, action)
                added.append(obj)

            rel = Relationship(source=parent,
                               destination=obj,
                               context=parent.context)
            added.append(rel)
            return added, []
Esempio n. 7
0
def create_old_style_cycle(cycle, task_group, cycle_task_group, current_user):
    """ This function preserves the old style of creating cycles, so each object
  gets its own task assigned to it.
  """
    if len(task_group.task_group_objects) == 0:
        for task_group_task in task_group.task_group_tasks:
            cycle_task_group_object_task = _create_cycle_task(
                task_group_task, cycle, cycle_task_group, current_user)

    for task_group_object in task_group.task_group_objects:
        object_ = task_group_object.object
        for task_group_task in task_group.task_group_tasks:
            cycle_task_group_object_task = _create_cycle_task(
                task_group_task, cycle, cycle_task_group, current_user)
            Relationship(source=cycle_task_group_object_task,
                         destination=object_)
Esempio n. 8
0
 def after_save(self, obj):
   for linked_object in self.created_links():
     db.session.add(linked_object)
     relationship = Relationship()
     relationship.relationship_type_id = self.options.get('relationship_type_id')
     if self.options.get('direction') == 'to':
       relationship.source = self.importer.obj
       relationship.destination = linked_object
     elif self.options.get('direction') == 'from':
       relationship.destination = self.importer.obj
       relationship.source = linked_object
     db.session.add(relationship)
Esempio n. 9
0
def create_old_style_cycle(cycle, task_group, cycle_task_group, current_user):
    """ This function preserves the old style of creating cycles, so each object
  gets its own task assigned to it.
  """
    related_objs = [
        obj for obj in task_group.related_objects()
        if not isinstance(obj, (all_models.TaskGroupTask, all_models.Workflow))
    ]
    if len(related_objs) == 0:
        for task_group_task in task_group.task_group_tasks:
            _create_cycle_task(task_group_task, cycle, cycle_task_group,
                               current_user)

    for obj in related_objs:
        for task_group_task in task_group.task_group_tasks:
            cycle_task_group_object_task = _create_cycle_task(
                task_group_task, cycle, cycle_task_group, current_user)
            Relationship(source=cycle_task_group_object_task, destination=obj)
Esempio n. 10
0
    def setUp(self):
        super(TestRelationship, self).setUp()
        if RelationshipTestMockModel.__table__.exists(db.engine):
            RelationshipTestMockModel.__table__.drop(db.engine)
        RelationshipTestMockModel.__table__.create(db.engine)
        with self.client.session_transaction() as session:
            session['permissions'] = {
                "__GGRC_ADMIN__": {
                    "__GGRC_ALL__": {
                        "contexts": [0]
                    }
                }
            }

        self.m1 = self.mock_model()
        self.m2 = self.mock_model()
        self.rel = Relationship(source=self.m1, destination=self.m2)
        db.session.add(self.rel)
Esempio n. 11
0
class TestRelationshipAttr(unittest.TestCase):
    def setUp(self):
        super(TestRelationshipAttr, self).setUp()

        m1 = RelationshipAttrTestMockModel()
        m2 = RelationshipAttrTestMockModel()
        self.rel = Relationship(source=m1, destination=m2)

        self.mapper_mock = mock.Mock(name='mapper')
        self.connection_mock = mock.Mock(name='connection')

    def test_attrs_validation_ok(self):
        self.rel.attrs["validated_attr"] = "123"

        # not raises ValueError
        self.rel.validate_attrs(self.mapper_mock, self.connection_mock,
                                self.rel)

    def test_attrs_validation_invalid_attr(self):
        self.rel.attrs["foo"] = "bar"

        with self.assertRaises(ValueError):
            self.rel.validate_attrs(self.mapper_mock, self.connection_mock,
                                    self.rel)

    def test_attrs_validation_invalid_value(self):
        self.rel.attrs["validated_attr"] = "wrong value"

        with self.assertRaises(ValueError):
            self.rel.validate_attrs(self.mapper_mock, self.connection_mock,
                                    self.rel)

    def test_gather_validators(self):
        class ValidatorParent(object):
            @staticmethod
            def _validate_relationship_attr(cls):
                return True

        class ValidatorChild(ValidatorParent):
            @staticmethod
            def _validate_relationship_attr(cls):
                return False

        validators = RelationshipAttr._gather_validators(ValidatorChild)
        self.assertEqual({True, False}, {v() for v in validators})
Esempio n. 12
0
class TestRelationshipAttr(unittest.TestCase):

  def setUp(self):
    super(TestRelationshipAttr, self).setUp()

    m1 = RelationshipAttrTestMockModel()
    m2 = RelationshipAttrTestMockModel()
    self.rel = Relationship(source=m1, destination=m2)

    self.mapper_mock = mock.Mock(name='mapper')
    self.connection_mock = mock.Mock(name='connection')

  def test_attrs_validation_ok(self):
    self.rel.attrs["validated_attr"] = "123"

    # not raises ValueError
    self.rel.validate_attrs(self.mapper_mock, self.connection_mock, self.rel)

  def test_attrs_validation_invalid_attr(self):
    self.rel.attrs["foo"] = "bar"

    with self.assertRaises(ValueError):
      self.rel.validate_attrs(self.mapper_mock, self.connection_mock, self.rel)

  def test_attrs_validation_invalid_value(self):
    self.rel.attrs["validated_attr"] = "wrong value"

    with self.assertRaises(ValueError):
      self.rel.validate_attrs(self.mapper_mock, self.connection_mock, self.rel)

  def test_gather_validators(self):
    class ValidatorParent(object):
      @staticmethod
      def _validate_relationship_attr(cls):
        return True

    class ValidatorChild(ValidatorParent):
      @staticmethod
      def _validate_relationship_attr(cls):
        return False

    validators = RelationshipAttr._gather_validators(ValidatorChild)
    self.assertEqual({True, False}, {v() for v in validators})
Esempio n. 13
0
def build_cycle(workflow, cycle=None, current_user=None):
  """Build a cycle with it's child objects"""
  build_failed = False

  if not workflow.tasks:
    logger.error("Starting a cycle has failed on Workflow with "
                 "slug == '%s' and id == '%s', due to empty setup",
                 workflow.slug, workflow.id)
    build_failed = True

  # Use Admin role when this is called via the cron job.
  if not current_user:
    admins = workflow.get_persons_for_rolename("Admin")
    if admins:
      current_user = admins[0]
    else:
      logger.error("Cannot start cycle on Workflow with slug == '%s' and "
                   "id == '%s', cause it doesn't have Admins",
                   workflow.slug, workflow.id)
      build_failed = True

  if build_failed:
    pusher.update_or_create_notifications(workflow, date.today(),
                                          "cycle_start_failed")
    return

  # Determine the relevant Workflow
  cycle = cycle or models.Cycle()

  # Populate the top-level Cycle object
  cycle.workflow = workflow
  cycle.is_current = True
  cycle.context = workflow.context
  cycle.title = workflow.title
  cycle.description = workflow.description
  cycle.is_verification_needed = workflow.is_verification_needed
  cycle.status = models.Cycle.ASSIGNED

  # Populate CycleTaskGroups based on Workflow's TaskGroups
  for task_group in workflow.task_groups:
    cycle_task_group = models.CycleTaskGroup(
        context=cycle.context,
        cycle=cycle,
        task_group=task_group,
        title=task_group.title,
        description=task_group.description,
        end_date=cycle.end_date,
        modified_by=current_user,
        contact=task_group.contact,
        status=models.CycleTaskGroup.ASSIGNED,
    )

    # preserve the old cycle creation for old workflows, so each object
    # gets its own cycle task
    if workflow.is_old_workflow:
      create_old_style_cycle(cycle, task_group, cycle_task_group, current_user)
    else:
      for task_group_task in task_group.task_group_tasks:
        cycle_task_group_object_task = _create_cycle_task(
            task_group_task, cycle, cycle_task_group, current_user)
        related_objs = [obj for obj in task_group.related_objects()
                        if not isinstance(obj, (
                            all_models.TaskGroupTask, all_models.Workflow
                        ))]
        for obj in related_objs:
          Relationship(source=cycle_task_group_object_task,
                       destination=obj)

  update_cycle_dates(cycle)
  workflow.repeat_multiplier += 1
  workflow.next_cycle_start_date = workflow.calc_next_adjusted_date(
      workflow.min_task_start_date)
  return cycle