Example #1
0
    def test__has_access_to_location(self):
        location = Location("i4x://edX/toy/course/2012_Fall")

        self.assertFalse(access._has_access_to_location(None, location, "staff", None))
        u = Mock()
        u.is_authenticated.return_value = False
        self.assertFalse(access._has_access_to_location(u, location, "staff", None))
        u = Mock(is_staff=True)
        self.assertTrue(access._has_access_to_location(u, location, "instructor", None))
        # A user has staff access if they are in the staff group
        u = Mock(is_staff=False)
        g = Mock()
        g.name = "staff_edX/toy/2012_Fall"
        u.groups.all.return_value = [g]
        self.assertTrue(access._has_access_to_location(u, location, "staff", None))
        # A user has staff access if they are in the instructor group
        g.name = "instructor_edX/toy/2012_Fall"
        self.assertTrue(access._has_access_to_location(u, location, "staff", None))

        # A user has instructor access if they are in the instructor group
        g.name = "instructor_edX/toy/2012_Fall"
        self.assertTrue(access._has_access_to_location(u, location, "instructor", None))

        # A user does not have staff access if they are
        # not in either the staff or the the instructor group
        g.name = "student_only"
        self.assertFalse(access._has_access_to_location(u, location, "staff", None))

        # A user does not have instructor access if they are
        # not in the instructor group
        g.name = "student_only"
        self.assertFalse(access._has_access_to_location(u, location, "instructor", None))
    def test_create_resource(self):
        # Create ResourceType
        rt = Mock()
        rt.name = "bad name"
        with self.assertRaises(BadRequest):
            self.rms.create_resource_type(rt, "123")

        rt.name = "good_name"
        bad_object_id = None
        with self.assertRaises(BadRequest):
            self.rms.create_resource_type(rt, bad_object_id)

        # Create ObjectType
        ot = Mock()
        ot.definition = self.object_definition
        ot.name = "good_name"
        ot.description = "This is just a test. No need to panic"

        self.rms.clients.resource_registry.read.return_value = ot
        resource_id_return_value = "123"
        version_return_value = 1
        self.rms.clients.resource_registry.create.return_value = [resource_id_return_value, version_return_value]
        self.rms.clients.resource_registry.create_association.return_value = "999"

        object_id = "444"
        resource_id = self.rms.create_resource_type(rt, object_id)
        self.assertEqual(resource_id, "123")

        self.rms.clients.resource_registry.read.assert_called_once_with(object_id, "")
        self.rms.clients.resource_registry.create.assert_called_once_with(rt)
        self.rms.clients.resource_registry.create_association.assert_called_once_with(
            resource_id_return_value, PRED.hasObjectType, object_id, "H2H"
        )
Example #3
0
    def test_traverse_bucket(self, *mocks):
        def ret_sample(population, offset=1):
            if population and offset == 1:
                # sample keys
                return [population[0]]
            else:
                return population

        with patch("plugins.S3AclPlugin.sample_population", side_effect=ret_sample) as MockClass:
            bucket = Mock()
            bucket.name = "bucket1"
            prefix = Mock()
            prefix.name = "prefix"
            key = Mock(Key)
            key.name = "key1"
            key2 = Mock(Key)
            key2.name = "key2"

            def ret_list(pref, slash):
                if pref == "":
                    return [key, prefix, key2]
                else:
                    return []

            bucket.list.side_effect = ret_list

            self.plugin.init(Mock(), {"user": "bob", "key": "xxx"}, {})
            self.assertEqual(self.plugin.traverse_bucket(bucket, ""), [key])
Example #4
0
    def test_responder_call_hashcat(self, mock_os, mock_subprocess):
        self.handler.accept_eula = Mock()
        self.handler.get_configs = Mock()
        self.handler.get_configs.return_value = ["hashcat", "ruleset", "wordlist"]

        outfile = Mock()
        outfile.name = "outfile"
        self.handler.get_outfile = Mock()
        self.handler.get_outfile.return_value = outfile

        junkfile = Mock()
        junkfile.name = "junkfile"
        self.handler.get_junkfile = Mock()
        self.handler.get_junkfile.return_value = junkfile

        tempfile = Mock()
        tempfile.name = "tempfile"

        self.handler.get_tempfile = Mock()
        self.handler.get_tempfile.return_value = tempfile

        self.handler.outpath = "outpath"

        mock_os.path = Mock()
        mock_os.path.exists.return_value = True

        mock_subprocess.Popen = Mock()

        self.handler.call_hashcat("5600", "SMB-NTLMv2.txt")

        self.assertEqual(
            ["hashcat", "-m", "5600", "-r", "ruleset", "-o", "outfile", "junkfile", "wordlist"],
            mock_subprocess.Popen.call_args[0][0],
        )
