Beispiel #1
0
def test_get_or_create_sheet_gets_existing_sheet():
    ("XL backend should create a new sheet when a sheet of that name"
     " does not exist yet")

    # Given a mocked workbook and XL backend with one sheet
    workbook = Mock()
    sheet = Mock()
    sheet.name = 'awesomesheet'
    sheet.rows = {0: 'stuff', 1: 'more stuff'}

    class MyXL(XL):
        def get_sheets(self):
            return [sheet]

    xl_backend = MyXL(workbook=workbook)

    # When I call get_or_create_sheet of `awesome sheet1
    current_sheet, current_row = xl_backend.get_or_create_sheet('awesomesheet')

    # Then workbook.add_sheet should not have been called
    workbook.add_sheet.called.should.be.false

    # And the current sheet is equal to the mocked sheet
    current_sheet.should.equal(sheet)

    # And current_row should be 1
    current_row.should.equal(1)
Beispiel #2
0
 def get_backup_file(self):
     file = Mock()
     file.platform = amo.PLATFORM_ALL.id
     file.latest_xpi_url.return_value = 'xpi.backup'
     file.get_url_path.return_value = 'xpi.backup.url'
     file.status = amo.STATUS_PUBLIC
     return file
Beispiel #3
0
    def test_getattr_consults_schema_item_default_factory_with_context(self):

        content = Item()
        content.id = u"id"
        content.portal_type = u"testtype"

        from zope.interface import provider
        from zope.schema.interfaces import IContextAwareDefaultFactory

        @provider(IContextAwareDefaultFactory)
        def defaultFactory(context):
            return u"{0:s}_{1:s}".format(context.id, context.portal_type)

        class ISchema(Interface):
            foo = zope.schema.TextLine(title=u"foo",
                                       defaultFactory=defaultFactory)
            bar = zope.schema.TextLine(title=u"bar")

        # FTI mock
        fti_mock = Mock(wraps=DexterityFTI(u"testtype"))
        fti_mock.lookupSchema = Mock(return_value=ISchema)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        SCHEMA_CACHE.invalidate('testtype')

        self.assertEqual(u"id_testtype", content.foo)
        self.assertEqual(None, content.bar)
        self.assertEqual(u"id", content.id)
        self.assertRaises(AttributeError, getattr, content, 'baz')
Beispiel #4
0
    def test_get_agent_bindings(self, mock_factory):
        bind_payload = {'a': 1, 'b': 2}
        distributor = {'distributor_type_id': '3838'}
        mock_distributor_manager = Mock()
        mock_distributor_manager.get_distributor = Mock(return_value=distributor)
        mock_distributor_manager.create_bind_payload = Mock(return_value=bind_payload)
        mock_factory.repo_distributor_manager = Mock(return_value=mock_distributor_manager)

        # test manager

        bindings = [
            {'consumer_id': '10', 'repo_id': '20', 'distributor_id': '30', 'binding_config': {}},
            {'consumer_id': '40', 'repo_id': '50', 'distributor_id': '60', 'binding_config': {}},
        ]
        agent_bindings = AgentManager._bindings(bindings)

        # validation

        for binding in bindings:
            mock_distributor_manager.get_distributor.assert_any_call(
                binding['repo_id'], binding['distributor_id'])
            mock_distributor_manager.create_bind_payload.assert_any_call(
                binding['repo_id'], binding['distributor_id'], binding['binding_config'])

        self.assertEqual(len(agent_bindings), 2)
        for binding, agent_binding in itertools.izip(bindings, agent_bindings):
            self.assertEqual(binding['repo_id'], agent_binding['repo_id'])
            self.assertEqual(distributor['distributor_type_id'], agent_binding['type_id'])
            self.assertEqual(bind_payload, agent_binding['details'])
