当前位置: 首页>>代码示例>>Python>>正文


Python Api.set_user方法代码示例

本文整理汇总了Python中integration.ggrc.Api.set_user方法的典型用法代码示例。如果您正苦于以下问题:Python Api.set_user方法的具体用法?Python Api.set_user怎么用?Python Api.set_user使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在integration.ggrc.Api的用法示例。


在下文中一共展示了Api.set_user方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: CycleRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class CycleRBACFactory(base.BaseRBACFactory):
  """Cycle RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Cycle permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        object_acl: Dict with format: {
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    # pylint: disable=unused-argument
    self.setup_workflow_scope(user_id, acr)
    self.api = Api()
    if user_id:
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def create(self):
    """Create new cycle for Workflow."""
    return self.generate_cycle(self.workflow_id, self.api)

  def update(self):
    """Update existing cycle."""
    cycle = all_models.Cycle.query.first()
    return self.api.put(cycle, {"title": factories.random_str()})

  def delete(self):
    """Delete existing cycle."""
    cycle = all_models.Cycle.query.first()
    return self.api.delete(cycle)

  def activate(self):
    """Activate Workflow."""
    workflow = all_models.Workflow.query.get(self.workflow_id)
    cycle = wf_factories.CycleFactory(workflow=workflow)
    return self.api.put(workflow, {
        "status": "Active",
        "recurrences": bool(workflow.repeat_every and workflow.unit),
        "cycles": [{
            "id": cycle.id,
            "type": "Cycle",
        }]
    })

  def read(self):
    """Read existing Cycle object."""
    cycle = all_models.Cycle.query.first()
    return self.api.get(cycle, cycle.id)

  def end(self):
    """End existing Cycle."""
    cycle = all_models.Cycle.query.first()
    return self.api.put(cycle, {"is_current": False})
开发者ID:,项目名称:,代码行数:57,代码来源:

示例2: CycleTaskEntryRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class CycleTaskEntryRBACFactory(base.BaseRBACFactory):
  """Cycle Task Entry RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Cycle Task Entry permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    # pylint: disable=unused-argument
    self.setup_workflow_scope(user_id, acr)
    self.api = Api()
    self.create()
    if user_id:
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def create(self):
    """Create new Cycle Task Entry object."""
    cycle_task = all_models.CycleTaskGroupObjectTask.query.first()
    return self.api.post(all_models.CycleTaskEntry, {
        "cycle_task_entry": {
            "description": "New Comment",
            "is_declining_review": "",
            "context": None,
            "cycle_task_group_object_task": {
                "id": cycle_task.id,
                "type": "CycleTaskGroupObjectTask",
            },
            "cycle": {
                "id": cycle_task.cycle.id,
                "type": "Cycle",
            },
        }
    })

  def read(self):
    """Read existing Cycle Task Entry object."""
    cycle_task_entry = all_models.CycleTaskEntry.query.first()
    return self.api.get(cycle_task_entry, cycle_task_entry.id)

  def update(self):
    """Update title of existing Cycle Task Entry object."""
    cycle_task_entry = all_models.CycleTaskEntry.query.first()
    return self.api.put(
        cycle_task_entry,
        {"description": factories.random_str()}
    )

  def delete(self):
    """Delete Cycle Task Entry object."""
    cycle_task_entry = all_models.CycleTaskEntry.query.first()
    return self.api.delete(cycle_task_entry)
开发者ID:egorhm,项目名称:ggrc-core,代码行数:57,代码来源:cycle_task_entry.py