Example #5
0
    def test_dirty_save(self):
        age_field = Mock()
        age_field.name = "age"
        age_field.value_to_string.return_value = 30

        name_field = Mock()
        name_field.name = "name"
        name_field.value_to_string.return_value = "Bob"

        class DirtyUser(mock_orm.Model):
            _fields = [age_field, name_field]
            pk = 3

        class DirtyUserResource(resources.ModelResource):
            parent_resource_path = "users"
            model_class = DirtyUser

            fields = [
                fields.AttributeField(attribute="name", type=str),
                fields.AttributeField(attribute="age", type=int),
            ]

        dirty_user = DirtyUser()
        dirty_user.save = Mock()
        dirty_user.is_dirty = lambda: True
        resource = DirtyUserResource(dirty_user)

        resource.put(mock_context(), {"name": "Bob", "age": 30, "resourceUri": "uri://users/1"})
        self.assertTrue(dirty_user.save.called)
Example #6
0
    def test_do_run(self, *mocks):

        key1 = Mock(Key)
        key1.name = "key1"
        key1.bucket = Mock()
        key1.bucket.name = "bucket1"
        key2 = Mock(Key)
        key2.name = "key2"
        key2.bucket = Mock()
        key2.bucket.name = "bucket1"

        def ret_keys(key):
            if key == key1:
                return ["id permission"]
            return []

        with patch("plugins.S3AclPlugin.traverse_bucket", return_value=[key1, key2]) as MockClass:
            with patch("plugins.S3AclPlugin.suspicious_grants", side_effect=ret_keys):

                self.plugin.init(Mock(), {"user": "bob", "key": "xxx"}, {})
                # run the tested method
                self.assertEqual(
                    list(self.plugin.do_run(MagicMock())),
                    [{"details": ["id permission"], "id": "bucket1:key1", "plugin_name": "s3acl"}],
                )
    def test_repo_groups(self):
        line_evaluator = Mock()
        line_evaluator.key = "line"
        line_evaluator.matches = Mock(return_value=True)

        rule = Mock()
        rule.name = "os_code_exec::python"
        rule.evaluators = [line_evaluator]

        junk_repo = Mock()
        junk_repo.name = "junk"
        local_repo = Mock()
        local_repo.name = "tooling"

        repo_groups = {"skipped_repos": ["junk"], "local_repos": ["tooling"]}
        rules_to_groups = {
            "skipped_repos": [{"except": ".*"}],
            "local_repos": [{"match": ".*"}, {"except": "os_code_exec::.*"}],
        }

        code_checker = CodeChecker(
            context_processors=[], rules=[rule], repo_groups=repo_groups, rules_to_groups=rules_to_groups
        )
        check_context = {"filename": "macbeth.txt"}

        self.assertEquals(code_checker.check(lines=self.code, context=check_context, repo=junk_repo), [])
        self.assertEquals(code_checker.check(lines=self.code, context=check_context, repo=local_repo), [])
Example #8
0
    def test_node_remove_specific_host(self, m_client, m_cont_running, m_veth):
        """
        Test the client removes the specific host when node_remove called, and
        that endpoints are removed when remove_endpoints flag is set.
        """
        # Call method under test
        endpoint1 = Mock()
        endpoint1.name = "vethname1"
        endpoint1.ipv4_nets = {IPNetwork("1.2.3.4/32")}
        endpoint1.ipv6_nets = set()
        endpoint2 = Mock()
        endpoint2.name = "vethname2"
        endpoint2.ipv4_nets = set()
        endpoint2.ipv6_nets = set()
        m_client.get_endpoints.return_value = [endpoint1, endpoint2]
        # This should not cause a failure with specific host
        m_cont_running.return_value = True
        node.node_remove(True, "other-host")

        # Assert
        m_client.get_endpoints.assert_called_once_with(hostname="other-host")
        m_client.release_ips.assert_called_once_with({IPAddress("1.2.3.4")})
        m_client.remove_ipam_host.assert_called_once_with("other-host")
        m_client.remove_host.assert_called_once_with("other-host")
        m_veth.assert_has_calls([call("vethname1"), call("vethname2")])