Beispiel #5
0
    def test_annotate_decorator(self):
        from celery.app.task import Task

        class adX(Task):
            abstract = True

            def run(self, y, z, x):
                return y, z, x

        check = Mock()
        def deco(fun):
            def _inner(*args, **kwargs):
                check(*args, **kwargs)
                return fun(*args, **kwargs)
            return _inner

        app = Celery(set_as_current=False)
        app.conf.CELERY_ANNOTATIONS = {
                adX.name: {"@__call__": deco}
        }
        adX.bind(app)
        self.assertIs(adX.app, app)

        i = adX()
        i(2, 4, x=3)
        check.assert_called_with(i, 2, 4, x=3)

        i.annotate()
        i.annotate()
Beispiel #6
0
    def test_mysql_mode_locks_unlocks_tables(self, mock_create_dir, mock_get_lvm_info, mock_get_vol_fs_type, mock_popen):
        mock_get_vol_fs_type.return_value = 'xfs'
        mock_get_lvm_info.return_value = {
            'volgroup': 'lvm_volgroup',
            'srcvol': 'lvm_device',
            'snap_path': 'snap_path'}
        mock_process = Mock()
        mock_process.communicate.return_value = '', ''
        mock_process.returncode = 0
        mock_popen.return_value = mock_process

        backup_opt = Mock()
        backup_opt.snapshot = True
        backup_opt.lvm_auto_snap = ''
        backup_opt.path_to_backup = '/just/a/path'
        backup_opt.lvm_dirmount = '/var/mountpoint'
        backup_opt.lvm_snapperm = 'ro'
        backup_opt.mode = 'mysql'
        backup_opt.mysql_db_inst = Mock()
        mock_cursor = Mock()
        backup_opt.mysql_db_inst.cursor.return_value = mock_cursor

        self.assertTrue(lvm.lvm_snap(backup_opt))

        first_call = call('FLUSH TABLES WITH READ LOCK')
        second_call = call('UNLOCK TABLES')
        self.assertEquals(first_call, mock_cursor.execute.call_args_list[0])
        self.assertEquals(second_call, mock_cursor.execute.call_args_list[1])
Beispiel #7
0
    def test_side_effect(self):
        mock = Mock()

        def effect(*args, **kwargs):
            raise SystemError('kablooie')

        mock.side_effect = effect
        self.assertRaises(SystemError, mock, 1, 2, fish=3)
        mock.assert_called_with(1, 2, fish=3)

        results = [1, 2, 3]
        def effect():
            return results.pop()
        mock.side_effect = effect

        self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
                          "side effect not used correctly")

        mock = Mock(side_effect=sentinel.SideEffect)
        self.assertEqual(mock.side_effect, sentinel.SideEffect,
                          "side effect in constructor not used")

        def side_effect():
            return DEFAULT
        mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
        self.assertEqual(mock(), sentinel.RETURN)
Beispiel #8
0
    def test_run(self, *mocks):

        eddaclient = Mock()
        eddaclient._since = 500

        def ret_list(args):
            return [
                {'imageId': 'ami-1', 'instanceId': 'a', 'launchTime': '500',
                 'tags': [{'key': 'service_name', 'value': 'conversion'}, {'key': 'started_by', 'value': 'john'}]},
                {'imageId': 'ami-1', 'instanceId': 'b', 'launchTime': '2000',
                 'tags': [{'key': 'service_name', 'value': 'router'}]},
                {'imageId': 'ami-2', 'instanceId': 'c', 'launchTime': '400'}]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.clean = Mock(return_value=m)
        self.plugin.init(eddaclient, self.config, {'first_seen': {"ami-1": 1000, "ami-2": 400}})

        real = self.plugin.run()
        expected = [
            {'id': 'ami-1', 'plugin_name': 'ami', 'details': [
                ('a', 500, [{'service_name': 'conversion'}, {'started_by': 'john'}]),
                ('b', 2000, [{'service_name': 'router'}])]}
        ]

        self.assertEqual(expected, real)

        m.query.assert_has_calls([call('/api/v2/view/instances;_expand')])
        self.assertEqual(self.plugin.status, {'first_seen': {'ami-1': 500, 'ami-2': 400}})
    def test_error_output(self):
        from planterbox import FeatureTestSuite, step

        test_feature = """Feature: A Test Feature
            Scenario: A Test Scenario
                When I fail a test
        """

        @step(r'I fail a test')
        def fail_test(test):
            test.fail('Expected Failure')

        mock_world = Mock()
        mock_world.fail_test = fail_test

        test_suite = FeatureTestSuite(mock_world, test_feature)

        test_case = test_suite._tests[0]

        def mock_addFailure(result, exc):
            self.exc_info = exc

        mock_result = Mock(addFailure=Mock(side_effect=mock_addFailure))

        test_case.run(mock_result)

        formatted = test_case.formatTraceback(self.exc_info)

        formatted_lines = formatted.split('\n')

        self.assertEqual(formatted_lines[0], 'When I fail a test')
        self.assertEqual(formatted_lines[-2],
                         'AssertionError: Expected Failure')
        self.assertEqual(unicode(test_case),
                         'A Test Scenario (A Test Feature)')