示例3: CycleTaskGroupRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class CycleTaskGroupRBACFactory(base.BaseRBACFactory):
  """Cycle Task Group RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Cycle Task Group permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    # pylint: disable=unused-argument
    self.setup_workflow_scope(user_id, acr)

    self.admin_control_id = {
        name: id_ for id_, name
        in access_control.role.get_custom_roles_for("Control").items()
    }["Admin"]
    self.api = Api()

    if user_id:
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def read(self):
    """Read existing Cycle Task Group object."""
    cycle_tg = all_models.CycleTaskGroup.query.first()
    return self.api.get(all_models.CycleTaskGroup, cycle_tg.id)

  def update(self):
    """Update title of existing Cycle Task Group object."""
    cycle_tg = all_models.CycleTaskGroup.query.first()
    return self.api.put(cycle_tg, {"title": factories.random_str()})

  def delete(self):
    """Delete Cycle Task Group object."""
    cycle_tg = all_models.CycleTaskGroup.query.first()
    return self.api.delete(cycle_tg)
开发者ID:egorhm,项目名称:ggrc-core,代码行数:40,代码来源:cycle_task_group.py

示例4: UniversalRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class UniversalRBACFactory(base.BaseRBACFactory):
  """Universal RBAC factory class.

  Can be used in 'one rank' tests
  """
  # pylint: disable=too-many-instance-attributes

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    self.api = Api()
    self.objgen = generator.ObjectGenerator()
    self.objgen.api = self.api

    self.acr = acr
    self.user_id = user_id
    self.parent_name = parent
    self.document_id = None
    self.parent = None
    self.parent_id = None
    self.setup_models(self.parent_name)
    self.set_user(user_id)

  def set_user(self, user_id):
    """Set user to send requests"""
    if self.user_id:
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def setup_models(self, parent_name):
    """Setup document, parent, relationship"""
    with factories.single_commit():
      self.parent = get_model_factory(parent_name)()
      self.parent_id = self.parent.id
      self.parent_name = parent_name
      self.assign_person(self.parent, self.acr, self.user_id)

  def _setup_document(self):
    """Crate and map document"""
    with factories.single_commit():
      document = factories.DocumentReferenceUrlFactory()
      parent = db.session.query(self.parent.__class__).get(self.parent_id)
      factories.RelationshipFactory(source=parent, destination=document)
    return document.id

  def _setup_comment(self):
    """Crate and map comment"""
    with factories.single_commit():
      comment = factories.CommentFactory(description="Hey!")
      parent = db.session.query(self.parent.__class__).get(self.parent_id)
      factories.RelationshipFactory(source=parent, destination=comment)
    return comment.id

  def read_parent(self):
    """Can Read parent info."""
    res = self.api.get(self.parent, self.parent_id)
    return res

  def create_and_map_document(self):
    """Create and map document object to parent."""
    admin_acr_id = all_models.AccessControlRole.query.filter_by(
        name="Admin",
        object_type="Document",
    ).one().id

    _, document = self.objgen.generate_object(
        all_models.Document, {
            "link":
            factories.random_str(),
            "title":
            factories.random_str(),
            "context":
            None,
            "access_control_list": [
                {
                    "ac_role_id": admin_acr_id,
                    "person": {
                        "id": self.user_id,
                        "type": "Person",
                    }
                }
            ],
        }
    )
    parent = db.session.query(self.parent.__class__).get(self.parent_id)
    return self.objgen.generate_relationship(
        source=document, destination=parent
    )[0]

  def read_document(self):
    """Read existing Document object."""
    doc_id = self._setup_document()
    res = self.api.get(all_models.Document, doc_id)
    return res

#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:

示例5: TestEvidenceRolePropagation

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class TestEvidenceRolePropagation(TestCase):
  """Evidence role propagation test case"""
  # pylint: disable=invalid-name

  def setUp(self):
    super(TestEvidenceRolePropagation, self).setUp()
    self.api = Api()
    self.generator = ObjectGenerator()

  # Propagation isn't work for 'Primary Contacts', 'Secondary Contacts'
  # just add them to data list to check if fix works.

  @ddt.data("Assignees", "Creators", "Verifiers")
  def test_assessment_role_propagation_edit(self, role_name):
    """Asses user with role '{0}' should be able to edit related evidence"""

    _, reader = self.generator.generate_person(user_role="Creator")
    with factories.single_commit():
      assessment = factories.AssessmentFactory()
      assessment.add_person_with_role_name(reader, role_name)
      evidence = factories.EvidenceFactory()
      evidence_id = evidence.id
      factories.RelationshipFactory(source=assessment, destination=evidence)

    self.api.set_user(reader)

    evidence = all_models.Evidence.query.get(evidence_id)
    new_description = 'new description'
    resp = self.api.modify_object(evidence, {'description': new_description})
    evidence = self.refresh_object(evidence)
    self.assert200(resp)
    self.assertEquals(new_description, evidence.description)
    self.assertEquals(reader.id, evidence.modified_by_id)

  @ddt.data(
      ("Creator", "Audit Captains", 200),
      ("Creator", "Auditors", 403),
      ("Reader", "Audit Captains", 200),
      ("Reader", "Auditors", 403),
      ("Editor", "Audit Captains", 200),
      ("Editor", "Auditors", 200),
  )
  @ddt.unpack
  def test_audit_role_propagation_edit(self, user_role, audit_role,
                                       status_code):
    """'{0}' assigned as '{1}' should get '{2}' when editing audit evidence"""
    _, user = self.generator.generate_person(user_role=user_role)
    with factories.single_commit():
      audit = factories.AuditFactory()
      audit.add_person_with_role_name(user, audit_role)
      evidence = factories.EvidenceFactory()
      evidence_id = evidence.id

    factories.RelationshipFactory(source=audit, destination=evidence)

    self.api.set_user(user)

    evidence = all_models.Evidence.query.get(evidence_id)
    new_description = 'new description'
    resp = self.api.modify_object(evidence, {'description': new_description})
    evidence = self.refresh_object(evidence)

    if status_code == 200:
      self.assert200(resp)
      self.assertEquals(new_description, evidence.description)
      self.assertEquals(user.id, evidence.modified_by_id)
    else:
      self.assertStatus(resp, status_code)

  def test_audit_role_propagation_not_delete(self):
    """Audit user with role Auditors can NOT delete related evidence"""
    role_name = "Auditors"
    _, reader = self.generator.generate_person(user_role="Reader")
    with factories.single_commit():
      audit = factories.AuditFactory()
      audit.add_person_with_role_name(reader, role_name)
      evidence = factories.EvidenceFactory()
      evidence_id = evidence.id

    factories.RelationshipFactory(source=audit, destination=evidence)

    self.api.set_user(reader)
    evidence = all_models.Evidence.query.get(evidence_id)

    resp = self.api.delete(evidence)
    self.assertStatus(resp, 403)
    evidence = all_models.Evidence.query.get(evidence_id)
    self.assertTrue(evidence)
开发者ID:,项目名称:,代码行数:90,代码来源:

示例6: EvidenceRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class EvidenceRBACFactory(base.BaseRBACFactory):
  """Evidence RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Evidence permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    self.setup_program_scope(user_id, acr)

    with factories.single_commit():
      evidence = factories.EvidenceUrlFactory()
      if parent == "Audit":
        self.mapping_id = factories.RelationshipFactory(
            source=self.audit, destination=evidence
        ).id
      elif parent == "Assessment":
        self.mapping_id = factories.RelationshipFactory(
            source=self.assessment, destination=evidence
        ).id
    self.evidence_id = evidence.id
    self.parent = parent
    self.admin_acr_id = all_models.AccessControlRole.query.filter_by(
        name="Admin",
        object_type="Evidence",
    ).one().id
    self.user_id = user_id
    self.api = Api()
    self.objgen = generator.ObjectGenerator()
    self.objgen.api = self.api
    if user_id:
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def create(self):
    """Create new Evidence object."""
    result = self.api.post(all_models.Evidence, {
        "evidence": {
            "access_control_list": [{
                "ac_role_id": self.admin_acr_id,
                "person": {
                    "id": self.user_id,
                    "type": "Person",
                }
            }],
            "link": factories.random_str(),
            "title": factories.random_str(),
            "context": None,
        }
    })
    return result

  def read(self):
    """Read existing Evidence object."""
    res = self.api.get(all_models.Evidence, self.evidence_id)
    return res

  def update(self):
    """Update title of existing Evidence object."""
    evidence = all_models.Evidence.query.get(self.evidence_id)
    return self.api.put(evidence, {"title": factories.random_str()})

  def delete(self):
    """Delete Evidence object."""
    evidence = all_models.Evidence.query.get(self.evidence_id)
    return self.api.delete(evidence)

  def map(self, evidence=None):
    """Map Evidence to parent object."""
    if self.parent == "Audit":
      parent = all_models.Audit.query.get(self.audit_id)
    else:
      parent = all_models.Assessment.query.get(self.assessment_id)
    map_evidence = evidence if evidence else factories.EvidenceUrlFactory()

    return self.api.put(parent, {
        "actions": {
            "add_related": [{
                "id": map_evidence.id,
                "type": "Evidence",
            }]
        }
    })

  def create_and_map(self):
    """Create new Evidence and map it to parent."""
    response = self.create()
    evidence_id = None
    if response.json and response.json.get("evidence"):
      evidence_id = response.json.get("evidence", {}).get("id")
    if not evidence_id:
      return response

    evidence = all_models.Evidence.query.get(evidence_id)
    return self.map(evidence)

  def add_comment(self):