Example #9
0
    def test_server_sends_marshaled_exception_when_callback_raises_exception(self, mock_command_response):
        request = '{"name": "foobar", "arg": {"arg1": "value"}}'

        expected = '{"error": "raise me!", "value": null}'

        command_response = Mock(CommandResponse)
        command_response.error = "raise me!"
        command_response.value = None
        mock_command_response.return_value = command_response
        callback = Mock(side_effect=BusCtlServerError())

        marshaler = Mock(Marshaler)
        server = BusCtlServer()
        server._marshaler = marshaler

        command = Mock()
        command.name = "foobar"
        marshaler.unmarshal_command.return_value = command
        marshaler.marshal_response.return_value = expected

        command_class = Mock()
        command_class.name = "foobar"

        server.add_command(command_class, callback)

        response = server._process_next_command(request)

        self.assertEqual(response, expected)
        marshaler.marshal_response.assert_called_once_with(command_response)
Example #10
0
    def test_restructure_layout_preferences_forwards(self):

        empty_workspace = Mock()
        empty_workspace_layout_pref = Mock()
        empty_workspace_layout_preferences = TestQueryResult([])
        empty_workspace.workspacepreference_set.filter.side_effect = (
            lambda **kwargs: empty_workspace_layout_pref
            if kwargs.get("name") == "layout"
            else empty_workspace_layout_preferences
        )
        empty_workspace.tab_set.all.return_value = TestQueryResult([])

        workspace = Mock()
        workspace_layout_pref = Mock()
        workspace_columns_pref = Mock()
        workspace_columns_pref.name = "columns"
        workspace_columns_pref.value = 15
        workspace_layout_preferences = TestQueryResult([workspace_columns_pref])
        workspace.workspacepreference_set.filter.side_effect = (
            lambda **kwargs: workspace_layout_pref
            if kwargs.get("name", "") == "layout"
            else workspace_layout_preferences
        )

        workspace_tab = Mock()
        workspace_tab_layout_pref = Mock()
        workspace_tab_columns_pref = Mock()
        workspace_tab_columns_pref.name = "columns"
        workspace_tab_columns_pref.value = 15
        workspace_tab_layout_preferences = TestQueryResult([workspace_tab_columns_pref])
        workspace_tab.tabpreference_set.filter.side_effect = (
            lambda **kwargs: workspace_tab_layout_pref
            if kwargs.get("name", "") == "layout"
            else workspace_tab_layout_preferences
        )

        workspace_empty_tab = Mock()
        workspace_empty_tab_layout_pref = Mock()
        workspace_empty_tab_layout_preferences = TestQueryResult([])
        workspace_empty_tab.tabpreference_set.filter.side_effect = (
            lambda **kwargs: workspace_empty_tab_layout_pref
            if kwargs.get("name", "") == "layout"
            else workspace_empty_tab_layout_preferences
        )
        workspace.tab_set.all.return_value = TestQueryResult([workspace_empty_tab, workspace_tab])

        migration = self._pick_migration("0016_restructure_layout_preferences")
        orm = Mock(autospec=migration.orm())
        orm.Workspace.objects.all.return_value = TestQueryResult([empty_workspace, workspace])
        migration.migration_instance().forwards(orm)

        self.assertTrue(empty_workspace_layout_pref.update.called)
        self.assertEqual(empty_workspace_layout_preferences.delete.call_count, 0)
        self.assertFalse(empty_workspace.workspacepreference_set.create.called)

        self.assertTrue(workspace_layout_pref.update.called)
        self.assertTrue(workspace_layout_preferences.delete.called)
        self.assertTrue(workspace_tab_layout_preferences.delete.called)
        self.assertFalse(workspace_empty_tab_layout_preferences.delete.called)
        self.assertTrue(workspace.workspacepreference_set.create.called)