Beispiel #10
0
def frame():
    frame = Mock()
    f_code = Mock()
    f_code.co_filename = 'foo.py'
    f_code.co_firstlineno = 23
    frame.f_code = f_code
    return frame
Beispiel #11
0
    def test_resource_policy_event_callback(self):

        event_data = Mock()
        event_data.resource_id = 'resource._id'
        event_data.resource_type = 'resource.type_'
        event_data.resource_name = 'resource.name'
        event_data.origin = 'policy._id'

        policy_rules = 'policy_rules'
        pc = Mock()
        pc.get_active_resource_access_policy_rules.return_value = policy_rules
        self.governance_controller.policy_client = pc
        self.governance_controller.system_actor_user_header = {}
        # call resource_policy_event_callback without a PDP
        self.governance_controller.resource_policy_event_callback(event_data)
        # expect that nothing happened since there was no PDP to update
        self.assertEqual(pc.get_active_resource_access_policy_rules.called, False)

        #add a pdp
        pdp = Mock()
        self.governance_controller.policy_decision_point_manager = pdp

        self.governance_controller.resource_policy_event_callback(event_data)

        # expect that policy rules are retrieved for resource
        pc.get_active_resource_access_policy_rules.assert_called_with(event_data.resource_id, headers={})

        # expect that pdp is called with new rules
        pdp.load_resource_policy_rules.assert_called_with(event_data.resource_id, policy_rules)
Beispiel #12
0
    def test___init__(self):
        manager = Mock()
        manager.write_to_completion_cache = Mock(return_value=None)

        info_ = {}
        robj = base.Resource(manager, info_)
        self.assertEqual(0, manager.write_to_completion_cache.call_count)

        info_ = {"id": "id-with-less-than-36-char"}
        robj = base.Resource(manager, info_)
        self.assertEqual(info_["id"], robj.id)
        self.assertEqual(0, manager.write_to_completion_cache.call_count)

        id_ = "id-with-36-char-"
        for i in range(36 - len(id_)):
            id_ = id_ + "-"
        info_ = {"id": id_}
        robj = base.Resource(manager, info_)
        self.assertEqual(info_["id"], robj.id)
        self.assertEqual(1, manager.write_to_completion_cache.call_count)

        info_["name"] = "test-human-id"
        # Resource.HUMAN_ID is False
        robj = base.Resource(manager, info_)
        self.assertEqual(info_["id"], robj.id)
        self.assertEqual(None, robj.human_id)
        self.assertEqual(2, manager.write_to_completion_cache.call_count)

        # base.Resource.HUMAN_ID = True
        info_["HUMAN_ID"] = True
        robj = base.Resource(manager, info_)
        self.assertEqual(info_["id"], robj.id)
        self.assertEqual(info_["name"], robj.human_id)
        self.assertEqual(4, manager.write_to_completion_cache.call_count)