#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:

示例7: AssessmentTemplateRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class AssessmentTemplateRBACFactory(base.BaseRBACFactory):
  """Assessment Template RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Assessment Template permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    self.setup_program_scope(user_id, acr, parent)

    with factories.single_commit():
      template = factories.AssessmentTemplateFactory(audit=self.audit)
      factories.RelationshipFactory(source=self.audit, destination=template)

    self.template_id = template.id
    self.default_assignees = "Admin"
    self.default_verifiers = "Admin"
    self.api = Api()

    if user_id:
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def create(self):
    """Create new Assessment Template object."""
    return self.api.post(all_models.AssessmentTemplate, {
        "assessment_template": {
            "audit": {"id": self.audit_id, "type": "Audit"},
            "context": None,
            "default_people": {
                "assignees": self.default_assignees,
                "verifiers": self.default_verifiers,
            },
            "title": "New Assessment Template"
        }
    })

  def read(self):
    """Read existing Assessment Template object."""
    return self.api.get(all_models.AssessmentTemplate, self.template_id)

  def update(self):
    """Update title of existing Assessment Template object."""
    template = all_models.AssessmentTemplate.query.get(self.template_id)
    return self.api.put(template, {"title": factories.random_str()})

  def delete(self):
    """Delete Assessment Template object."""
    template = all_models.AssessmentTemplate.query.get(self.template_id)
    return self.api.delete(template)

  def read_revisions(self):
    """Read revisions for Assessment Template object."""
    model_class = get_model("AssessmentTemplate")
    responses = []
    for query in ["source_type={}&source_id={}",
                  "destination_type={}&destination_id={}",
                  "resource_type={}&resource_id={}"]:
      responses.append(
          self.api.get_query(
              model_class,
              query.format("assessment_template", self.template_id)
          )
      )
    return responses
开发者ID:,项目名称:,代码行数:70,代码来源:

示例8: TaskGroupTaskRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class TaskGroupTaskRBACFactory(base.BaseRBACFactory):
  """Task Group Task RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Task Group Task permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    # pylint: disable=unused-argument
    self.setup_workflow_scope(user_id, acr)

    self.api = Api()

    if user_id:
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def create(self):
    """Create new Task Group Task object."""
    person = factories.PersonFactory()
    return self.api.post(all_models.TaskGroupTask, {
        "task_group_task": {
            "title": "New Task Group Task",
            "start_date": datetime.now().strftime("%Y-%m-%d"),
            "end_date": datetime.now().strftime("%Y-%m-%d"),
            "contact": person,
            "context": None,
            "task_group": {
                "id": self.task_group_id,
                "type": "Task Group",
            },
        }
    })

  def read(self):
    """Read existing Task Group Task object."""
    return self.api.get(all_models.TaskGroupTask, self.task_id)

  def update(self):
    """Update title of existing Task Group Task object."""
    task = all_models.TaskGroupTask.query.get(self.task_id)
    return self.api.put(task, {"title": factories.random_str()})

  def delete(self):
    """Delete Task Group Task object."""
    task = all_models.TaskGroupTask.query.get(self.task_id)
    return self.api.delete(task)

  def read_revisions(self):
    """Read revisions for Task Group Task object."""
    responses = []
    for query in ["source_type={}&source_id={}",
                  "destination_type={}&destination_id={}",
                  "resource_type={}&resource_id={}"]:
      responses.append(
          self.api.get_query(
              all_models.TaskGroupTask,
              query.format("task_group_task", self.task_id)
          )
      )
    return responses