Example #11
0
def test_print_instance(colorize):
    colorize.return_value = "fancy-cloud"

    # as name is an argument in the Mock constructor
    # we have to set it on an instance
    group1 = Mock()
    group1.name = "group1"
    group2 = Mock()
    group2.name = "group2"
    groups = [group1, group2]

    instance = Mock(
        name="cloud",
        instance_type="fancy",
        status="happy",
        tags={"owner": "ofs"},
        launch_time=datetime.datetime(2000, 01, 01),
        groups=groups,
        availability_zone="cloud-zone",
    )

    expected = ["fancy-cloud", "fancy", "fancy-cloud", "ofs", "fancy-cloud", "group1,group2", "cloud-zone"]
    result = print_instance_summary(instance)

    assert result == expected
Example #12
0
    def testGetSuggestedInstancesTwoDifferentSize(self, getELBInstancesMock):
        region = "us-west-2"
        # Instance 1
        instanceMock1 = Mock(spec="boto.ec2.elb.load_balancer.LoadBalancer")
        instanceMock1.name = "testName1"
        instanceMock1.instances = ["a", "b"]
        # Instance 2
        instanceMock2 = Mock(spec="boto.ec2.elb.load_balancer.LoadBalancer")
        instanceMock2.name = "testName2"
        instanceMock2.instances = ["c", "d", "e"]

        getELBInstancesMock.return_value = [instanceMock1, instanceMock2]

        suggestions = elb_utils.getSuggestedInstances(region)
        self.assertIsInstance(suggestions, types.GeneratorType)
        suggestions = list(suggestions)

        self.assertSequenceEqual(
            suggestions,
            [
                {"id": "testName2", "name": "testName2", "namespace": "AWS/ELB", "region": region},
                {"id": "testName1", "name": "testName1", "namespace": "AWS/ELB", "region": region},
            ],
        )
        getELBInstancesMock.assert_call_once_with(region)
Example #13
0
    def test_resource_offers_creates_nodes(self, mock_get_slave):
        mock_get_slave.return_value = SlaveInfo(u"localhost", 5151)
        mock_cpu = Mock()
        mock_cpu.name = u"cpus"
        mock_cpu.value = 10

        mock_disk = Mock()
        mock_disk.name = u"disk"
        mock_disk.value = 4000

        mock_mem = Mock()
        mock_mem.name = u"mem"
        mock_mem.value = 100000

        mock_offer = Mock()
        mock_offer.id.value = 1
        mock_offer.slave_id.value = 1
        mock_offer.hostname.value = u"localhost"
        mock_offer.resources = [mock_cpu, mock_disk, mock_mem]
        offers = [mock_offer]

        my_scheduler, driver, master_info = self._get_mocked_scheduler_driver_master()

        localhost_exists = Node.objects.filter(hostname=u"localhost").exists()
        self.assertFalse(localhost_exists, "there should not be a node before the first offer")
        my_scheduler.resourceOffers(driver, offers)
        localhost_exists = Node.objects.all().exists()
        self.assertTrue(localhost_exists, "there should be a node after the first offer")
    def test_map_plugin_packets(self, mock_config, mock_path, mock_sys):
        mock_plugin = Mock()
        mock_plugin.name = "Test"
        mock_plugin.overridden_packets = {1: {"on": "add me on 1", "after": "add me after 1"}}
        mock_plugin2 = Mock()
        mock_plugin2.name = "Test2"
        mock_plugin2.overridden_packets = {2: {"on": "add me on 2"}, 3: {"after": "add me after 2"}}

        pm = PluginManager(Mock())
        pm.map_plugin_packets(mock_plugin)

        self.assertDictEqual(
            pm.packets,
            {1: {"on": {"Test": (mock_plugin, "add me on 1")}, "after": {"Test": (mock_plugin, "add me after 1")}}},
        )

        pm.map_plugin_packets(mock_plugin2)
        self.assertDictEqual(
            pm.packets,
            {
                1: {"on": {"Test": (mock_plugin, "add me on 1")}, "after": {"Test": (mock_plugin, "add me after 1")}},
                2: {"on": {"Test2": (mock_plugin2, "add me on 2")}},
                3: {"after": {"Test2": (mock_plugin2, "add me after 2")}},
            },
        )