Beispiel #13
0
    def setUp(self):
        super(ManagerListTest, self).setUp()

        @contextlib.contextmanager
        def completion_cache_mock(*arg, **kwargs):
            yield

        self.manager = base.Manager()
        self.manager.api = Mock()
        self.manager.api.client = Mock()

        self.response_key = "response_key"
        self.data_p = ["p1", "p2"]
        self.body_p = {self.response_key: self.data_p}
        self.url_p = "test_url_post"
        self.manager.api.client.post = Mock(return_value=(self.url_p,
                                                          self.body_p))

        self.data_g = ["g1", "g2", "g3"]
        self.body_g = {self.response_key: self.data_g}
        self.url_g = "test_url_get"
        self.manager.api.client.get = Mock(return_value=(self.url_g,
                                                         self.body_g))

        mock = Mock()
        mock.side_effect = completion_cache_mock
        self.manager.completion_cache = mock
Beispiel #14
0
    def test__create(self):
        manager = base.Manager()
        manager.api = Mock()
        manager.api.client = Mock()

        response_key = "response_key"
        data_ = "test-data"
        body_ = {response_key: data_}
        url_ = "test_url_post"
        manager.api.client.post = Mock(return_value=(url_, body_))

        return_raw = True
        r = manager._create(url_, body_, response_key, return_raw)
        self.assertEqual(data_, r)

        return_raw = False

        @contextlib.contextmanager
        def completion_cache_mock(*arg, **kwargs):
            yield

        mock = Mock()
        mock.side_effect = completion_cache_mock
        manager.completion_cache = mock

        manager.resource_class = Mock(return_value="test-class")
        r = manager._create(url_, body_, response_key, return_raw)
        self.assertEqual("test-class", r)
Beispiel #15
0
 def test_has_object_permission_user(self):
     self.request.user = self.user
     self.request.amo_user = self.request.user
     obj = Mock()
     obj.user = self.user
     eq_(self.permission.has_object_permission(self.request, 'myview', obj),
         True)
Beispiel #16
0
    def test_incoming_with_add(self):
        class MockResource(ModelResource):
            key = Mock()
            model_class = mock_orm.Model
            fields = [
                AttributeField(attribute='bar', type=int),
                ]

        field = URIListResourceField(attribute='foos', resource_class=MockResource)

        source_dict = {
            'foos': ['uri://resources/1', 'uri://resources/2']
        }

        target_object = mock_orm.Mock()
        related_manager = mock_orm.Manager()
        related_manager.all = Mock(return_value=mock_orm.QuerySet())
        target_object.foos = related_manager

        ctx = mock_context()
        foo1_model = Mock()
        foo2_model = Mock()
        mock_resources = Mock()
        resource1 = MockResource(foo1_model)
        resource1.key = 1
        resource2 = MockResource(foo2_model)
        resource2.key = 2
        mock_resources.side_effect = [resource1, resource2]

        ctx.resolve_resource_uri = mock_resources

        field.handle_incoming(ctx, source_dict, target_object)
        related_manager.add.assert_called_with(foo1_model, foo2_model)
 def mock_flavor(self):
     flavor = Mock()
     flavor.name = 'Flavor Name'
     flavor.vcpus = 2
     flavor.ram = 256
     flavor.disk = 320
     return flavor