开发者ID:egorhm,项目名称:ggrc-core,代码行数:66,代码来源:task_group_task.py

示例9: IssueRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class IssueRBACFactory(base.BaseRBACFactory):
  """Issue RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Issue permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    self.setup_program_scope(user_id, acr)

    with factories.single_commit():
      issue = factories.IssueFactory()
      if parent == "Audit":
        self.mapping_id = factories.RelationshipFactory(
            source=self.audit, destination=issue
        ).id
      elif parent == "Assessment":
        self.mapping_id = factories.RelationshipFactory(
            source=self.assessment, destination=issue
        ).id

    self.issue_id = issue.id
    self.parent = parent
    self.admin_acr_id = all_models.AccessControlRole.query.filter_by(
        name="Admin",
        object_type="Issue",
    ).one().id
    self.user_id = user_id
    self.api = Api()
    self.objgen = generator.ObjectGenerator()
    self.objgen.api = self.api

    if user_id:
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def create(self):
    """Create new Issue object."""
    return self.api.post(all_models.Issue, {
        "issue": {
            "access_control_list": [{
                "ac_role_id": self.admin_acr_id,
                "person": {
                    "id": self.user_id,
                    "type": "Person",
                }
            }],
            "title": factories.random_str(),
            "context": None,
        }
    })

  def read(self):
    """Read existing Issue object."""
    return self.api.get(all_models.Issue, self.issue_id)

  def update(self):
    """Update title of existing Issue object."""
    issue = all_models.Issue.query.get(self.issue_id)
    return self.api.put(issue, {"title": factories.random_str()})

  def delete(self):
    """Delete Issue object."""
    issue = all_models.Issue.query.get(self.issue_id)
    return self.api.delete(issue)

  def read_revisions(self):
    """Read revisions of Issue object."""
    model_class = get_model("Issue")
    responses = []
    for query in ["source_type={}&source_id={}",
                  "destination_type={}&destination_id={}",
                  "resource_type={}&resource_id={}"]:
      responses.append(
          self.api.get_query(
              model_class,
              query.format("issue", self.issue_id)
          )
      )
    return responses

  def map(self, issue=None):
    """Map Issue to parent object."""
    if self.parent == "Audit":
      parent = all_models.Audit.query.get(self.audit_id)
    else:
      parent = all_models.Assessment.query.get(self.assessment_id)
    map_issue = issue if issue else factories.IssueFactory()

    return self.objgen.generate_relationship(
        source=parent,
        destination=map_issue
    )[0]

  def create_and_map(self):
    """Create new Issue and map it to parent."""
    response = self.create()
#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:

示例10: SnapshotRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class SnapshotRBACFactory(base.BaseRBACFactory):
  """Snapshot RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Snapshot permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    self.setup_program_scope(user_id, acr)

    control = factories.ControlFactory()
    # pylint: disable=protected-access
    snapshot = TestCase._create_snapshots(self.audit, [control])[0]
    factories.RelationshipFactory(source=snapshot, destination=self.audit)
    factories.RelationshipFactory(source=control, destination=self.program)
    if parent == "Assessment":
      factories.RelationshipFactory(
          source=snapshot, destination=self.assessment
      )

    self.control_id = control.id
    self.snapshot_id = snapshot.id
    self.user_id = user_id

    self.api = Api()
    self.objgen = generator.ObjectGenerator()
    self.objgen.api = self.api

    if user_id:
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def _update_orig_obj(self):
    """Update title of original object of Snapshot."""
    snapshot = all_models.Snapshot.query.get(self.snapshot_id)
    original = get_model(snapshot.child_type).query.get(snapshot.child_id)
    # Assume that Admin is first in people table
    admin = all_models.Person.query.get(1)
    self.api.set_user(admin)
    self.api.put(original, {"title": factories.random_str()})
    user = all_models.Person.query.get(self.user_id)
    self.api.set_user(user)

  def read(self):
    """Read Snapshot object."""
    return self.api.get(all_models.Snapshot, self.snapshot_id)

  def read_original(self):
    """Read original object of Snapshot."""
    snapshot = all_models.Snapshot.query.get(self.snapshot_id)
    original = get_model(snapshot.child_type).query.get(snapshot.child_id)
    return self.api.get(original, original.id)

  def get_latest_version(self):
    """Get latest revisions for original object of Snapshot"""
    self._update_orig_obj()
    snapshot = all_models.Snapshot.query.get(self.snapshot_id)
    last_revision = db.session.query(
        sa.sql.func.max(all_models.Revision.id)
    ).filter(
        all_models.Revision.resource_type == snapshot.child_type,
        all_models.Revision.resource_id == snapshot.child_id,
    ).first()[0]
    return self.api.client.get(
        "api/revisions?id__in={}%2C{}".format(
            snapshot.revision.id, last_revision
        )
    )

  def update(self):
    """Update snapshot to the latest version."""
    self._update_orig_obj()
    snapshot = all_models.Snapshot.query.get(self.snapshot_id)
    return self.api.put(snapshot, {"update_revision": "latest"})
