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')]
Beispiel #2
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)
Beispiel #3
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 #4
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 #5
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 #6
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')
Beispiel #7
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 #8
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 #9
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 #10
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 #11
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'])
 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')
Beispiel #13
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)
 def mock_flavor(self):
     flavor = Mock()
     flavor.name = 'Flavor Name'
     flavor.vcpus = 2
     flavor.ram = 256
     flavor.disk = 320
     return flavor
Beispiel #15
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 #16
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 #17
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 #18
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
 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)
 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
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 #22
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)
Beispiel #23
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}})
Beispiel #24
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 #25
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 #26
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 #27
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)
    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 #29
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 #30
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_team(self):
     m = Mock()
     self.client.team = m
     self.assertEqual(self.client.team, m)
 def test_handle_lifecycle_control(self):
     ctrl = Mock()
     ctrl.message = "start"
     self.participant.handle_lifecycle_control(ctrl)
Beispiel #33
0
def request_mock(**kwargs):
    return Mock(status_code=200, headers={}, content=json.dumps({'status': 0}))
Beispiel #34
0
def vmmaster_server_mock(port):
    mocked_image = Mock(
        id=1, status='active',
        get=Mock(return_value='snapshot'),
        min_disk=20,
        min_ram=2,
        instance_type_flavorid=1,
    )
    type(mocked_image).name = PropertyMock(
        return_value='test_origin_1')

    with patch(
        'core.db.Database', DatabaseMock()
    ), patch(
        'core.utils.init.home_dir', Mock(return_value=fake_home_dir())
    ), patch(
        'core.logger.setup_logging', Mock(return_value=Mock())
    ), patch(
        'core.sessions.SessionWorker', Mock()
    ), patch.multiple(
        'vmpool.platforms.OpenstackPlatforms',
        images=Mock(return_value=[mocked_image]),
        flavor_params=Mock(return_value={'vcpus': 1, 'ram': 2}),
        limits=Mock(return_value={
            'maxTotalCores': 10, 'maxTotalInstances': 10,
            'maxTotalRAMSize': 100, 'totalCoresUsed': 0,
            'totalInstancesUsed': 0, 'totalRAMUsed': 0}),
    ), patch.multiple(
        'core.utils.openstack_utils',
        nova_client=Mock(return_value=Mock())
    ), patch.multiple(
        'core.db.models.OpenstackClone',
        _wait_for_activated_service=custom_wait,
        ping_vm=Mock(return_value=True)
    ):
        from vmmaster.server import VMMasterServer
        return VMMasterServer(reactor, port)
Beispiel #35
0
 def get_last_session_step(session_id):
     return Mock()
Beispiel #36
0
 def __init__(self, *args, **kwargs):
     super(DatabaseMock, self).__init__(*args, **kwargs)
     self.add = Mock(side_effect=set_primary_key)
Beispiel #37
0
import unittest
from Queue import Queue, Empty

from mock import Mock, patch, PropertyMock
from nose.twistedtools import reactor

from core.utils.network_utils import get_socket
from twisted.internet.defer import Deferred, TimeoutError
from twisted.python.failure import Failure


class TimeoutException(Exception):
    pass


app_context_mock = Mock(return_value=Mock(__enter__=Mock(), __exit__=Mock()))


def call_in_thread_mock(f):
    def wrapper(*args, **kwargs):
        return f(*args, **kwargs)
    return wrapper


def wait_for(condition, timeout=10):
    start = time.time()
    while not condition() and time.time() - start < timeout:
        time.sleep(0.1)

    return condition()
def test_request_with_no_parameters(petstore_spec):
    request = Mock(spec=IncomingRequest)
    # /user/logout conveniently has no params
    op = petstore_spec.resources['user'].operations['logoutUser']
    request_data = unmarshal_request(request, op)
    assert 0 == len(request_data)
Beispiel #39
0
            display_name=course_title,
            language='ar',
            default_store=ModuleStoreEnum.Type.split
        )

    @override_settings(LANGUAGE_CODE='eo')
    def test_esperanto_platform_arabic_course(self):
        """
        The course language should override the platform's.
        """
        message = self.send_email()
        self.assertRegexpMatches(message.from_email, '@AR .* Course Staff@')


@attr(shard=1)
@patch('bulk_email.models.html_to_text', Mock(return_value='Mocking CourseEmail.text_message', autospec=True))
class TestEmailSendFromDashboardMockedHtmlToText(EmailSendFromDashboardTestCase):
    """
    Tests email sending with mocked html_to_text.
    """
    def test_email_disabled(self):
        """
        Test response when email is disabled for course.
        """
        BulkEmailFlag.objects.create(enabled=True, require_course_email_auth=True)
        test_email = {
            'action': 'Send email',
            'send_to': '["myself"]',
            'subject': 'test subject for myself',
            'message': 'test message for myself'
        }
Beispiel #40
0
 def test_handle_exception(self):
     "Test that an exception is raised by the callback method"
     handler = Mock(side_effect=self._always_raise)
     self.callback += handler
     self.assertRaises(Exception, self.callback, message=sentinel.message)