Beispiel #18
0
    def test_incoming_read_only(self):

        class Resource(ModelResource):
            model_class = Mock(spec=[])
            fields = [
                AttributeField(attribute='bar', type=int),
            ]

        field = SubModelResourceField(
            attribute='foo',
            resource_class=Resource,
            read_only=True,
        )

        source_dict = {
            'foo': {'bar': 20},
        }

        target_object = Mock()
        target_object.foo = Mock(['save'])

        field.handle_incoming(mock_context(), source_dict, target_object)

        self.assertFalse(hasattr(target_object.foo, 'bar'))
        self.assertFalse(target_object.foo.save.called)
 def test_should_find_correct_alert_type(self):
     trap = Mock('trap')
     trap.snmpTrapOID = '.1.3.6.1.4.1.17373.3.32767.0.10205'
     TRIP_TYPE_HIGH = 2
     trap.varbinds = {'.1.3.6.1.4.1.17373.3.1.6.0': TRIP_TYPE_HIGH}
     goose = wg.WeatherGoose2(trap, None, None, None)
     self.assertEquals(goose._get_alert_type(), 'cmClimateTempCTRAP')
 def assert_handled(self, key, exp_handler=SAME_AS_KEY, **exp_captures):
     if exp_handler is SAME_AS_KEY:
         exp_handler = key
     if isinstance(exp_handler, types.StringTypes):
         exp_handler = exp_handler.strip("/")
     m_response = Mock(spec=etcd.EtcdResult)
     m_response.key = key
     m_response.action = self.action
     self.dispatcher.handle_event(m_response)
     exp_handlers = self.handlers[self.expected_handlers]
     for handler_key, handler in exp_handlers.iteritems():
         assert isinstance(handler, Mock)
         if handler_key == exp_handler:
             continue
         self.assertFalse(handler.called,
                          "Unexpected set handler %s was called for "
                          "key %s" % (handler_key, key))
     unexp_handlers = self.handlers[self.unexpected_handlers]
     for handler_key, handler in unexp_handlers.iteritems():
         assert isinstance(handler, Mock)
         self.assertFalse(handler.called,
                          "Unexpected del handler %s was called for "
                          "key %s" % (handler_key, key))
     if exp_handler is not None:
         exp_handlers[exp_handler].assert_called_once_with(
             m_response, **exp_captures)
Beispiel #21
0
    def test_call(self):
        mock = Mock()
        self.assertTrue(is_instance(mock.return_value, Mock),
                        "Default return_value should be a Mock")

        result = mock()
        self.assertEqual(mock(), result,
                         "different result from consecutive calls")
        mock.reset_mock()

        ret_val = mock(sentinel.Arg)
        self.assertTrue(mock.called, "called not set")
        self.assertEqual(mock.call_count, 1, "call_count incoreect")
        self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
                         "call_args not set")
        self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
                         "call_args_list not initialised correctly")

        mock.return_value = sentinel.ReturnValue
        ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
        self.assertEqual(ret_val, sentinel.ReturnValue,
                         "incorrect return value")

        self.assertEqual(mock.call_count, 2, "call_count incorrect")
        self.assertEqual(mock.call_args,
                         ((sentinel.Arg,), {'key': sentinel.KeyArg}),
                         "call_args not set")
        self.assertEqual(mock.call_args_list, [
            ((sentinel.Arg,), {}),
            ((sentinel.Arg,), {'key': sentinel.KeyArg})
        ],
            "call_args_list not set")
Beispiel #22
0
async def test_ipmi_sel_alert_source__works_filters_dismissed_events():
    middleware = Mock()
    fut1 = asyncio.Future()
    fut1.set_result(True)
    fut2 = asyncio.Future()
    fut2.set_result(datetime(2017, 4, 20, 6, 3, 7))
    middleware.call = lambda method, *args: ({
        "keyvalue.has_key": fut1,
        "keyvalue.get": fut2,
    }[method])

    source = IPMISELAlertSource(middleware)

    assert await source._produce_alerts_for_ipmitool_output(textwrap.dedent("""\
        9,04/20/2017,06:03:07,Watchdog2 #0xca,Timer interrupt (),Asserted
        9,04/20/2017,06:03:08,Watchdog2 #0xca,Timer interrupt (),Asserted
    """)) == [
        Alert(
            IPMISELAlertClass,
            args=dict(
                sensor="Watchdog2 #0xca",
                event="Timer interrupt ()",
                direction="Asserted",
                verbose=None
            ),
            _key=ANY,
            datetime=datetime(2017, 4, 20, 6, 3, 8),
        )
    ]