Example #15
0
  def testGetSuggestedInstancesTwoDifferentSize(self, getAutoScalingGroupsMock):
    region = "us-west-2"
    # Instance 1
    instanceMock1 = Mock(spec="boto.ec2.auto_scale.group.AutoScalingGroup")
    instanceMock1.name = "testName1"
    instanceMock1.desired_capacity = 64
    # Instance 2
    instanceMock2 = Mock(spec="boto.ec2.auto_scale.group.AutoScalingGroup")
    instanceMock2.name = "testName2"
    instanceMock2.desired_capacity = 65

    getAutoScalingGroupsMock.return_value = [
        instanceMock1,
        instanceMock2,
    ]

    suggestions = asg_utils.getSuggestedInstances(region)
    self.assertIsInstance(suggestions, types.GeneratorType)
    suggestions = list(suggestions)

    self.assertSequenceEqual(suggestions, [
        {"id": "testName2", "name": "testName2", "namespace": "AWS/AutoScaling",
         "region": region},
        {"id": "testName1", "name": "testName1", "namespace": "AWS/AutoScaling",
         "region": region},
    ])
    getAutoScalingGroupsMock.assert_call_once_with(region)
Example #16
0
def test_batch_norm_macro():
    from lasagne.layers import Layer, BatchNormLayer, batch_norm, NonlinearityLayer
    from lasagne.nonlinearities import identity

    input_shape = (2, 3)
    obj = object()

    # check if it steals the nonlinearity
    layer = Mock(Layer, output_shape=input_shape, nonlinearity=obj)
    bnstack = batch_norm(layer)
    assert isinstance(bnstack, NonlinearityLayer)
    assert isinstance(bnstack.input_layer, BatchNormLayer)
    assert layer.nonlinearity is identity
    assert bnstack.nonlinearity is obj

    # check if it removes the bias
    layer = Mock(Layer, output_shape=input_shape, b=obj, params={obj: set()})
    bnstack = batch_norm(layer)
    assert isinstance(bnstack, BatchNormLayer)
    assert layer.b is None
    assert obj not in layer.params

    # check if it can handle an unset bias
    layer = Mock(Layer, output_shape=input_shape, b=None, params={obj: set()})
    bnstack = batch_norm(layer)
    assert isinstance(bnstack, BatchNormLayer)
    assert layer.b is None

    # check if it passes on kwargs
    layer = Mock(Layer, output_shape=input_shape)
    bnstack = batch_norm(layer, name="foo")
    assert isinstance(bnstack, BatchNormLayer)
    assert bnstack.name == "foo"

    # check if created layers are named with kwargs name
    layer = Mock(Layer, output_shape=input_shape, nonlinearity=obj)
    layer.name = "foo"
    bnstack = batch_norm(layer, name="foo_bnorm")
    assert isinstance(bnstack, NonlinearityLayer)
    assert isinstance(bnstack.input_layer, BatchNormLayer)
    assert bnstack.name == "foo_bnorm_nonlin"
    assert bnstack.input_layer.name == "foo_bnorm"

    # check if created layers are named with wrapped layer name
    layer = Mock(Layer, output_shape=input_shape, nonlinearity=obj)
    layer.name = "foo"
    bnstack = batch_norm(layer)
    assert isinstance(bnstack, NonlinearityLayer)
    assert isinstance(bnstack.input_layer, BatchNormLayer)
    assert bnstack.name == "foo_bn_nonlin"
    assert bnstack.input_layer.name == "foo_bn"

    # check if created layers remain unnamed if no names are given
    layer = Mock(Layer, output_shape=input_shape, nonlinearity=obj)
    bnstack = batch_norm(layer)
    assert isinstance(bnstack, NonlinearityLayer)
    assert isinstance(bnstack.input_layer, BatchNormLayer)
    assert bnstack.name is None
    assert bnstack.input_layer.name is None
    def test_should_get_group_from_nova_security_group_manager_when_multiple_groups_present(self):
        security_group1 = Mock()
        security_group1.name = "secGroup"
        security_group2 = Mock()
        security_group2.name = "otherGroup"
        self.security_group_manager.list.return_value = [security_group1, security_group2]

        self.assertEqual(self.openstack_group_service.get_group(security_group2.name), security_group2)
Example #18
0
 def test_get_sources(self, get_source_map):
     get_source_map.return_value = {"system": ["foo"]}
     system = Mock()
     system.name = "system"
     eq_(sources.get_sources(system), ["foo"])
     system = Mock()
     system.name = "bar"
     eq_(sources.get_sources(system), [])