Beispiel #41
0
class TestAccountApi(UserSettingsEventTestMixin, EmailTemplateTagMixin,
                     RetirementTestCase):
    """
    These tests specifically cover the parts of the API methods that are not covered by test_views.py.
    This includes the specific types of error raised, and default behavior when optional arguments
    are not specified.
    """
    password = "******"

    def setUp(self):
        super(TestAccountApi, self).setUp()
        self.request_factory = RequestFactory()
        self.table = "student_languageproficiency"
        self.user = UserFactory.create(password=self.password)
        self.default_request = self.request_factory.get(
            "/api/user/v1/accounts/")
        self.default_request.user = self.user
        self.different_user = UserFactory.create(password=self.password)
        self.staff_user = UserFactory(is_staff=True, password=self.password)
        self.reset_tracker()

    def test_get_username_provided(self):
        """Test the difference in behavior when a username is supplied to get_account_settings."""
        account_settings = get_account_settings(self.default_request)[0]
        self.assertEqual(self.user.username, account_settings["username"])

        account_settings = get_account_settings(self.default_request,
                                                usernames=[self.user.username
                                                           ])[0]
        self.assertEqual(self.user.username, account_settings["username"])

        account_settings = get_account_settings(
            self.default_request, usernames=[self.different_user.username])[0]
        self.assertEqual(self.different_user.username,
                         account_settings["username"])

    def test_get_configuration_provided(self):
        """Test the difference in behavior when a configuration is supplied to get_account_settings."""
        config = {
            "default_visibility": "private",
            "shareable_fields": [
                'name',
            ],
            "public_fields": [
                'email',
            ],
        }

        # With default configuration settings, email is not shared with other (non-staff) users.
        account_settings = get_account_settings(
            self.default_request, [self.different_user.username])[0]
        self.assertNotIn("email", account_settings)

        account_settings = get_account_settings(
            self.default_request,
            [self.different_user.username],
            configuration=config,
        )[0]
        self.assertEqual(self.different_user.email, account_settings["email"])

    def test_get_user_not_found(self):
        """Test that UserNotFound is thrown if there is no user with username."""
        with self.assertRaises(UserNotFound):
            get_account_settings(self.default_request,
                                 usernames=["does_not_exist"])

        self.user.username = "******"
        request = self.request_factory.get("/api/user/v1/accounts/")
        request.user = self.user
        with self.assertRaises(UserNotFound):
            get_account_settings(request)

    def test_update_username_provided(self):
        """Test the difference in behavior when a username is supplied to update_account_settings."""
        update_account_settings(self.user, {"name": "Mickey Mouse"})
        account_settings = get_account_settings(self.default_request)[0]
        self.assertEqual("Mickey Mouse", account_settings["name"])

        update_account_settings(self.user, {"name": "Donald Duck"},
                                username=self.user.username)
        account_settings = get_account_settings(self.default_request)[0]
        self.assertEqual("Donald Duck", account_settings["name"])

        with self.assertRaises(UserNotAuthorized):
            update_account_settings(self.different_user, {"name": "Pluto"},
                                    username=self.user.username)

    def test_update_user_not_found(self):
        """Test that UserNotFound is thrown if there is no user with username."""
        with self.assertRaises(UserNotFound):
            update_account_settings(self.user, {}, username="******")

        self.user.username = "******"
        with self.assertRaises(UserNotFound):
            update_account_settings(self.user, {})

    def test_get_empty_social_links(self):
        account_settings = get_account_settings(self.default_request)[0]
        self.assertEqual(account_settings['social_links'], [])

    def test_set_single_social_link(self):
        social_links = [
            dict(platform="facebook",
                 social_link="https://www.facebook.com/{}".format(
                     self.user.username))
        ]
        update_account_settings(self.user, {"social_links": social_links})
        account_settings = get_account_settings(self.default_request)[0]
        self.assertEqual(account_settings['social_links'], social_links)

    def test_set_multiple_social_links(self):
        social_links = [
            dict(platform="facebook",
                 social_link="https://www.facebook.com/{}".format(
                     self.user.username)),
            dict(platform="twitter",
                 social_link="https://www.twitter.com/{}".format(
                     self.user.username)),
        ]
        update_account_settings(self.user, {"social_links": social_links})
        account_settings = get_account_settings(self.default_request)[0]
        self.assertEqual(account_settings['social_links'], social_links)

    def test_add_social_links(self):
        original_social_links = [
            dict(platform="facebook",
                 social_link="https://www.facebook.com/{}".format(
                     self.user.username))
        ]
        update_account_settings(self.user,
                                {"social_links": original_social_links})

        extra_social_links = [
            dict(platform="twitter",
                 social_link="https://www.twitter.com/{}".format(
                     self.user.username)),
            dict(platform="linkedin",
                 social_link="https://www.linkedin.com/in/{}".format(
                     self.user.username)),
        ]
        update_account_settings(self.user,
                                {"social_links": extra_social_links})

        account_settings = get_account_settings(self.default_request)[0]
        self.assertEqual(
            account_settings['social_links'],
            sorted(original_social_links + extra_social_links,
                   key=lambda s: s['platform']),
        )

    def test_replace_social_links(self):
        original_facebook_link = dict(
            platform="facebook", social_link="https://www.facebook.com/myself")
        original_twitter_link = dict(
            platform="twitter", social_link="https://www.twitter.com/myself")
        update_account_settings(
            self.user,
            {"social_links": [original_facebook_link, original_twitter_link]})

        modified_facebook_link = dict(
            platform="facebook", social_link="https://www.facebook.com/new_me")
        update_account_settings(self.user,
                                {"social_links": [modified_facebook_link]})

        account_settings = get_account_settings(self.default_request)[0]
        self.assertEqual(account_settings['social_links'],
                         [modified_facebook_link, original_twitter_link])

    def test_remove_social_link(self):
        original_facebook_link = dict(
            platform="facebook", social_link="https://www.facebook.com/myself")
        original_twitter_link = dict(
            platform="twitter", social_link="https://www.twitter.com/myself")
        update_account_settings(
            self.user,
            {"social_links": [original_facebook_link, original_twitter_link]})

        removed_facebook_link = dict(platform="facebook", social_link="")
        update_account_settings(self.user,
                                {"social_links": [removed_facebook_link]})

        account_settings = get_account_settings(self.default_request)[0]
        self.assertEqual(account_settings['social_links'],
                         [original_twitter_link])

    def test_unsupported_social_link_platform(self):
        social_links = [
            dict(platform="unsupported",
                 social_link="https://www.unsupported.com/{}".format(
                     self.user.username))
        ]
        with self.assertRaises(AccountUpdateError):
            update_account_settings(self.user, {"social_links": social_links})

    def test_update_error_validating(self):
        """Test that AccountValidationError is thrown if incorrect values are supplied."""
        with self.assertRaises(AccountValidationError):
            update_account_settings(self.user, {"username": "******"})

        with self.assertRaises(AccountValidationError):
            update_account_settings(self.user, {"gender": "undecided"})

        with self.assertRaises(AccountValidationError):
            update_account_settings(
                self.user, {
                    "profile_image": {
                        "has_image": "not_allowed",
                        "image_url": "not_allowed"
                    }
                })

        # Check the various language_proficiencies validation failures.
        # language_proficiencies must be a list of dicts, each containing a
        # unique 'code' key representing the language code.
        with self.assertRaises(AccountValidationError):
            update_account_settings(self.user,
                                    {"language_proficiencies": "not_a_list"})
        with self.assertRaises(AccountValidationError):
            update_account_settings(self.user,
                                    {"language_proficiencies": [{}]})

        with self.assertRaises(AccountValidationError):
            update_account_settings(self.user, {"account_privacy": ""})

    def test_update_multiple_validation_errors(self):
        """Test that all validation errors are built up and returned at once"""
        # Send a read-only error, serializer error, and email validation error.

        naughty_update = {
            "username":
            "******",
            "gender":
            "undecided",
            "email":
            "not an email address",
            "name":
            "<p style=\"font-size:300px; color:green;\"></br>Name<input type=\"text\"></br>Content spoof"
        }

        with self.assertRaises(AccountValidationError) as context_manager:
            update_account_settings(self.user, naughty_update)
        field_errors = context_manager.exception.field_errors
        self.assertEqual(4, len(field_errors))
        self.assertEqual("This field is not editable via this API",
                         field_errors["username"]["developer_message"])
        self.assertIn("Value \'undecided\' is not valid for field \'gender\'",
                      field_errors["gender"]["developer_message"])
        self.assertIn("Valid e-mail address required.",
                      field_errors["email"]["developer_message"])
        self.assertIn("Full Name cannot contain the following characters: < >",
                      field_errors["name"]["user_message"])

    @patch('django.core.mail.send_mail')
    @patch('student.views.management.render_to_string',
           Mock(side_effect=mock_render_to_string, autospec=True))
    def test_update_sending_email_fails(self, send_mail):
        """Test what happens if all validation checks pass, but sending the email for email change fails."""
        send_mail.side_effect = [Exception, None]
        less_naughty_update = {
            "name": "Mickey Mouse",
            "email": "*****@*****.**"
        }

        with patch('crum.get_current_request', return_value=self.fake_request):
            with self.assertRaises(AccountUpdateError) as context_manager:
                update_account_settings(self.user, less_naughty_update)
        self.assertIn("Error thrown from do_email_change_request",
                      context_manager.exception.developer_message)

        # Verify that the name change happened, even though the attempt to send the email failed.
        account_settings = get_account_settings(self.default_request)[0]
        self.assertEqual("Mickey Mouse", account_settings["name"])

    @patch.dict(settings.FEATURES, dict(ALLOW_EMAIL_ADDRESS_CHANGE=False))
    def test_email_changes_disabled(self):
        """
        Test that email address changes are rejected when ALLOW_EMAIL_ADDRESS_CHANGE is not set.
        """
        disabled_update = {"email": "*****@*****.**"}

        with self.assertRaises(AccountUpdateError) as context_manager:
            update_account_settings(self.user, disabled_update)
        self.assertIn("Email address changes have been disabled",
                      context_manager.exception.developer_message)

    @patch.dict(settings.FEATURES, dict(ALLOW_EMAIL_ADDRESS_CHANGE=True))
    def test_email_changes_blocked_on_retired_email(self):
        """
        Test that email address changes are rejected when an email associated with a *partially* retired account is
        specified.
        """
        # First, record the original email addres of the primary user (the one seeking to update their email).
        original_email = self.user.email

        # Setup a partially retired user.  This user recently submitted a deletion request, but it has not been
        # processed yet.
        partially_retired_email = '*****@*****.**'
        partially_retired_user = UserFactory(email=partially_retired_email)
        fake_requested_retirement(partially_retired_user)

        # Attempt to change email to the one of the partially retired user.
        rejected_update = {'email': partially_retired_email}
        update_account_settings(self.user, rejected_update)

        # No error should be thrown, and we need to check that the email update was skipped.
        assert self.user.email == original_email

    @patch(
        'openedx.core.djangoapps.user_api.accounts.serializers.AccountUserSerializer.save'
    )
    def test_serializer_save_fails(self, serializer_save):
        """
        Test the behavior of one of the serializers failing to save. Note that email request change
        won't be processed in this case.
        """
        serializer_save.side_effect = [Exception, None]
        update_will_fail = {"name": "Mickey Mouse", "email": "*****@*****.**"}

        with self.assertRaises(AccountUpdateError) as context_manager:
            update_account_settings(self.user, update_will_fail)
        self.assertIn("Error thrown when saving account updates",
                      context_manager.exception.developer_message)

        # Verify that no email change request was initiated.
        pending_change = PendingEmailChange.objects.filter(user=self.user)
        self.assertEqual(0, len(pending_change))

    def test_language_proficiency_eventing(self):
        """
        Test that eventing of language proficiencies, which happens update_account_settings method, behaves correctly.
        """
        def verify_event_emitted(new_value, old_value):
            """
            Confirm that the user setting event was properly emitted
            """
            update_account_settings(self.user,
                                    {"language_proficiencies": new_value})
            self.assert_user_setting_event_emitted(
                setting='language_proficiencies', old=old_value, new=new_value)
            self.reset_tracker()

        # Change language_proficiencies and verify events are fired.
        verify_event_emitted([{"code": "en"}], [])
        verify_event_emitted([{
            "code": "en"
        }, {
            "code": "fr"
        }], [{
            "code": "en"
        }])
        # Note that events are fired even if there has been no actual change.
        verify_event_emitted([{
            "code": "en"
        }, {
            "code": "fr"
        }], [{
            "code": "en"
        }, {
            "code": "fr"
        }])
        verify_event_emitted([], [{"code": "en"}, {"code": "fr"}])