Beispiel #23
0
    def test_wrap_round_robin(self):
        cluster = Mock(spec=Cluster)
        cluster.metadata = Mock(spec=Metadata)
        hosts = [Host(str(i), SimpleConvictionPolicy) for i in range(4)]
        for host in hosts:
            host.set_up()

        def get_replicas(keyspace, packed_key):
            index = struct.unpack('>i', packed_key)[0]
            return list(islice(cycle(hosts), index, index + 2))

        cluster.metadata.get_replicas.side_effect = get_replicas

        policy = TokenAwarePolicy(RoundRobinPolicy())
        policy.populate(cluster, hosts)

        for i in range(4):
            query = Statement(routing_key=struct.pack('>i', i), keyspace='keyspace_name')
            qplan = list(policy.make_query_plan(None, query))

            replicas = get_replicas(None, struct.pack('>i', i))
            other = set(h for h in hosts if h not in replicas)
            self.assertEqual(replicas, qplan[:2])
            self.assertEqual(other, set(qplan[2:]))

        # Should use the secondary policy
        for i in range(4):
            qplan = list(policy.make_query_plan())

            self.assertEqual(set(qplan), set(hosts))
Beispiel #24
0
    def test_netrc_open(self):
        root_directory = tempfile.mkdtemp()
        machine = 'foo.org'
        uri = 'https://%s/bim/bam' % machine
        netrcname = os.path.join(root_directory, "netrc")
        mock_build_opener = Mock()
        mock_build_opener_fun = Mock()
        mock_build_opener_fun.return_value = mock_build_opener
        back_build_opener = vcstools.common.build_opener
        try:
            vcstools.common.build_opener = mock_build_opener_fun
            filelike = _netrc_open(uri, netrcname)
            self.assertFalse(filelike)

            with open(netrcname, 'w') as fhand:
                fhand.write(
                    'machine %s login fooname password foopass' % machine)
            filelike = _netrc_open(uri, netrcname)
            self.assertTrue(filelike)
            filelike = _netrc_open('other', netrcname)
            self.assertFalse(filelike)
            filelike = _netrc_open(None, netrcname)
            self.assertFalse(filelike)
        finally:
            shutil.rmtree(root_directory)
            vcstools.common.build_opener = back_build_opener
Beispiel #25
0
    def test_collection(self):
        """Same as src; looking for collection{,_id,_uuid} in request."""
        b = self.get_button()
        eq_(b.collection, None)

        self.request.GET['collection_uuid'] = 'aa'
        b = self.get_button()
        eq_(b.collection, 'aa')

        self.request.GET['collection_id'] = 'bb'
        b = self.get_button()
        eq_(b.collection, 'bb')

        self.request.GET['collection'] = 'cc'
        b = self.get_button()
        eq_(b.collection, 'cc')

        self.context['collection'] = 'dd'
        b = self.get_button()
        eq_(b.collection, 'dd')

        b = self.get_button(collection='ee')
        eq_(b.collection, 'ee')

        c = Mock()
        c.uuid = 'ff'
        b = self.get_button(collection=c)
        eq_(b.collection, 'ff')
 def __reltype_ordering_mock(self):
     """
     Return RelationshipCollection instance with mocked-up contents
     suitable for testing _reltype_ordering.
     """
     # setup ------------------------
     partnames = ['/ppt/slides/slide4.xml',
                  '/ppt/slideLayouts/slideLayout1.xml',
                  '/ppt/slideMasters/slideMaster1.xml',
                  '/ppt/slides/slide1.xml',
                  '/ppt/presProps.xml']
     part1 = Mock(name='part1')
     part1.partname = partnames[0]
     part2 = Mock(name='part2')
     part2.partname = partnames[1]
     part3 = Mock(name='part3')
     part3.partname = partnames[2]
     part4 = Mock(name='part4')
     part4.partname = partnames[3]
     part5 = Mock(name='part5')
     part5.partname = partnames[4]
     rel1 = _Relationship('rId1', RT_SLIDE,        part1)
     rel2 = _Relationship('rId2', RT_SLIDE_LAYOUT, part2)
     rel3 = _Relationship('rId3', RT_SLIDE_MASTER, part3)
     rel4 = _Relationship('rId4', RT_SLIDE,        part4)
     rel5 = _Relationship('rId5', RT_PRES_PROPS,   part5)
     relationships = _RelationshipCollection()
     relationships._additem(rel1)
     relationships._additem(rel2)
     relationships._additem(rel3)
     relationships._additem(rel4)
     relationships._additem(rel5)
     return (relationships, partnames)