Example #19
0
 def setUp(self):
     super(PXCClusterTasksTest, self).setUp()
     util.init_db()
     self.cluster_id = "1232"
     self.cluster_name = "Cluster-1234"
     self.tenant_id = "6789"
     self.db_cluster = DBCluster(
         ClusterTaskStatus.NONE,
         id=self.cluster_id,
         created=str(datetime.date),
         updated=str(datetime.date),
         name=self.cluster_name,
         task_id=ClusterTaskStatus.NONE._code,
         tenant_id=self.tenant_id,
         datastore_version_id="1",
         deleted=False,
     )
     self.dbinst1 = DBInstance(
         InstanceTasks.NONE,
         id="1",
         name="member1",
         compute_instance_id="compute-1",
         task_id=InstanceTasks.NONE._code,
         task_description=InstanceTasks.NONE._db_text,
         volume_id="volume-1",
         datastore_version_id="1",
         cluster_id=self.cluster_id,
         type="member",
     )
     self.dbinst2 = DBInstance(
         InstanceTasks.NONE,
         id="2",
         name="member2",
         compute_instance_id="compute-2",
         task_id=InstanceTasks.NONE._code,
         task_description=InstanceTasks.NONE._db_text,
         volume_id="volume-2",
         datastore_version_id="1",
         cluster_id=self.cluster_id,
         type="member",
     )
     self.dbinst3 = DBInstance(
         InstanceTasks.NONE,
         id="3",
         name="member3",
         compute_instance_id="compute-3",
         task_id=InstanceTasks.NONE._code,
         task_description=InstanceTasks.NONE._db_text,
         volume_id="volume-3",
         datastore_version_id="1",
         cluster_id=self.cluster_id,
         type="member",
     )
     mock_ds1 = Mock()
     mock_ds1.name = "pxc"
     mock_dv1 = Mock()
     mock_dv1.name = "7.1"
     self.clustertasks = ClusterTasks(Mock(), self.db_cluster, datastore=mock_ds1, datastore_version=mock_dv1)
Example #20
0
    def test_buildsetComplete_sends_email(self):
        fakeBuildMessage = Mock()
        mn = MailNotifier(
            "from@example.org",
            buildSetSummary=True,
            mode=("failing", "passing", "warnings"),
            builders=["Builder1", "Builder2"],
        )

        mn.buildMessage = fakeBuildMessage

        builder1 = Mock()
        builder1.getBuild = lambda number: build1
        builder1.name = "Builder1"

        build1 = FakeBuildStatus()
        build1.results = FAILURE
        build1.finished = True
        build1.reason = "testReason"
        build1.getBuilder.return_value = builder1
        build1.getResults.return_value = build1.results

        builder2 = Mock()
        builder2.getBuild = lambda number: build2
        builder2.name = "Builder2"

        build2 = FakeBuildStatus()
        build2.results = FAILURE
        build2.finished = True
        build2.reason = "testReason"
        build2.getBuilder.return_value = builder1
        build2.getResults.return_value = build2.results

        def fakeGetBuilder(buildername):
            return {"Builder1": builder1, "Builder2": builder2}[buildername]

        self.db = fakedb.FakeDBConnector(self)
        self.db.insertTestData(
            [
                fakedb.SourceStampSet(id=127),
                fakedb.Buildset(id=99, sourcestampsetid=127, results=SUCCESS, reason="testReason"),
                fakedb.BuildRequest(id=11, buildsetid=99, buildername="Builder1"),
                fakedb.Build(number=0, brid=11),
                fakedb.BuildRequest(id=12, buildsetid=99, buildername="Builder2"),
                fakedb.Build(number=0, brid=12),
            ]
        )
        mn.master = self  # FIXME: Should be FakeMaster

        self.status = Mock()
        mn.master_status = Mock()
        mn.master_status.getBuilder = fakeGetBuilder
        mn.buildMessageDict = Mock()
        mn.buildMessageDict.return_value = {"body": "body", "type": "text", "subject": "subject"}

        mn._buildsetComplete(99, FAILURE)
        fakeBuildMessage.assert_called_with("(whole buildset)", [build1, build2], SUCCESS)
Example #21
0
    def test_get_a_local_process(self):
        pmock = Mock()
        pmock.name = sentinel.name
        pmock2 = Mock()
        pmock2.name = sentinel.name2

        self.pm.procs = {"one": pmock, "two": pmock2}

        self.assertEquals(self.pm.get_a_local_process(sentinel.name2), pmock2)