Beispiel #42
0
class TestEmailSendFromDashboardMockedHtmlToText(EmailSendFromDashboardTestCase):
    """
    Tests email sending with mocked html_to_text.
    """
    def test_email_disabled(self):
        """
        Test response when email is disabled for course.
        """
        BulkEmailFlag.objects.create(enabled=True, require_course_email_auth=True)
        test_email = {
            'action': 'Send email',
            'send_to': '["myself"]',
            'subject': 'test subject for myself',
            'message': 'test message for myself'
        }
        response = self.client.post(self.send_mail_url, test_email)
        # We should get back a HttpResponseForbidden (status code 403)
        self.assertContains(response, "Email is not enabled for this course.", status_code=403)

    @patch('bulk_email.models.html_to_text', Mock(return_value='Mocking CourseEmail.text_message', autospec=True))
    def test_send_to_self(self):
        """
        Make sure email send to myself goes to myself.
        """
        test_email = {
            'action': 'send',
            'send_to': '["myself"]',
            'subject': 'test subject for myself',
            'message': 'test message for myself'
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        # Check that outbox is as expected
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(len(mail.outbox[0].to), 1)
        self.assertEquals(mail.outbox[0].to[0], self.instructor.email)
        self.assertEquals(mail.outbox[0].subject, 'test subject for myself')
        self.assertEquals(
            mail.outbox[0].from_email,
            u'"{course_display_name}" Course Staff <{course_name}[email protected]>'.format(
                course_display_name=self.course.display_name,
                course_name=self.course.id.course
            )
        )

    def test_send_to_staff(self):
        """
        Make sure email send to staff and instructors goes there.
        """
        test_email = {
            'action': 'Send email',
            'send_to': '["staff"]',
            'subject': 'test subject for staff',
            'message': 'test message for subject'
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        # the 1 is for the instructor in this test and others
        self.assertEquals(len(mail.outbox), 1 + len(self.staff))
        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [self.instructor.email] + [s.email for s in self.staff]
        )

    def test_send_to_cohort(self):
        """
        Make sure email sent to a cohort goes there.
        """
        cohort = CourseCohort.create(cohort_name='test cohort', course_id=self.course.id)
        for student in self.students:
            add_user_to_cohort(cohort.course_user_group, student.username)
        test_email = {
            'action': 'Send email',
            'send_to': '["cohort:{}"]'.format(cohort.course_user_group.name),
            'subject': 'test subject for cohort',
            'message': 'test message for cohort'
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [s.email for s in self.students]
        )

    def test_send_to_cohort_unenrolled(self):
        """
        Make sure email sent to a cohort does not go to unenrolled members of the cohort.
        """
        self.students.append(UserFactory())  # user will be added to cohort, but not enrolled in course
        cohort = CourseCohort.create(cohort_name='test cohort', course_id=self.course.id)
        for student in self.students:
            add_user_to_cohort(cohort.course_user_group, student.username)
        test_email = {
            'action': 'Send email',
            'send_to': '["cohort:{}"]'.format(cohort.course_user_group.name),
            'subject': 'test subject for cohort',
            'message': 'test message for cohort'
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        self.assertEquals(len(mail.outbox), len(self.students) - 1)
        self.assertNotIn(self.students[-1].email, [e.to[0] for e in mail.outbox])

    def test_send_to_track(self):
        """
        Make sure email sent to a registration track goes there.
        """
        CourseMode.objects.create(mode_slug='test', course_id=self.course.id)
        for student in self.students:
            update_enrollment(student, unicode(self.course.id), 'test')
        test_email = {
            'action': 'Send email',
            'send_to': '["track:test"]',
            'subject': 'test subject for test track',
            'message': 'test message for test track',
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [s.email for s in self.students]
        )

    def test_send_to_track_other_enrollments(self):
        """
        Failing test for EDUCATOR-217: verifies that emails are only sent to
        users in a specific track if they're in that track in the course the
        email is being sent from.
        """
        # Create a mode and designate an enrolled user to be placed in that mode
        CourseMode.objects.create(mode_slug='test_mode', course_id=self.course.id)
        test_mode_student = self.students[0]
        update_enrollment(test_mode_student, unicode(self.course.id), 'test_mode')

        # Take another user already enrolled in the course, then enroll them in
        # another course but in that same test mode
        test_mode_student_other_course = self.students[1]
        other_course = CourseFactory.create()
        CourseMode.objects.create(mode_slug='test_mode', course_id=other_course.id)
        CourseEnrollmentFactory.create(
            user=test_mode_student_other_course,
            course_id=other_course.id
        )
        update_enrollment(test_mode_student_other_course, unicode(other_course.id), 'test_mode')

        # Send the emails...
        test_email = {
            'action': 'Send email',
            'send_to': '["track:test_mode"]',
            'subject': 'test subject for test_mode track',
            'message': 'test message for test_mode track',
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        # Only the the student in the test mode in the course the email was
        # sent from should receive an email
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].to[0], test_mode_student.email)

    def test_send_to_all(self):
        """
        Make sure email send to all goes there.
        """

        test_email = {
            'action': 'Send email',
            'send_to': '["myself", "staff", "learners"]',
            'subject': 'test subject for all',
            'message': 'test message for all'
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        # the 1 is for the instructor
        self.assertEquals(len(mail.outbox), 1 + len(self.staff) + len(self.students))
        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [self.instructor.email] + [s.email for s in self.staff] + [s.email for s in self.students]
        )

    @override_settings(BULK_EMAIL_JOB_SIZE_THRESHOLD=1)
    def test_send_to_all_high_queue(self):
        """
        Test that email is still sent when the high priority queue is used
        """
        self.test_send_to_all()

    def test_no_duplicate_emails_staff_instructor(self):
        """
        Test that no duplicate emails are sent to a course instructor that is
        also course staff
        """
        CourseStaffRole(self.course.id).add_users(self.instructor)
        self.test_send_to_all()

    def test_no_duplicate_emails_enrolled_staff(self):
        """
        Test that no duplicate emails are sent to a course instructor that is
        also enrolled in the course
        """
        CourseEnrollment.enroll(self.instructor, self.course.id)
        self.test_send_to_all()

    def test_no_duplicate_emails_unenrolled_staff(self):
        """
        Test that no duplicate emails are sent to a course staff that is
        not enrolled in the course, but is enrolled in other courses
        """
        course_1 = CourseFactory.create()
        course_2 = CourseFactory.create()
        # make sure self.instructor isn't enrolled in the course
        self.assertFalse(CourseEnrollment.is_enrolled(self.instructor, self.course.id))
        CourseEnrollment.enroll(self.instructor, course_1.id)
        CourseEnrollment.enroll(self.instructor, course_2.id)
        self.test_send_to_all()

    def test_unicode_subject_send_to_all(self):
        """
        Make sure email (with Unicode characters) send to all goes there.
        """

        uni_subject = u'téśt śúbjéćt főŕ áĺĺ'
        test_email = {
            'action': 'Send email',
            'send_to': '["myself", "staff", "learners"]',
            'subject': uni_subject,
            'message': 'test message for all'
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        self.assertEquals(len(mail.outbox), 1 + len(self.staff) + len(self.students))
        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [self.instructor.email] + [s.email for s in self.staff] + [s.email for s in self.students]
        )
        self.assertEquals(mail.outbox[0].subject, uni_subject)

    def test_unicode_students_send_to_all(self):
        """
        Make sure email (with Unicode characters) send to all goes there.
        """

        # Create a student with Unicode in their first & last names
        unicode_user = UserFactory(first_name=u'Ⓡⓞⓑⓞⓣ', last_name=u'ՇﻉรՇ')
        CourseEnrollmentFactory.create(user=unicode_user, course_id=self.course.id)
        self.students.append(unicode_user)

        test_email = {
            'action': 'Send email',
            'send_to': '["myself", "staff", "learners"]',
            'subject': 'test subject for all',
            'message': 'test message for all'
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        self.assertEquals(len(mail.outbox), 1 + len(self.staff) + len(self.students))

        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [self.instructor.email] + [s.email for s in self.staff] + [s.email for s in self.students]
        )

    @override_settings(BULK_EMAIL_DEFAULT_FROM_EMAIL="*****@*****.**")
    def test_long_course_display_name(self):
        """
        This test tests that courses with exorbitantly large display names
        can still send emails, since it appears that 320 appears to be the
        character length limit of from emails for Amazon SES.
        """
        test_email = {
            'action': 'Send email',
            'send_to': '["myself", "staff", "learners"]',
            'subject': 'test subject for self',
            'message': 'test message for self'
        }

        # make display_name that's longer than 320 characters when encoded
        # to ascii and escaped, but shorter than 320 unicode characters
        long_name = u"Финансовое программирование и политика, часть 1: макроэкономические счета и анализ"

        course = CourseFactory.create(
            display_name=long_name,
            org="IMF",
            number="FPP.1x",
            run="2016",
        )
        instructor = InstructorFactory(course_key=course.id)

        unexpected_from_addr = _get_source_address(
            course.id, course.display_name, course_language=None, truncate=False
        )
        __, encoded_unexpected_from_addr = forbid_multi_line_headers(
            "from", unexpected_from_addr, 'utf-8'
        )
        escaped_encoded_unexpected_from_addr = escape(encoded_unexpected_from_addr)

        # it's shorter than 320 characters when just encoded
        self.assertEqual(len(encoded_unexpected_from_addr), 318)
        # escaping it brings it over that limit
        self.assertEqual(len(escaped_encoded_unexpected_from_addr), 324)
        # when not escaped or encoded, it's well below 320 characters
        self.assertEqual(len(unexpected_from_addr), 137)

        self.login_as_user(instructor)
        send_mail_url = reverse('send_email', kwargs={'course_id': unicode(course.id)})
        response = self.client.post(send_mail_url, test_email)
        self.assertTrue(json.loads(response.content)['success'])

        self.assertEqual(len(mail.outbox), 1)
        from_email = mail.outbox[0].from_email

        expected_from_addr = (
            u'"{course_name}" Course Staff <{course_name}[email protected]>'
        ).format(course_name=course.id.course)

        self.assertEqual(
            from_email,
            expected_from_addr
        )
        self.assertEqual(len(from_email), 61)

    @override_settings(BULK_EMAIL_EMAILS_PER_TASK=3)
    @patch('bulk_email.tasks.update_subtask_status')
    def test_chunked_queries_send_numerous_emails(self, email_mock):
        """
        Test sending a large number of emails, to test the chunked querying
        """
        mock_factory = MockCourseEmailResult()
        email_mock.side_effect = mock_factory.get_mock_update_subtask_status()
        added_users = []
        for _ in xrange(LARGE_NUM_EMAILS):
            user = UserFactory()
            added_users.append(user)
            CourseEnrollmentFactory.create(user=user, course_id=self.course.id)

        optouts = []
        for i in [1, 3, 9, 10, 18]:  # 5 random optouts
            user = added_users[i]
            optouts.append(user)
            optout = Optout(user=user, course_id=self.course.id)
            optout.save()

        test_email = {
            'action': 'Send email',
            'send_to': '["myself", "staff", "learners"]',
            'subject': 'test subject for all',
            'message': 'test message for all'
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        self.assertEquals(mock_factory.emails_sent,
                          1 + len(self.staff) + len(self.students) + LARGE_NUM_EMAILS - len(optouts))
        outbox_contents = [e.to[0] for e in mail.outbox]
        should_send_contents = ([self.instructor.email] +
                                [s.email for s in self.staff] +
                                [s.email for s in self.students] +
                                [s.email for s in added_users if s not in optouts])
        self.assertItemsEqual(outbox_contents, should_send_contents)
 def make_connection(self):
     c = AsyncoreConnection('1.2.3.4', cql_version='3.0.1')
     c.socket = Mock()
     c.socket.send.side_effect = lambda x: len(x)
     return c
Beispiel #44
0
class AccountCreationActivationAndPasswordChangeTest(TestCase):
    """
    Test cases to cover the account initialization workflow
    """
    USERNAME = u'claire-underwood'
    PASSWORD = u'ṕáśśẃőŕd'
    EMAIL = u'*****@*****.**'

    IS_SECURE = False

    @skip_unless_lms
    def test_activate_account(self):
        # Create the account, which is initially inactive
        activation_key = create_account(self.USERNAME, self.PASSWORD,
                                        self.EMAIL)
        user = User.objects.get(username=self.USERNAME)

        request = RequestFactory().get("/api/user/v1/accounts/")
        request.user = user
        account = get_account_settings(request)[0]
        self.assertEqual(self.USERNAME, account["username"])
        self.assertEqual(self.EMAIL, account["email"])
        self.assertFalse(account["is_active"])

        # Activate the account and verify that it is now active
        activate_account(activation_key)
        account = get_account_settings(request)[0]
        self.assertTrue(account['is_active'])

    def test_create_account_duplicate_username(self):
        create_account(self.USERNAME, self.PASSWORD, self.EMAIL)
        with self.assertRaises(AccountUserAlreadyExists):
            create_account(self.USERNAME, self.PASSWORD,
                           '*****@*****.**')

    def test_username_too_long(self):
        long_username = '******' * (USERNAME_MAX_LENGTH + 1)
        with self.assertRaises(AccountUsernameInvalid):
            create_account(long_username, self.PASSWORD, self.EMAIL)

    @ddt.data(*INVALID_EMAILS)
    def test_create_account_invalid_email(self, invalid_email):
        with pytest.raises(AccountEmailInvalid):
            create_account(self.USERNAME, self.PASSWORD, invalid_email)

    @ddt.data(*INVALID_PASSWORDS)
    def test_create_account_invalid_password(self, invalid_password):
        with pytest.raises(AccountPasswordInvalid):
            create_account(self.USERNAME, invalid_password, self.EMAIL)

    def test_create_account_username_password_equal(self):
        # Username and password cannot be the same
        with pytest.raises(AccountPasswordInvalid):
            create_account(self.USERNAME, self.USERNAME, self.EMAIL)

    @ddt.data(*INVALID_USERNAMES)
    def test_create_account_invalid_username(self, invalid_username):
        with pytest.raises(AccountRequestError):
            create_account(invalid_username, self.PASSWORD, self.EMAIL)

    def test_create_account_prevent_auth_user_writes(self):
        with pytest.raises(UserAPIInternalError,
                           message=SYSTEM_MAINTENANCE_MSG):
            with waffle().override(PREVENT_AUTH_USER_WRITES, True):
                create_account(self.USERNAME, self.PASSWORD, self.EMAIL)

    def test_activate_account_invalid_key(self):
        with pytest.raises(UserNotAuthorized):
            activate_account(u'invalid')

    def test_activate_account_prevent_auth_user_writes(self):
        activation_key = create_account(self.USERNAME, self.PASSWORD,
                                        self.EMAIL)
        with pytest.raises(UserAPIInternalError,
                           message=SYSTEM_MAINTENANCE_MSG):
            with waffle().override(PREVENT_AUTH_USER_WRITES, True):
                activate_account(activation_key)

    @skip_unless_lms
    def test_request_password_change(self):
        # Create and activate an account
        activation_key = create_account(self.USERNAME, self.PASSWORD,
                                        self.EMAIL)
        activate_account(activation_key)

        request = RequestFactory().post('/password')
        request.user = Mock()
        request.site = SiteFactory()

        with patch('crum.get_current_request', return_value=request):
            # Request a password change
            request_password_change(self.EMAIL, self.IS_SECURE)

        # Verify that one email message has been sent
        self.assertEqual(len(mail.outbox), 1)

        # Verify that the body of the message contains something that looks
        # like an activation link
        email_body = mail.outbox[0].body
        result = re.search(r'(?P<url>https?://[^\s]+)', email_body)
        self.assertIsNot(result, None)

    @skip_unless_lms
    def test_request_password_change_invalid_user(self):
        with self.assertRaises(UserNotFound):
            request_password_change(self.EMAIL, self.IS_SECURE)

        # Verify that no email messages have been sent
        self.assertEqual(len(mail.outbox), 0)

    @skip_unless_lms
    def test_request_password_change_inactive_user(self):
        # Create an account, but do not activate it
        create_account(self.USERNAME, self.PASSWORD, self.EMAIL)

        request = RequestFactory().post('/password')
        request.user = Mock()
        request.site = SiteFactory()

        with patch('crum.get_current_request', return_value=request):
            request_password_change(self.EMAIL, self.IS_SECURE)

        # Verify that the activation email was still sent
        self.assertEqual(len(mail.outbox), 1)

    def _assert_is_datetime(self, timestamp):
        """
        Internal helper to validate the type of the provided timestamp
        """
        if not timestamp:
            return False
        try:
            parse_datetime(timestamp)
        except ValueError:
            return False
        else:
            return True

    @patch("openedx.core.djangoapps.site_configuration.helpers.get_value",
           Mock(return_value=False))
    def test_create_account_not_allowed(self):
        """
        Test case to check user creation is forbidden when ALLOW_PUBLIC_ACCOUNT_CREATION feature flag is turned off
        """
        response = create_account(self.USERNAME, self.PASSWORD, self.EMAIL)
        self.assertEqual(response.status_code, 403)
Beispiel #45
0
 def test_get_cluster(self):
     self.k.get_cluster()
     with patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod',
                       Mock(side_effect=Exception)):
         self.assertRaises(KubernetesError, self.k.get_cluster)
Beispiel #46
0
 def test_skip_logging(self):
     # Should skip setting up logging on the handler
     mock_handler = Mock()
     skip_request_logging(mock_handler)
     eq_(len(mock_handler.mock_calls), 0)
Beispiel #47
0
 def test_take_leader(self):
     self.k.take_leader()
     self.k._leader_observed_record['leader'] = 'test'
     self.k.patch_or_create = Mock(return_value=False)
     self.k.take_leader()
    def test_process_message(self, remote_call_type_mock, push_dlq_mock,
                             push_retry_mock):
        post = Mock()
        response = Mock()
        response.status_code = 200
        post.return_value = response
        remote_call_type_mock.get.return_value = post

        # Test remote job flow
        body = json.dumps({"body": "work body"})
        message = Mock()
        api = "http://test.api.com/test_dest"
        api_request_headers = {"title": "Yippi"}
        job = EasyJob.create(api,
                             constants.API_REMOTE,
                             api_request_headers=api_request_headers)
        headers = {}
        headers.update(job.to_dict())
        message.headers = headers

        self.work_queue_con.process_message(body, message)

        data_body = {'tag': 'unknown', 'data': body, 'job_id': job.id}

        # when return in 200
        post.assert_called_with(api,
                                data=data_body,
                                timeout=constants.DEFAULT_ASYNC_TIMEOUT,
                                headers=api_request_headers)

        # when the status code is 410 (in the error list to be reported
        # then the job will be added to be dlq
        response.status_code = 410
        response.text = "big error"
        self.work_queue_con.process_message(body, message)
        push_dlq_mock.assert_called()

        # when the status code is 5XX then add to the error queue
        response.status_code = 520
        response.text = "big error"
        self.work_queue_con.process_message(body, message)
        push_retry_mock.assert_called()

        # test local flow

        sys.path += os.path.dirname(test_class.__file__)

        # test with module function
        api = test_class.dummy_function_external
        job = EasyJob.create(api, constants.API_LOCAL)

        headers = {}
        headers.update(job.to_dict())
        message.headers = headers
        test_class.TestClass.module_function_called = False
        self.work_queue_con.process_message(body, message)
        self.assertEqual(test_class.TestClass.module_function_called, True)

        # test with string function
        api = "tests.test_class.dummy_function_external"
        job = EasyJob.create(api, constants.API_LOCAL)

        headers = {}
        headers.update(job.to_dict())
        message.headers = headers
        test_class.TestClass.module_function_called = False
        self.work_queue_con.process_message(body, message)
        self.assertEqual(test_class.TestClass.module_function_called, True)

        # test with instance function
        test_cls = test_class.TestClass()
        api = test_cls.dummy_function_in_class
        job = EasyJob.create(api, constants.API_LOCAL)

        headers = {}
        headers.update(job.to_dict())
        message.headers = headers
        test_class.TestClass.class_function_called = False
        self.work_queue_con.process_message(body, message)
        self.assertEqual(test_class.TestClass.class_function_called, True)

        # test with instance class
        tst_class = test_class.TestClass()
        job = EasyJob.create(tst_class, constants.API_LOCAL)

        headers = {}
        headers.update(job.to_dict())
        message.headers = headers
        test_class.TestClass.class_instance_called = False
        self.work_queue_con.process_message(body, message)
        self.assertEqual(test_class.TestClass.class_instance_called, True)
Beispiel #49
0
class TestConfig(TestCase):
    @staticmethod
    def schema_has_section(section):
        for _section in [s[0] for s in SCHEMA]:
            if _section == section:
                return True
        return False

    @staticmethod
    def schema_has_property(section, key):
        for _section in SCHEMA:
            if _section[0] != section:
                continue
            for _key in [p[0] for p in _section[2]]:
                if _key == key:
                    return True
        return False

    def test_default(self):
        # Everything in the schema has a default.
        for section in SCHEMA:
            for key in [p[0] for p in section[2]]:
                msg = '[%s] not found in schema' % key
                self.assertTrue(key in DEFAULT[section[0]], msg=msg)
        # Everything in the default is defined in the schema.
        for section in DEFAULT:
            self.assertTrue(self.schema_has_section(section))
            for key in DEFAULT[section]:
                msg = '[%s].%s has not default' % (section, key)
                self.assertTrue(self.schema_has_property(section, key),
                                msg=msg)

    @patch('os.listdir')
    @patch('os.path.expanduser')
    @patch('os.path.exists', Mock(return_value=False))
    @patch('pulp.client.admin.config.Config')
    def test_read(self, fake_config, fake_expanduser, fake_listdir):
        fake_listdir.return_value = ['A', 'B', 'C']
        fake_expanduser.return_value = '/home/pulp/.pulp/admin.conf'

        # test
        cfg = read_config()

        # validation
        paths = [
            '/etc/pulp/admin/admin.conf',
            '/etc/pulp/admin/conf.d/A',
            '/etc/pulp/admin/conf.d/B',
            '/etc/pulp/admin/conf.d/C',
        ]

        fake_config.assert_called_with(*paths)
        fake_config().validate.assert_called_with(SCHEMA)
        self.assertEqual(cfg, fake_config())

    @patch('pulp.client.admin.config.Config')
    def test_read_paths(self, fake_config):
        paths = ['path_A', 'path_B']

        # test
        cfg = read_config(paths=paths)

        # validation
        fake_config.assert_called_with(*paths)
        fake_config().validate.assert_called_with(SCHEMA)
        self.assertEqual(cfg, fake_config())

    @patch('pulp.client.admin.config.Config')
    @patch('pulp.client.admin.config.validate_overrides')
    def test_read_calls_validate_overrides(self, mock_validate_overrides,
                                           fake_config):
        read_config()

        mock_validate_overrides.assert_called_once()

    @patch('pulp.client.admin.config.Config')
    def test_read_no_validation(self, fake_config):
        paths = ['path_A', 'path_B']

        # test
        cfg = read_config(paths=paths, validate=False)

        # validation
        fake_config.assert_called_with(*paths)
        self.assertFalse(fake_config().validate.called)
        self.assertEqual(cfg, fake_config())

    @patch('pulp.client.admin.config.validate_overrides',
           Mock(return_value=True))
    @patch('os.listdir')
    @patch('os.path.expanduser')
    @patch('os.path.exists', Mock(return_value=True))
    @patch('pulp.client.admin.config.Config')
    def test_read_with_override(self, fake_config, fake_expanduser,
                                fake_listdir):
        fake_listdir.return_value = ['A', 'B', 'C']
        fake_expanduser.return_value = '/home/pulp/.pulp/admin.conf'

        # test
        cfg = read_config()

        # validation
        paths = [
            '/etc/pulp/admin/admin.conf', '/etc/pulp/admin/conf.d/A',
            '/etc/pulp/admin/conf.d/B', '/etc/pulp/admin/conf.d/C',
            '/home/pulp/.pulp/admin.conf'
        ]

        fake_config.assert_called_with(*paths)
        fake_config().validate.assert_called_with(SCHEMA)
        self.assertEqual(cfg, fake_config())

    @patch('pulp.client.admin.config.os.stat')
    @patch('pulp.client.admin.config.Config')
    def test_validate_overrides_when_has_password(self, mock_config,
                                                  mock_os_stat):
        # st_mode is the file permissions component of stat output
        # st_mode = 33279 emulates a 777 permission
        mock_os_stat.return_value.st_mode = 33279
        mock_config.return_value.has_option.return_value = True
        self.assertRaises(RuntimeError, validate_overrides, '/tmp/admin.conf')
        mock_os_stat.assert_has_calls([call('/tmp/admin.conf')])
        mock_config.return_value.has_option.assert_called_once_with(
            'auth', 'password')

    @patch('pulp.client.admin.config.os.stat')
    @patch('pulp.client.admin.config.Config')
    def test_validate_overrides_when_has_password_good_permissions(
            self, mock_config, mock_os_stat):
        # st_mode is the file permissions component of stat output
        # st_mode = 33216 emulates a 700 permission
        mock_os_stat.return_value.st_mode = 33216
        mock_config.return_value.has_option.return_value = True
        validate_overrides('/tmp/admin.conf')
        mock_config.assert_called_once_with('/tmp/admin.conf')

    @patch('pulp.client.admin.config.os.stat')
    @patch('pulp.client.admin.config.Config')
    def test_validate_overrides_when_does_not_have_password(
            self, mock_config, mock_os_stat):
        # st_mode is the file permissions component of stat output
        # st_mode = 33279 emulates a 777 permission
        mock_os_stat.return_value.st_mode = 33279
        mock_config.return_value.has_option.return_value = False
        try:
            validate_overrides('/tmp/admin.conf')
        except Exception as error:
            self.fail(
                "validate_overrides should not raise an Exception. Raised %s" %
                error)
Beispiel #50
0
class TestKubernetes(unittest.TestCase):
    @patch('kubernetes.config.load_kube_config', Mock())
    @patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map',
                  mock_list_namespaced_config_map)
    @patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod',
                  mock_list_namespaced_pod)
    def setUp(self):
        self.k = Kubernetes({
            'ttl': 30,
            'scope': 'test',
            'name': 'p-0',
            'retry_timeout': 10,
            'labels': {
                'f': 'b'
            }
        })
        with patch('time.time', Mock(return_value=1)):
            self.k.get_cluster()

    @patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map',
                  mock_list_namespaced_config_map)
    @patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod',
                  mock_list_namespaced_pod)
    def test_get_cluster(self):
        self.k.get_cluster()
        with patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod',
                          Mock(side_effect=Exception)):
            self.assertRaises(KubernetesError, self.k.get_cluster)

    @patch('kubernetes.config.load_kube_config', Mock())
    @patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints', Mock())
    def test_update_leader(self):
        k = Kubernetes({
            'ttl': 30,
            'scope': 'test',
            'name': 'p-0',
            'retry_timeout': 10,
            'labels': {
                'f': 'b'
            },
            'use_endpoints': True,
            'pod_ip': '10.0.0.0'
        })
        self.assertIsNotNone(k.update_leader('123'))

    def test_take_leader(self):
        self.k.take_leader()
        self.k._leader_observed_record['leader'] = 'test'
        self.k.patch_or_create = Mock(return_value=False)
        self.k.take_leader()

    def test_manual_failover(self):
        self.k.manual_failover('foo', 'bar')

    def test_set_config_value(self):
        self.k.set_config_value('{}')

    @patch.object(k8s_client.CoreV1Api, 'patch_namespaced_pod',
                  Mock(return_value=True))
    def test_touch_member(self):
        self.k.touch_member({})
        self.k._name = 'p-1'
        self.k.touch_member({'state': 'running', 'role': 'replica'})
        self.k.touch_member({'state': 'stopped', 'role': 'master'})

    def test_initialize(self):
        self.k.initialize()

    def test_delete_leader(self):
        self.k.delete_leader()

    def test_cancel_initialization(self):
        self.k.cancel_initialization()

    @patch.object(k8s_client.CoreV1Api,
                  'delete_collection_namespaced_config_map',
                  Mock(side_effect=k8s_client.rest.ApiException(500, '')))
    def test_delete_cluster(self):
        self.k.delete_cluster()

    @patch('kubernetes.config.load_kube_config', Mock())
    @patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints',
                  Mock(side_effect=[
                      k8s_client.rest.ApiException(502, ''),
                      k8s_client.rest.ApiException(500, '')
                  ]))
    def test_delete_sync_state(self):
        k = Kubernetes({
            'ttl': 30,
            'scope': 'test',
            'name': 'p-0',
            'retry_timeout': 10,
            'labels': {
                'f': 'b'
            },
            'use_endpoints': True,
            'pod_ip': '10.0.0.0'
        })
        self.assertFalse(k.delete_sync_state())

    def test_watch(self):
        self.k.set_ttl(10)
        self.k.watch(None, 0)
        self.k.watch(None, 0)
        with patch.object(
                k8s_watch.Watch, 'stream',
                Mock(side_effect=[
                    Exception, [], KeyboardInterrupt,
                    [{
                        'raw_object': {
                            'metadata': {
                                'resourceVersion': '2'
                            }
                        }
                    }]
                ])):
            self.assertFalse(self.k.watch('1', 2))
            self.assertRaises(KeyboardInterrupt, self.k.watch, '1', 2)
            self.assertTrue(self.k.watch('1', 2))
    def setUp(self):
        self.policy_template_processor_mock = Mock()
        self.is_policy_template_mock = Mock()

        self.function_policies = FunctionPolicies({}, self.policy_template_processor_mock)
        self.function_policies._is_policy_template = self.is_policy_template_mock