开发者ID:egorhm,项目名称:ggrc-core,代码行数:79,代码来源:snapshot.py

示例11: AuditRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class AuditRBACFactory(base.BaseRBACFactory):
  """Audit RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Audit permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    # pylint: disable=unused-argument
    self.setup_program_scope(user_id, acr, "Audit")

    self.api = Api()
    self.objgen = generator.ObjectGenerator()
    self.objgen.api = self.api

    self.admin_control_id = {
        name: id for id, name
        in access_control.role.get_custom_roles_for("Control").items()
    }["Admin"]
    if user_id:
      self.user_id = user_id
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def create(self):
    """Create new Audit object."""
    return self.api.post(all_models.Audit, {
        "audit": {
            "title": "New audit",
            "program": {"id": self.program_id},
            "context": None,
            "access_control_list": [],
        }
    })

  def read(self):
    """Read existing Audit object."""
    return self.api.get(all_models.Audit, self.audit_id)

  def update(self):
    """Update title of existing Audit object."""
    audit = all_models.Audit.query.get(self.audit_id)
    return self.api.put(audit, {"title": factories.random_str()})

  def delete(self):
    """Delete Audit object."""
    audit = all_models.Audit.query.get(self.audit_id)
    return self.api.delete(audit)

  def clone(self):
    """Clone existing Audit with Assessment Templates."""
    return self.api.post(all_models.Audit, {
        "audit": {
            "program": {"id": self.program_id, "type": "Program"},
            # workaround - title is required for validation
            "title": "",
            "context": None,
            "operation": "clone",
            "cloneOptions": {
                "sourceObjectId": self.audit_id,
                "mappedObjects": "AssessmentTemplate"
            }
        }
    })

  def read_revisions(self):
    """Read revisions for Audit object."""
    model_class = get_model("Audit")
    responses = []
    for query in ["source_type={}&source_id={}",
                  "destination_type={}&destination_id={}",
                  "resource_type={}&resource_id={}"]:
      responses.append(
          self.api.get_query(model_class, query.format("audit", self.audit_id))
      )
    return responses

  def map_external_control(self):
    """Map Control (on which current user don't have any rights) to Audit."""
    control = factories.ControlFactory()
    audit = all_models.Audit.query.get(self.audit_id)

    return self.objgen.generate_relationship(
        source=audit,
        destination=control,
    )[0]

  def map_control(self):
    """Map new snapshot of Control to Audit."""
    with factories.single_commit():
      control = factories.ControlFactory()
      acl = [
          acl
          for acl in control._access_control_list
          if acl.ac_role_id == self.admin_control_id
      ][0]
      factories.AccessControlPersonFactory(
#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:

示例12: TestEvidenceRolePropagation

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class TestEvidenceRolePropagation(TestCase):
  """Evidence role propagation test case"""
  # pylint: disable=invalid-name

  def setUp(self):
    super(TestEvidenceRolePropagation, self).setUp()
    self.api = Api()
    self.generator = ObjectGenerator()

  # Propagation isn't work for 'Primary Contacts', 'Secondary Contacts'
  # just add them to data list to check if fix works.

  @ddt.data("Assignees", "Creators", "Verifiers")
  def test_assessment_role_propagation_edit(self, role):
    """Asses user with role '{0}' should be able to edit related evidence"""

    _, reader = self.generator.generate_person(user_role="Creator")
    assignees_role = all_models.AccessControlRole.query.filter_by(
        object_type=all_models.Assessment.__name__, name=role
    ).first()

    with factories.single_commit():
      assessment = factories.AssessmentFactory()
      factories.AccessControlListFactory(
          ac_role=assignees_role,
          object=assessment,
          person=reader
      )
      evidence = factories.EvidenceFactory()
      evidence_id = evidence.id
      factories.RelationshipFactory(source=assessment, destination=evidence)

    self.api.set_user(reader)

    evidence = all_models.Evidence.query.get(evidence_id)
    new_description = 'new description'
    resp = self.api.modify_object(evidence, {'description': new_description})
    evidence = self.refresh_object(evidence)
    self.assert200(resp)
    self.assertEquals(new_description, evidence.description)
    self.assertEquals(reader.id, evidence.modified_by_id)

  @ddt.data("Audit Captains", "Auditors")
  def test_audit_role_propagation_edit(self, role):
    """Audit user with role '{0}' should be able to edit related evidence"""
    _, reader = self.generator.generate_person(user_role="Reader")
    assignees_role = all_models.AccessControlRole.query.filter_by(
        object_type=all_models.Audit.__name__, name=role
    ).first()
    with factories.single_commit():
      audit = factories.AuditFactory()
      factories.AccessControlListFactory(
          ac_role=assignees_role,
          object=audit,
          person=reader
      )
      evidence = factories.EvidenceFactory()
      evidence_id = evidence.id

    factories.RelationshipFactory(source=audit, destination=evidence)

    self.api.set_user(reader)

    evidence = all_models.Evidence.query.get(evidence_id)
    new_description = 'new description'
    resp = self.api.modify_object(evidence, {'description': new_description})
    evidence = self.refresh_object(evidence)
    self.assert200(resp)
    self.assertEquals(new_description, evidence.description)
    self.assertEquals(reader.id, evidence.modified_by_id)

  def test_audit_role_propagation_not_delete(self, role="Auditors"):
    """Audit user with role Auditors can NOT delete related evidence"""

    _, reader = self.generator.generate_person(user_role="Reader")
    assignees_role = all_models.AccessControlRole.query.filter_by(
        object_type=all_models.Audit.__name__, name=role
    ).first()
    with factories.single_commit():
      audit = factories.AuditFactory()
      factories.AccessControlListFactory(
          ac_role=assignees_role,
          object=audit,
          person=reader
      )
      evidence = factories.EvidenceFactory()
      evidence_id = evidence.id

    factories.RelationshipFactory(source=audit, destination=evidence)

    self.api.set_user(reader)
    evidence = all_models.Evidence.query.get(evidence_id)

    resp = self.api.delete(evidence)
    self.assertStatus(resp, 403)
    evidence = all_models.Evidence.query.get(evidence_id)
    self.assertTrue(evidence)
开发者ID:egorhm,项目名称:ggrc-core,代码行数:99,代码来源:test_evidence_role_propagation.py

示例13: TaskGroupRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class TaskGroupRBACFactory(base.BaseRBACFactory):
  """Task Group RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Task Group permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    # pylint: disable=unused-argument
    self.setup_workflow_scope(user_id, acr)

    self.admin_control_id = {
        name: id_ for id_, name
        in access_control.role.get_custom_roles_for("Control").items()
    }["Admin"]
    self.api = Api()

    if user_id:
      self.user_id = user_id
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def create(self):
    """Create new Task Group object."""
    person = factories.PersonFactory()
    return self.api.post(all_models.TaskGroup, {
        "task_group": {
            "contact": {
                "id": person.id,
                "type": "Person",
            },
            "title": "New Task Group",
            "context": None,
            "workflow": {
                "id": self.workflow_id,
                "type": "Workflow",
            },
        }
    })

  def read(self):
    """Read existing Task Group object."""
    return self.api.get(all_models.TaskGroup, self.task_group_id)

  def update(self):
    """Update title of existing Task Group object."""
    task_group = all_models.TaskGroup.query.get(self.task_group_id)
    return self.api.put(task_group, {"title": factories.random_str()})

  def delete(self):
    """Delete Task Group object."""
    task_group = all_models.TaskGroup.query.get(self.task_group_id)
    return self.api.delete(task_group)

  def read_revisions(self):
    """Read revisions for Task Group object."""
    responses = []
    for query in ["source_type={}&source_id={}",
                  "destination_type={}&destination_id={}",
                  "resource_type={}&resource_id={}"]:
      responses.append(
          self.api.get_query(
              all_models.TaskGroup,
              query.format("task_group", self.task_group_id)
          )
      )
    return responses

  def map_control(self):
    """Map Control on which user don't have any rights to Cycle Task."""
    task_group = all_models.TaskGroup.query.get(self.task_group_id)
    control = factories.ControlFactory()
    return self.api.post(all_models.TaskGroupObject, {
        "task_group_object": {
            "context": None,
            "object": {
                "id": control.id,
                "type": "Control",
            },
            "task_group": {
                "id": task_group.id,
                "type": "TaskGroup",
            },
        }
    })

  def map_created_control(self):
    """Map Control that was created by user to Cycle Task."""
    task_group = all_models.TaskGroup.query.get(self.task_group_id)
    with factories.single_commit():
      control = factories.ControlFactory()
      factories.AccessControlListFactory(
          ac_role_id=self.admin_control_id,
          object_id=control.id,
          object_type="Control",
          person_id=self.user_id
      )
#.........这里部分代码省略.........
开发者ID:egorhm,项目名称:ggrc-core,代码行数:103,代码来源:task_group.py

示例14: AssessmentRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class AssessmentRBACFactory(base.BaseRBACFactory):
  """Assessment RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Assessment permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    self.setup_program_scope(user_id, acr, parent)

    self.api = Api()
    self.objgen = generator.ObjectGenerator()
    self.objgen.api = self.api

    if user_id:
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def create(self):
    """Create new Assessment object."""
    return self.api.post(all_models.Assessment, {
        "assessment": {
            "title": "New Assessment",
            "context": None,
            "audit": {"id": self.audit_id},
        },
    })

  def generate(self):
    """Generate new Assessment object."""
    with factories.single_commit():
      control = factories.ControlFactory()
      template_id = factories.AssessmentTemplateFactory().id
    audit = all_models.Audit.query.get(self.audit_id)
    # pylint: disable=protected-access
    snapshot = TestCase._create_snapshots(audit, [control])[0]
    snapshot_id = snapshot.id
    factories.RelationshipFactory(source=snapshot, destination=audit)

    responses = []
    asmnt_data = {
        "assessment": {
            "_generated": True,
            "audit": {
                "id": self.audit_id,
                "type": "Audit"
            },
            "object": {
                "id": snapshot_id,
                "type": "Snapshot"
            },
            "context": None,
            "title": "New assessment",
        }
    }
    responses.append(self.api.post(all_models.Assessment, asmnt_data))

    asmnt_data["assessment"]["template"] = {
        "id": template_id,
        "type": "AssessmentTemplate"
    }
    responses.append(self.api.post(all_models.Assessment, asmnt_data))
    return responses

  def read(self):
    """Read existing Assessment object."""
    return self.api.get(all_models.Assessment, self.assessment_id)

  def update(self):
    """Update title of existing Assessment object."""
    asmnt = all_models.Assessment.query.get(self.assessment_id)
    return self.api.put(asmnt, {"title": factories.random_str()})

  def delete(self):
    """Delete Assessment object."""
    asmnt = all_models.Assessment.query.get(self.assessment_id)
    return self.api.delete(asmnt)

  def read_revisions(self):
    """Read revisions for Assessment object."""
    model_class = get_model("Assessment")
    responses = []
    for query in ["source_type={}&source_id={}",
                  "destination_type={}&destination_id={}",
                  "resource_type={}&resource_id={}"]:
      responses.append(
          self.api.get_query(
              model_class,
              query.format("assessment", self.assessment_id)
          )
      )
    return responses

  def map_snapshot(self):
    """Map snapshot to assessment."""
    audit = all_models.Audit.query.get(self.audit_id)
    assessment = all_models.Assessment.query.get(self.assessment_id)
#.........这里部分代码省略.........
开发者ID:egorhm,项目名称:ggrc-core,代码行数:103,代码来源:assessment.py

示例15: DocumentReferenceUrlRBACFactory

# 需要导入模块: from integration.ggrc import Api [as 别名]
# 或者: from integration.ggrc.Api import set_user [as 别名]
class DocumentReferenceUrlRBACFactory(base.BaseRBACFactory):
  """Document Reference Url RBAC factory class."""

  def __init__(self, user_id, acr, parent=None):
    """Set up objects for Document permission tests.

    Args:
        user_id: Id of user under which all operations will be run.
        acr: Instance of ACR that should be assigned for tested user.
        parent: Model name in scope of which objects should be set up.
    """
    self.api = Api()
    self.objgen = generator.ObjectGenerator()
    self.objgen.api = self.api

    self.acr = acr
    self.user_id = user_id
    self.parent_name = parent
    self.document_id = None
    self.parent = None
    self.parent_id = None
    self.admin_acr_id = all_models.AccessControlRole.query.filter_by(
        name="Admin",
        object_type="Document",
    ).one().id

    self.setup_models(self.parent_name)
    self.set_user(user_id)

  def set_user(self, user_id):
    """Set user to send requests"""
    if self.user_id:
      user = all_models.Person.query.get(user_id)
      self.api.set_user(user)

  def setup_models(self, parent_name):
    """Setup document, parent, relationship"""
    with factories.single_commit():
      document = factories.DocumentReferenceUrlFactory()
      self.document_id = document.id
      self.parent = self.build_parent(parent_name)
      self.parent_id = self.parent.id
      factories.RelationshipFactory(source=self.parent, destination=document)
      self.assign_person(self.parent, self.acr, self.user_id)

  @staticmethod
  def build_parent(parent_name):
    """Create parent based on Name"""
    try:
      parent = FACTORIES_MAPPING[parent_name]()
    except KeyError():
      raise ValueError("Unknown parent {}".format(parent_name))
    return parent

  def create(self):
    """Create new Document object."""
    result = self.api.post(all_models.Document, {
        "document": {
            "access_control_list": [{
                "ac_role_id": self.admin_acr_id,
                "person": {
                    "id": self.user_id,
                    "type": "Person",
                }
            }],
            "link": factories.random_str(),
            "title": factories.random_str(),
            "context": None,
        }
    })
    return result

  def read(self):
    """Read existing Document object."""
    res = self.api.get(all_models.Document, self.document_id)
    return res

  def update(self):
    """Update title of existing Document object."""
    document = all_models.Document.query.get(self.document_id)
    return self.api.put(document, {"title": factories.random_str()})

  def delete(self):
    """Delete Document object."""
    document = all_models.Document.query.get(self.document_id)
    return self.api.delete(document)

  def map(self, document=None):
    """Map Document to parent object."""
    parent = self.parent.__class__.query.get(self.parent_id)
    map_document = document if document \
        else factories.DocumentReferenceUrlFactory()

    return self.objgen.generate_relationship(
        source=parent,
        destination=map_document
    )[0]

  def create_and_map(self):
    """Create new Document and map it to parent."""
#.........这里部分代码省略.........
开发者ID:egorhm,项目名称:ggrc-core,代码行数:103,代码来源:document.py


注:本文中的integration.ggrc.Api.set_user方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。