Example #22
0
    def test_given_a_document_then_returns_a_list_of_field_names(self):
        field1 = Mock(Field)
        field1.name = "field1"

        field2 = Mock(Field)
        field2.name = "field2"

        document = Document([field1, field2])

        assert_that(document.field_names(), contains("field1", "field2"))
Example #23
0
 def test_got_csrf(self):
     cookie1 = Mock()
     cookie1.name = "csrftoken"
     cookie1.value = "csrf value 1"
     cookie1.domain = "other domain"
     cookie2 = Mock()
     cookie2.name = "csrftoken"
     cookie2.value = "csrf value 2"
     cookie2.domain = "test.trigger.io"
     self.remote.cookies = [cookie1, cookie2]
     eq_(self.remote._csrf_token(), "csrf value 2")
Example #24
0
 def test_get_an_element_by_name(self):
     repo = EntityRepo()
     in_element1 = Mock()
     in_element1.id_ = "fake_id1"
     in_element1.name = "fake_name1"
     repo.add(in_element1)
     in_element2 = Mock()
     in_element2.id_ = "fake_id2"
     in_element2.name = "fake_name2"
     repo.add(in_element2)
     self.assertEqual(repo.get_by_name("fake_name1"), in_element1)
Example #25
0
    def test_get_backend(self, get_backend_map):
        get_backend_map.return_value = {"system": {"env": "foo"}}

        env = Mock()
        env.name = "env"
        env.system = Mock()
        env.system.name = "system"
        eq_(backends.get_backend(env), "foo")
        env.name = "foo"
        eq_(backends.get_backend(env), None)
        env.system.name = "foo"
        eq_(backends.get_backend(env), None)
    def test_should_allow_authorized_users_to_add_admin_unit(self):
        request = Mock()
        mock_user = Mock()
        mock_user.is_superuser = True

        mock_admin_group = Mock()
        mock_editor_group = Mock()
        mock_admin_group.name = "admin"
        mock_editor_group.name = "editors_publishers"
        mock_user.groups.all.return_value = [mock_admin_group, mock_editor_group]

        request.user = mock_user
        self.assertTrue(project_tags.add_admin_unit_related_links(mock_user).__contains__("/add_admin_unit"))
    def test_return_404_response_if_resource_is_not_found(self):
        request = Mock()
        mock_user = Mock()
        mock_admin_group = Mock()
        mock_editor_group = Mock()
        mock_admin_group.name = "admin"
        mock_editor_group.name = "editors_publishers"
        mock_user.groups.all.return_value = [mock_admin_group, mock_editor_group]
        request.user = mock_user

        request.META = {"HTTP_REFERER": "http://localhost:8000"}
        response = views.view_404(request)
        self.assertEquals(404, response.status_code)
    def test_return_500_response_if_server_throws_exception(self):
        request = Mock()
        mock_user = Mock()
        mock_admin_group = Mock()
        mock_editor_group = Mock()
        mock_admin_group.name = "admin"
        mock_editor_group.name = "editors_publishers"
        mock_user.groups.all.return_value = [mock_admin_group, mock_editor_group]
        request.user = mock_user

        request.META = {"HTTP_REFERER": "http://localhost:8000"}
        response = views.view_500(request)
        self.assertEquals(500, response.status_code)
Example #29
0
    def test_given_a_list_of_fields_when_document_validated_then_each_field_validated(self):
        field1 = Mock(Field)
        field1.name = "field1"
        field2 = Mock(Field)
        field2.name = "field2"

        content = {"field1": "value1", "field2": "value2"}

        document = Document([field1, field2])
        document.validate(content)

        field1.validate.assert_called_with("value1", None)
        field2.validate.assert_called_with("value2", None)
 def test_is_allowed_template_normalizes_underscores(self):
     template = Mock()
     template.name = u"Denkmalliste_Sachsen_Tabellenzeile"
     self.assertTrue(self.checker.is_allowed_template(template), "Template not found")
     # Check if config is normalized
     self.config[u"Denkmalliste_Brandenburg_Tabellenzeile"] = {
         "id": "ID",
         "id_check": "\\d{4,}",
         "id_check_description": u"Nummer, mindestens vierstellig",
     }
     self.checker = TemplateChecker(self.config)
     template.name = u"Denkmalliste Brandenburg Tabellenzeile"
     self.assertTrue(self.checker.is_allowed_template(template), "Template not found")