Beispiel #52
0
    metadata.update({'name': 'test-sync', 'annotations': {'leader': 'p-0'}})
    items.append(
        k8s_client.V1ConfigMap(metadata=k8s_client.V1ObjectMeta(**metadata)))
    metadata = k8s_client.V1ObjectMeta(resource_version='1')
    return k8s_client.V1ConfigMapList(metadata=metadata, items=items)


def mock_list_namespaced_pod(self, *args, **kwargs):
    metadata = k8s_client.V1ObjectMeta(resource_version='1',
                                       name='p-0',
                                       annotations={'status': '{}'})
    items = [k8s_client.V1Pod(metadata=metadata)]
    return k8s_client.V1PodList(items=items)


@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_config_map', Mock())
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_config_map', Mock())
class TestKubernetes(unittest.TestCase):
    @patch('kubernetes.config.load_kube_config', Mock())
    @patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map',
                  mock_list_namespaced_config_map)
    @patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod',
                  mock_list_namespaced_pod)
    def setUp(self):
        self.k = Kubernetes({
            'ttl': 30,
            'scope': 'test',
            'name': 'p-0',
            'retry_timeout': 10,
            'labels': {
                'f': 'b'
 def test_read(self):
     _result = Mock()
     self.obj.make_request = Mock(return_value=_result)
     self.obj.read()
     self.obj.make_request.called_once_with('GET')
Beispiel #54
0
 def _build_replication_data_handler(self):
     return Mock(wraps=super()._build_replication_data_handler())
Beispiel #55
0
 def connect(self, server):
     return Mock()
class TestFunctionPolicies(TestCase):

    def setUp(self):
        self.policy_template_processor_mock = Mock()
        self.is_policy_template_mock = Mock()

        self.function_policies = FunctionPolicies({}, self.policy_template_processor_mock)
        self.function_policies._is_policy_template = self.is_policy_template_mock


    @patch.object(FunctionPolicies, "_get_policies")
    def test_initialization_must_ingest_policies_from_resource_properties(self, get_policies_mock):
        resource_properties = {}
        dummy_policy_results = ["some", "policy", "statements"]
        expected_length = 3

        get_policies_mock.return_value = dummy_policy_results
        function_policies = FunctionPolicies(resource_properties, self.policy_template_processor_mock)

        get_policies_mock.assert_called_once_with(resource_properties)
        self.assertEqual(expected_length, len(function_policies))


    @patch.object(FunctionPolicies, "_get_policies")
    def test_get_must_yield_results_on_every_call(self, get_policies_mock):
        resource_properties = {} # Just some input
        dummy_policy_results = ["some", "policy", "statements"]
        expected_results = ["some", "policy", "statements"]

        # Setup _get_policies to return these dummy values for testing
        get_policies_mock.return_value = dummy_policy_results
        function_policies = FunctionPolicies(resource_properties, self.policy_template_processor_mock)

        # `list()` will implicitly call the `get()` repeatedly because it is a generator
        self.assertEqual(list(function_policies.get()), expected_results)


    @patch.object(FunctionPolicies, "_get_policies")
    def test_get_must_yield_no_results_with_no_policies(self, get_policies_mock):
        resource_properties = {} # Just some input
        dummy_policy_results = []
        expected_result = []

        # Setup _get_policies to return these dummy values for testing
        get_policies_mock.return_value = dummy_policy_results
        function_policies = FunctionPolicies(resource_properties, self.policy_template_processor_mock)

        # `list()` will implicitly call the `get()` repeatedly because it is a generator
        self.assertEqual(list(function_policies.get()), expected_result)

    def test_contains_policies_must_work_for_valid_input(self):
        resource_properties = {
            "Policies": "some managed policy"
        }

        self.assertTrue(self.function_policies._contains_policies(resource_properties))

    def test_contains_policies_must_ignore_resources_without_policies(self):
        resource_properties = {
            "some key": "value"
        }

        self.assertFalse(self.function_policies._contains_policies(resource_properties))

    def test_contains_policies_must_ignore_non_dict_resources(self):
        resource_properties = "some value"

        self.assertFalse(self.function_policies._contains_policies(resource_properties))

    def test_contains_policies_must_ignore_none_resources(self):
        resource_properties = None

        self.assertFalse(self.function_policies._contains_policies(resource_properties))

    def test_contains_policies_must_ignore_lowercase_property_name(self):
        # Property names are case sensitive
        resource_properties = {
            "policies": "some managed policy"
        }

        self.assertFalse(self.function_policies._contains_policies(resource_properties))

    def test_get_type_must_work_for_managed_policy(self):
        policy = "managed policy is a string"
        expected = PolicyTypes.MANAGED_POLICY

        result = self.function_policies._get_type(policy)
        self.assertEqual(result, expected)

    @patch("samtranslator.model.function_policies.is_instrinsic")
    def test_get_type_must_work_for_managed_policy_with_intrinsics(self, is_intrinsic_mock):
        policy = {
            "Ref": "somevalue"
        }
        expected = PolicyTypes.MANAGED_POLICY
        is_intrinsic_mock.return_value = True

        result = self.function_policies._get_type(policy)
        self.assertEqual(result, expected)

    def test_get_type_must_work_for_policy_statements(self):
        policy = {
            "Statement": "policy statements have a 'Statement' key"
        }
        expected = PolicyTypes.POLICY_STATEMENT

        result = self.function_policies._get_type(policy)
        self.assertEqual(result, expected)

    def test_get_type_must_work_for_policy_templates(self):
        policy = {
            "PolicyTemplate": "some template"
        }
        self.is_policy_template_mock.return_value = True
        expected = PolicyTypes.POLICY_TEMPLATE

        result = self.function_policies._get_type(policy)
        self.assertEqual(result, expected)

    def test_get_type_must_ignore_invalid_policy(self):
        policy = {
            "not-sure-what-this-is": "value"
        }
        # This is also not a policy template
        self.is_policy_template_mock.return_value = False
        expected = PolicyTypes.UNKNOWN

        result = self.function_policies._get_type(policy)
        self.assertEqual(result, expected)

    def test_get_type_must_ignore_invalid_policy_value_list(self):
        policy = ["invalid", "policy"]
        expected = PolicyTypes.UNKNOWN

        self.is_policy_template_mock.return_value = False

        result = self.function_policies._get_type(policy)
        self.assertEqual(result, expected)
        self.is_policy_template_mock.assert_called_once_with(policy)

    def test_get_policies_must_return_all_policies(self):
        policies = [
            "managed policy 1",
            {"Ref": "some managed policy"},
            {"Statement": "policy statement"},
            {"PolicyTemplate": "some value"},
            ["unknown", "policy"]
        ]
        resource_properties = {
            "Policies": policies
        }
        self.is_policy_template_mock.side_effect = [True, False] # Return True for policy template, False for the list

        expected = [
            PolicyEntry(data="managed policy 1", type=PolicyTypes.MANAGED_POLICY),
            PolicyEntry(data={"Ref": "some managed policy"}, type=PolicyTypes.MANAGED_POLICY),
            PolicyEntry(data={"Statement": "policy statement"}, type=PolicyTypes.POLICY_STATEMENT),
            PolicyEntry(data={"PolicyTemplate": "some value"}, type=PolicyTypes.POLICY_TEMPLATE),
            PolicyEntry(data=["unknown", "policy"], type=PolicyTypes.UNKNOWN),
        ]

        result = self.function_policies._get_policies(resource_properties)
        self.assertEqual(result, expected)

    def test_get_policies_must_ignore_if_resource_does_not_contain_policy(self):
        resource_properties = {
        }
        expected = []

        result = self.function_policies._get_policies(resource_properties)
        self.assertEqual(result, expected)

    def test_get_policies_must_ignore_if_policies_is_empty(self):
        resource_properties = {
            "Policies": []
        }
        expected = []

        result = self.function_policies._get_policies(resource_properties)
        self.assertEqual(result, expected)

    def test_get_policies_must_work_for_single_policy_string(self):
        resource_properties = {
            "Policies": "single managed policy"
        }
        expected = [
            PolicyEntry(data="single managed policy", type=PolicyTypes.MANAGED_POLICY)
        ]

        result = self.function_policies._get_policies(resource_properties)
        self.assertEqual(result, expected)

    def test_get_policies_must_work_for_single_dict_with_managed_policy_intrinsic(self):
        resource_properties = {
            "Policies": {
                "Ref": "some managed policy"
            }
        }
        expected = [
            PolicyEntry(data={"Ref": "some managed policy"}, type=PolicyTypes.MANAGED_POLICY)
        ]

        result = self.function_policies._get_policies(resource_properties)
        self.assertEqual(result, expected)

    def test_get_policies_must_work_for_single_dict_with_policy_statement(self):
        resource_properties = {
            "Policies": {
                "Statement": "some policy statement"
            }
        }
        expected = [
            PolicyEntry(data={"Statement": "some policy statement"}, type=PolicyTypes.POLICY_STATEMENT)
        ]

        result = self.function_policies._get_policies(resource_properties)
        self.assertEqual(result, expected)

    def test_get_policies_must_work_for_single_dict_of_policy_template(self):
        resource_properties = {
            "Policies": {
                "PolicyTemplate": "some template"
            }
        }
        self.is_policy_template_mock.return_value = True
        expected = [
            PolicyEntry(data={"PolicyTemplate": "some template"}, type=PolicyTypes.POLICY_TEMPLATE)
        ]

        result = self.function_policies._get_policies(resource_properties)
        self.assertEqual(result, expected)
        self.is_policy_template_mock.assert_called_once_with(resource_properties["Policies"])

    def test_get_policies_must_work_for_single_dict_of_invalid_policy_template(self):
        resource_properties = {
            "Policies": {
                "InvalidPolicyTemplate": "some template"
            }
        }
        self.is_policy_template_mock.return_value = False # Invalid policy template
        expected = [
            PolicyEntry(data={"InvalidPolicyTemplate": "some template"}, type=PolicyTypes.UNKNOWN)
        ]

        result = self.function_policies._get_policies(resource_properties)
        self.assertEqual(result, expected)
        self.is_policy_template_mock.assert_called_once_with({"InvalidPolicyTemplate": "some template"})

    def test_get_policies_must_work_for_unknown_policy_types(self):
        resource_properties = {
            "Policies": [
                1, 2, 3
            ]
        }
        expected = [
            PolicyEntry(data=1, type=PolicyTypes.UNKNOWN),
            PolicyEntry(data=2, type=PolicyTypes.UNKNOWN),
            PolicyEntry(data=3, type=PolicyTypes.UNKNOWN),
        ]

        self.is_policy_template_mock.return_value = False

        result = self.function_policies._get_policies(resource_properties)
        self.assertEqual(result, expected)

    def test_is_policy_template_must_detect_valid_policy_templates(self):
        template_name = "template_name"
        policy = {
            template_name: {
                "Param1": "foo"
            }
        }

        self.policy_template_processor_mock.has.return_value = True
        function_policies = FunctionPolicies({}, self.policy_template_processor_mock)

        self.assertTrue(function_policies._is_policy_template(policy))

        self.policy_template_processor_mock.has.assert_called_once_with(template_name)

    def test_is_policy_template_must_ignore_non_dict_policies(self):
        policy = [1,2,3]

        self.policy_template_processor_mock.has.return_value = True
        function_policies = FunctionPolicies({}, self.policy_template_processor_mock)

        self.assertFalse(function_policies._is_policy_template(policy))

        self.policy_template_processor_mock.has.assert_not_called()

    def test_is_policy_template_must_ignore_none_policies(self):
        policy = None

        function_policies = FunctionPolicies({}, self.policy_template_processor_mock)
        self.assertFalse(function_policies._is_policy_template(policy))

    def test_is_policy_template_must_ignore_dict_with_two_keys(self):
        template_name = "template_name"
        policy = {
            template_name: {"param1": "foo"},
            "A": "B"
        }

        self.policy_template_processor_mock.has.return_value = True

        function_policies = FunctionPolicies({}, self.policy_template_processor_mock)
        self.assertFalse(function_policies._is_policy_template(policy))

    def test_is_policy_template_must_ignore_non_policy_templates(self):
        template_name = "template_name"
        policy = {
            template_name: {"param1": "foo"}
        }

        self.policy_template_processor_mock.has.return_value = False

        function_policies = FunctionPolicies({}, self.policy_template_processor_mock)
        self.assertFalse(function_policies._is_policy_template(policy))

        self.policy_template_processor_mock.has.assert_called_once_with(template_name)

    def test_is_policy_template_must_return_false_without_the_processor(self):
        policy = {
            "template_name": {"param1": "foo"}
        }

        function_policies_obj = FunctionPolicies({}, None) # No policy template processor

        self.assertFalse(function_policies_obj._is_policy_template(policy))
        self.policy_template_processor_mock.has.assert_not_called()
class OfficerTimelineMobileQueryTestCase(TestCase):
    @patch(
        'officers.queries.OfficerTimelineMobileQuery.cr_new_timeline_serializer',
        return_value=Mock(data=[{'id': 1}, {'id': 2}])
    )
    def test_cr_timeline(self, cr_new_timeline_serializer_mock):
        officer = OfficerFactory(id=123)
        OfficerAllegationFactory(id=1, officer=officer, allegation__incident_date=datetime(2002, 2, 3, tzinfo=pytz.utc))
        OfficerAllegationFactory(id=2, officer=officer, allegation__incident_date=datetime(2003, 1, 5, tzinfo=pytz.utc))
        OfficerAllegationFactory(id=3, officer=officer, allegation__incident_date=None)

        unit_1 = PoliceUnitFactory(unit_name='001', description='District 001')
        unit_2 = PoliceUnitFactory(unit_name='002', description='District 002')
        OfficerHistoryFactory(
            officer=officer, unit=unit_1, effective_date=date(2002, 1, 3), end_date=date(2003, 1, 2)
        )
        OfficerHistoryFactory(
            officer=officer, unit=unit_2, effective_date=date(2003, 1, 3), end_date=date(2018, 1, 3)
        )
        SalaryFactory(
            year=2001, rank='Police Officer', officer=officer, rank_changed=True, spp_date=date(2001, 5, 3)
        )
        SalaryFactory(
            year=2002, rank='Senior Police Officer', officer=officer, rank_changed=True, spp_date=date(2002, 5, 3)
        )

        other_officer = OfficerFactory(id=456)
        OfficerAllegationFactory(id=4, officer=other_officer, start_date=date(2003, 1, 5))

        expect(OfficerTimelineMobileQuery(officer)._cr_timeline).to.eq([{'id': 1}, {'id': 2}])

        cr_timeline_queryset_arg = cr_new_timeline_serializer_mock.call_args[0][0]
        officer_allegation_1_arg, officer_allegation_2_arg = sorted(cr_timeline_queryset_arg, key=attrgetter('id'))

        expect(officer_allegation_1_arg.id).to.eq(1)
        expect(officer_allegation_1_arg.unit_name).to.eq('001')
        expect(officer_allegation_1_arg.unit_description).to.eq('District 001')
        expect(officer_allegation_1_arg.rank_name).to.eq('Police Officer')

        expect(officer_allegation_2_arg.id).to.eq(2)
        expect(officer_allegation_2_arg.unit_name).to.eq('002')
        expect(officer_allegation_2_arg.unit_description).to.eq('District 002')
        expect(officer_allegation_2_arg.rank_name).to.eq('Senior Police Officer')

    @patch(
        'officers.queries.OfficerTimelineMobileQuery.unit_change_new_timeline_serializer',
        return_value=Mock(data=[{'id': 1}, {'id': 2}])
    )
    def test_unit_change_timeline(self, unit_change_new_timeline_serializer_mock):
        officer = OfficerFactory(id=123, appointed_date=date(2001, 2, 3))
        officer_history_1 = OfficerHistoryFactory(
            officer=officer, effective_date=date(2002, 1, 3), end_date=date(2002, 1, 3)
        )
        officer_history_2 = OfficerHistoryFactory(
            officer=officer, effective_date=date(2003, 1, 3), end_date=date(2018, 1, 3)
        )
        OfficerHistoryFactory(
            officer=officer, effective_date=None, end_date=date(2018, 1, 3)
        )
        OfficerHistoryFactory(
            officer=officer, effective_date=None, end_date=date(2001, 2, 3)
        )
        SalaryFactory(
            year=2001, rank='Police Officer', officer=officer, rank_changed=True, spp_date=date(2001, 5, 3)
        )
        SalaryFactory(
            year=2002, rank='Senior Police Officer', officer=officer, rank_changed=True, spp_date=date(2002, 5, 3)
        )

        other_officer = OfficerFactory(id=456)
        OfficerHistoryFactory(
            officer=other_officer, effective_date=date(2002, 1, 3), end_date=date(2002, 1, 3)
        )

        expect(OfficerTimelineMobileQuery(officer)._unit_change_timeline).to.eq([{'id': 1}, {'id': 2}])

        unit_change_timeline_queryset_arg = unit_change_new_timeline_serializer_mock.call_args[0][0]
        officer_allegation_1_arg, officer_allegation_2_arg = unit_change_timeline_queryset_arg

        expect(officer_allegation_1_arg.id).to.eq(officer_history_1.id)
        expect(officer_allegation_1_arg.rank_name).to.eq('Police Officer')

        expect(officer_allegation_2_arg.id).to.eq(officer_history_2.id)
        expect(officer_allegation_2_arg.rank_name).to.eq('Senior Police Officer')

    @patch(
        'officers.queries.OfficerTimelineMobileQuery.rank_change_new_timeline_serializer',
        return_value=Mock(data=[{'id': 1}, {'id': 2}])
    )
    def test_rank_change_timeline(self, rank_change_new_timeline_serializer_mock):
        officer = OfficerFactory(id=123, appointed_date=date(2001, 2, 3))

        salary_1 = SalaryFactory(
            year=2001, rank='Police Officer', officer=officer, rank_changed=True, spp_date=date(2001, 5, 3)
        )
        salary_2 = SalaryFactory(
            year=2002, rank='Senior Police Officer', officer=officer, rank_changed=True, spp_date=date(2002, 5, 3)
        )
        SalaryFactory(
            year=2001, rank='Junior Police Officer', officer=officer, rank_changed=True, spp_date=date(2001, 2, 3)
        )
        SalaryFactory(
            year=2003, rank='Senior Police Officer', officer=officer, rank_changed=False, spp_date=date(2003, 5, 3)
        )

        unit_1 = PoliceUnitFactory(unit_name='001', description='District 001')
        unit_2 = PoliceUnitFactory(unit_name='002', description='District 002')
        OfficerHistoryFactory(
            officer=officer, unit=unit_1, effective_date=date(2001, 1, 3), end_date=date(2002, 1, 2)
        )
        OfficerHistoryFactory(
            officer=officer, unit=unit_2, effective_date=date(2002, 1, 3), end_date=date(2018, 1, 3)
        )

        other_officer = OfficerFactory(id=456)
        SalaryFactory(
            year=2001, rank='Police Officer', officer=other_officer, rank_changed=True, spp_date=date(2001, 5, 3)
        )

        expect(OfficerTimelineMobileQuery(officer)._rank_change_timeline).to.eq([{'id': 1}, {'id': 2}])

        rank_change_timeline_queryset_arg = rank_change_new_timeline_serializer_mock.call_args[0][0]

        salary_1_arg, salary_2_arg = rank_change_timeline_queryset_arg

        expect(salary_1_arg.id).to.eq(salary_1.id)
        expect(salary_1_arg.unit_name).to.eq('001')
        expect(salary_1_arg.unit_description).to.eq('District 001')

        expect(salary_2_arg.id).to.eq(salary_2.id)
        expect(salary_2_arg.unit_name).to.eq('002')
        expect(salary_2_arg.unit_description).to.eq('District 002')

    @patch(
        'officers.queries.OfficerTimelineMobileQuery.rank_change_new_timeline_serializer',
        return_value=Mock(data=[{'id': 1}])
    )
    def test_rank_change_timeline_no_officer_appointed_date(self, rank_change_new_timeline_serializer_mock):
        officer = OfficerFactory(id=123, appointed_date=None)

        salary = SalaryFactory(
            year=2001, rank='Police Officer', officer=officer, rank_changed=True, spp_date=date(2001, 5, 3)
        )

        expect(OfficerTimelineMobileQuery(officer)._rank_change_timeline).to.eq([{'id': 1}])

        rank_change_timeline_queryset_arg = rank_change_new_timeline_serializer_mock.call_args[0][0]

        salary_arg, = rank_change_timeline_queryset_arg
        expect(salary_arg.id).to.eq(salary.id)

    @patch(
        'officers.queries.OfficerTimelineMobileQuery.joined_new_timeline_serializer',
        return_value=Mock(data=[{'id': 1}])
    )
    def test_join_timeline(self, join_new_timeline_serializer_mock):
        officer = OfficerFactory(id=123, appointed_date=date(2001, 2, 3))

        SalaryFactory(
            year=2001, rank='Police Officer', officer=officer, rank_changed=True, spp_date=date(2001, 2, 3)
        )

        unit = PoliceUnitFactory(unit_name='001', description='District 001')
        OfficerHistoryFactory(
            officer=officer, unit=unit, effective_date=date(2001, 1, 3), end_date=date(2001, 2, 3)
        )

        expect(OfficerTimelineMobileQuery(officer)._join_timeline).to.eq([{'id': 1}])

        join_timeline_queryset_arg = join_new_timeline_serializer_mock.call_args[0][0]
        officer_arg, = join_timeline_queryset_arg

        expect(officer_arg.id).to.eq(officer.id)
        expect(officer_arg.unit_name).to.eq('001')
        expect(officer_arg.unit_description).to.eq('District 001')
        expect(officer_arg.rank_name).to.eq('Police Officer')

    def test_join_timeline_no_officer_appointed_date(self):
        officer = OfficerFactory(id=123, appointed_date=None)

        expect(OfficerTimelineMobileQuery(officer)._join_timeline).to.eq([])

    @patch(
        'officers.queries.OfficerTimelineMobileQuery.award_new_timeline_serializer',
        return_value=Mock(data=[{'id': 1}, {'id': 2}])
    )
    def test_award_timeline(self, award_new_timeline_serializer_mock):
        officer = OfficerFactory(id=123, appointed_date=date(2001, 2, 3))

        award_1 = AwardFactory(officer=officer, start_date=date(2002, 1, 3), award_type='Honored Police Star')
        award_2 = AwardFactory(officer=officer, start_date=date(2003, 1, 5), award_type='Life Saving Award')
        AwardFactory(officer=officer, start_date=date(2007, 2, 3), award_type='Complimentary Letter')
        AwardFactory(officer=officer, start_date=date(2008, 2, 3), award_type='Department Commendation')
        AwardFactory(officer=officer, start_date=date(2011, 2, 3), award_type='Citizen Honorable Mention')
        AwardFactory(officer=officer, start_date=None, award_type='Life Saving')

        unit_1 = PoliceUnitFactory(unit_name='001', description='District 001')
        unit_2 = PoliceUnitFactory(unit_name='002', description='District 002')
        OfficerHistoryFactory(
            officer=officer, unit=unit_1, effective_date=date(2002, 1, 3), end_date=date(2003, 1, 2)
        )
        OfficerHistoryFactory(
            officer=officer, unit=unit_2, effective_date=date(2003, 1, 3), end_date=date(2018, 1, 3)
        )
        SalaryFactory(
            year=2001, rank='Police Officer', officer=officer, rank_changed=True, spp_date=date(2001, 5, 3)
        )
        SalaryFactory(
            year=2002, rank='Senior Police Officer', officer=officer, rank_changed=True, spp_date=date(2002, 5, 3)
        )

        expect(OfficerTimelineMobileQuery(officer)._award_timeline).to.eq([{'id': 1}, {'id': 2}])

        award_timeline_queryset_arg = award_new_timeline_serializer_mock.call_args[0][0]
        award_1_arg, award_2_arg = sorted(award_timeline_queryset_arg, key=attrgetter('id'))

        expect(award_1_arg.id).to.eq(award_1.id)
        expect(award_1_arg.unit_name).to.eq('001')
        expect(award_1_arg.unit_description).to.eq('District 001')
        expect(award_1_arg.rank_name).to.eq('Police Officer')

        expect(award_2_arg.id).to.eq(award_2.id)
        expect(award_2_arg.unit_name).to.eq('002')
        expect(award_2_arg.unit_description).to.eq('District 002')
        expect(award_2_arg.rank_name).to.eq('Senior Police Officer')

    @patch(
        'officers.queries.OfficerTimelineMobileQuery.trr_new_timeline_serializer',
        return_value=Mock(data=[{'id': 1}, {'id': 2}])
    )
    def test_trr_timeline(self, trr_new_timeline_serializer_mock):
        officer = OfficerFactory(id=123, appointed_date=date(2001, 2, 3))

        trr_1 = TRRFactory(officer=officer, trr_datetime=datetime(2002, 1, 4, tzinfo=pytz.utc))
        trr_2 = TRRFactory(officer=officer, trr_datetime=datetime(2003, 1, 5, tzinfo=pytz.utc))

        unit_1 = PoliceUnitFactory(unit_name='001', description='District 001')
        unit_2 = PoliceUnitFactory(unit_name='002', description='District 002')
        OfficerHistoryFactory(
            officer=officer, unit=unit_1, effective_date=date(2002, 1, 3), end_date=date(2003, 1, 2)
        )
        OfficerHistoryFactory(
            officer=officer, unit=unit_2, effective_date=date(2003, 1, 3), end_date=date(2018, 1, 3)
        )
        SalaryFactory(
            year=2001, rank='Police Officer', officer=officer, rank_changed=True, spp_date=date(2001, 5, 3)
        )
        SalaryFactory(
            year=2002, rank='Senior Police Officer', officer=officer, rank_changed=True, spp_date=date(2002, 5, 3)
        )

        expect(OfficerTimelineMobileQuery(officer)._trr_timeline).to.eq([{'id': 1}, {'id': 2}])

        trr_timeline_queryset_arg = trr_new_timeline_serializer_mock.call_args[0][0]
        trr_1_arg, trr_2_arg = sorted(trr_timeline_queryset_arg, key=attrgetter('id'))

        expect(trr_1_arg.id).to.eq(trr_1.id)
        expect(trr_1_arg.unit_name).to.eq('001')
        expect(trr_1_arg.unit_description).to.eq('District 001')
        expect(trr_1_arg.rank_name).to.eq('Police Officer')

        expect(trr_2_arg.id).to.eq(trr_2.id)
        expect(trr_2_arg.unit_name).to.eq('002')
        expect(trr_2_arg.unit_description).to.eq('District 002')
        expect(trr_2_arg.rank_name).to.eq('Senior Police Officer')

    @patch(
        'officers.queries.OfficerTimelineMobileQuery._cr_timeline',
        new_callable=PropertyMock,
        return_value=[
            {'id': 1, 'date_sort': date(2000, 1, 1), 'priority_sort': 30},
            {'id': 2, 'date_sort': date(2001, 1, 2), 'priority_sort': 30},
        ]
    )
    @patch(
        'officers.queries.OfficerTimelineMobileQuery._unit_change_timeline',
        new_callable=PropertyMock,
        return_value=[
            {'id': 3, 'date_sort': date(2000, 1, 2), 'priority_sort': 20},
            {'id': 4, 'date_sort': date(2001, 1, 2), 'priority_sort': 20},
        ]
    )
    @patch(
        'officers.queries.OfficerTimelineMobileQuery._rank_change_timeline',
        new_callable=PropertyMock,
        return_value=[
            {'id': 5, 'date_sort': date(2000, 1, 3), 'priority_sort': 25},
            {'id': 6, 'date_sort': date(2001, 1, 2), 'priority_sort': 25},
        ]
    )
    @patch(
        'officers.queries.OfficerTimelineMobileQuery._join_timeline',
        new_callable=PropertyMock,
        return_value=[
            {'id': 7, 'date_sort': date(2000, 1, 1), 'priority_sort': 10},
        ]
    )
    @patch(
        'officers.queries.OfficerTimelineMobileQuery._award_timeline',
        new_callable=PropertyMock,
        return_value=[
            {'id': 8, 'date_sort': date(2000, 1, 4), 'priority_sort': 40},
            {'id': 9, 'date_sort': date(2001, 1, 2), 'priority_sort': 40},
        ]
    )
    @patch(
        'officers.queries.OfficerTimelineMobileQuery._trr_timeline',
        new_callable=PropertyMock,
        return_value=[
            {'id': 10, 'date_sort': date(2000, 1, 4), 'priority_sort': 50},
            {'id': 11, 'date_sort': date(2001, 1, 2), 'priority_sort': 50},
        ]
    )
    def test_execute(self, _trr, _award, _join, _rank, _unit, _cr):
        sorted_timeline = OfficerTimelineMobileQuery(None).execute()
        sorted_timeline_ids = [item['id'] for item in sorted_timeline]
        expect(sorted_timeline_ids).to.eq([11, 9, 2, 6, 4, 10, 8, 5, 3, 1, 7])
 def setUp(self):
     self.client = Mock()
     self.obj = StorageObject('CONTAINER', 'NAME', client=self.client)
Beispiel #59
0
    def test_can_get_facts(self):
        page = PageFactory.create(url='http://my-site.com')

        reviewer = Reviewer(
            api_url='http://localhost:2368',
            page_uuid=page.uuid,
            page_url=page.url,
            page_score=0.0,
            config=Config(),
            facters=[]
        )

        content = '<html><img src="test.png" alt="a" title="b" /><img src="" /></html>'

        result = {
            'url': page.url,
            'status': 200,
            'content': content,
            'html': lxml.html.fromstring(content)
        }
        reviewer.responses[page.url] = result
        reviewer._wait_for_async_requests = Mock()
        reviewer.save_review = Mock()
        response = Mock(status_code=200, text=content, headers={})
        reviewer.content_loaded(page.url, response)

        facter = ImageFacter(reviewer)
        facter.add_fact = Mock()

        facter.async_get = Mock()
        facter.get_facts()

        expect(facter.review.data).to_length(3)

        expect(facter.review.data).to_include('page.all_images')

        img = facter.review.data['page.all_images'][0]
        expect(img.tag).to_equal('img')
        expect(img.get('src')).to_equal('test.png')

        expect(facter.review.data).to_include('page.images')
        expect(facter.review.data['page.images']).to_equal(set([]))

        expect(facter.review.data).to_include('total.size.img')
        expect(facter.review.data['total.size.img']).to_equal(0)

        expect(facter.add_fact.call_args_list).to_include(
            call(
                key='page.images',
                value=set([]),
            ))

        expect(facter.add_fact.call_args_list).to_include(
            call(
                key='total.size.img',
                value=0,
            )),

        expect(facter.add_fact.call_args_list).to_include(
            call(
                key='total.requests.img',
                value=1,
            ))

        facter.async_get.assert_called_once_with(
            'http://my-site.com/test.png',
            facter.handle_url_loaded
        )
Beispiel #60
0
 def setup(self):
     Defaults.set_platform_name('x86_64')
     xml_data = Mock()
     xml_data.get_name = Mock(
         return_value='some-disk-image'
     )
     self.xml_state = Mock()
     self.xml_state.xml_data = xml_data
     self.xml_state.get_image_version = Mock(
         return_value='1.2.3'
     )
     self.vagrantconfig = Mock()
     self.vagrantconfig.get_embedded_vagrantfile = Mock(
         return_value=None
     )
     self.vagrantconfig.get_virtualsize = Mock(
         return_value=42
     )
     self.runtime_config = Mock()
     self.runtime_config.get_bundle_compression.return_value = False
     kiwi.storage.subformat.base.RuntimeConfig = Mock(
         return_value=self.runtime_config
     )
     self.disk_format = DiskFormatVagrantLibVirt(
         self.xml_state, 'root_dir', 'target_dir',
         {'vagrantconfig': self.vagrantconfig}
     )
     assert self.disk_format.image_format == 'vagrant.libvirt.box'
     assert self.disk_format.provider == 'libvirt'