Beispiel #27
0
    def test_verifyObjectPaste_fti_does_not_allow_content(self):
        from Products.CMFCore.interfaces import ITypeInformation
        original_container = Container(id='parent')
        original_container.manage_permission('View', ('Anonymous',))
        content = Item(id='test')
        content.__factory_meta_type__ = 'document'
        content.portal_type = 'document'
        container = Container(id='container')
        container.all_meta_types = [{'name': 'document',
                                     'action': None,
                                     'permission': 'View'}]
        container.manage_permission('View', ('Anonymous',))
        container['test'] = content
        content = container['test']
        fti_mock = Mock()
        fti_mock.isConstructionAllowed = Mock(return_value=False)
        self.mock_utility(fti_mock, ITypeInformation, name='document')
        mock_pt = Mock()
        mock_pt.getTypeInfo = Mock(return_value=None)
        self.mock_tool(mock_pt, 'portal_types')
        self.mock_utility(mock_pt, ITypesTool)

        self.assertRaises(
            ValueError,
            container._verifyObjectPaste,
            content,
            True
        )
Beispiel #28
0
 def test_has_object_permission_different_user(self):
     self.request.user = UserProfile.objects.get(pk=2519)
     self.request.amo_user = self.request.user
     obj = Mock()
     obj.addon = self.app
     eq_(self.permission.has_object_permission(self.request, 'myview', obj),
         False)
Beispiel #29
0
    def test_getattr_on_container_returns_children(self):

        content = Container()
        content.id = u"id"
        content.portal_type = u"testtype"

        content['foo'] = Item('foo')
        content['quux'] = Item('quux')

        class ISchema(Interface):
            foo = zope.schema.TextLine(title=u"foo", default=u"foo_default")
            bar = zope.schema.TextLine(title=u"bar")

        # FTI mock
        fti_mock = Mock(wraps=DexterityFTI(u"testtype"))
        fti_mock.lookupSchema = Mock(return_value=ISchema)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        SCHEMA_CACHE.invalidate('testtype')

        # Schema field masks contained item
        self.assertEqual(u"foo_default", content.foo)

        # But we can still obtain an item
        self.assertTrue(isinstance(content['foo'], Item))
        self.assertEqual('foo', content['foo'].id)

        # And if the item isn't masked by an attribute, we can still getattr it
        self.assertTrue(isinstance(content['quux'], Item))
        self.assertEqual('quux', content['quux'].id)

        self.assertTrue(isinstance(getattr(content, 'quux'), Item))
        self.assertEqual('quux', getattr(content, 'quux').id)
    def test_priorization(self):
        webdriver = Mock()
        settings = self.settings(WEBDRIVER_BROWSER=webdriver)
        webdriver.get.side_effect = self._wait
        webdriver.page_source = u''

        dispatcher.connect(self._stop_reactor, signal=signals.spider_closed)

        crawler = Crawler(Settings(values=settings))
        crawler.configure()
        spider = self.Spider(name='test', domain='testdomain')
        crawler.crawl(spider)
        crawler.start()
        log.start(loglevel='ERROR')
        reactor.run()

        assert webdriver.get.mock_calls == [
            call('http://testdomain/path?wr=0'),
            call('http://testdomain/path?wr=0&wa=0'),
            call('http://testdomain/path?wr=0&wa=1'),
            call('http://testdomain/path?wr=1'),
            call('http://testdomain/path?wr=1&wa=0'),
            call('http://testdomain/path?wr=1&wa=1'),
            call('http://testdomain/path?wr=0&wa=0&wr=0'),
            call('http://testdomain/path?wr=0&wa=1&wr=0'),
            call('http://testdomain/path?wr=1&wa=0&wr=0'),
            call('http://testdomain/path?wr=1&wa=1&wr=0')]