Exemple #1
0
 def test_list_security_group_rules_pagination(self):
     resources = "security_group_rules"
     cmd = securitygroup.ListSecurityGroupRule(test_cli20.MyApp(sys.stdout),
                                               None)
     self.mox.StubOutWithMock(securitygroup.ListSecurityGroupRule,
                              "extend_list")
     securitygroup.ListSecurityGroupRule.extend_list(
         mox.IsA(list), mox.IgnoreArg())
     self._test_list_resources_with_pagination(resources, cmd)
 def test_list_security_group_rules_sort(self, mock_extend_list):
     resources = "security_group_rules"
     cmd = securitygroup.ListSecurityGroupRule(
         test_cli20.MyApp(sys.stdout), None)
     self._test_list_resources(resources, cmd,
                               sort_key=["name", "id"],
                               sort_dir=["asc", "desc"])
     mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
                                              mock.ANY)
    def _test_list_security_group_rules_extend(self, api_data, expected,
                                               args=(), conv=True,
                                               query_fields=None):
        def setup_list_stub(resources, data, query):
            reses = {resources: data}
            resstr = self.client.serialize(reses)
            resp = (test_cli20.MyResp(200), resstr)
            path = getattr(self.client, resources + '_path')
            self.client.httpclient.request(
                test_cli20.MyUrlComparator(
                    test_cli20.end_url(path, query),
                    self.client),
                'GET',
                body=None,
                headers=mox.ContainsKeyValue(
                    'X-Auth-Token', test_cli20.TOKEN)).AndReturn(resp)

        cmd = securitygroup.ListSecurityGroupRule(
            test_cli20.MyApp(sys.stdout), None)
        self.mox.StubOutWithMock(cmd, 'get_client')
        self.mox.StubOutWithMock(self.client.httpclient, 'request')
        cmd.get_client().AndReturn(self.client)
        query = ''
        if query_fields:
            query = '&'.join(['fields=' + f for f in query_fields])
        setup_list_stub('security_group_rules', api_data, query)
        if conv:
            cmd.get_client().AndReturn(self.client)
            sec_ids = set()
            for n in api_data:
                sec_ids.add(n['security_group_id'])
                if n.get('remote_group_id'):
                    sec_ids.add(n['remote_group_id'])
            filters = ''
            for id in sec_ids:
                filters = filters + "&id=%s" % id
            setup_list_stub('security_groups',
                            [{'id': 'myid1', 'name': 'group1'},
                             {'id': 'myid2', 'name': 'group2'},
                             {'id': 'myid3', 'name': 'group3'}],
                            query='fields=id&fields=name' + filters)
        self.mox.ReplayAll()

        cmd_parser = cmd.get_parser('list_security_group_rules')
        parsed_args = cmd_parser.parse_args(args)
        result = cmd.take_action(parsed_args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
        # Check columns
        self.assertEqual(expected['cols'], result[0])
        # Check data
        _result = [x for x in result[1]]
        self.assertEqual(len(expected['data']), len(_result))
        for res, exp in zip(_result, expected['data']):
            self.assertEqual(len(exp), len(res))
            self.assertEqual(exp, res)
Exemple #4
0
 def test_list_security_group_rules_sort(self):
     resources = "security_group_rules"
     cmd = securitygroup.ListSecurityGroupRule(
         test_cli20.MyApp(sys.stdout), None)
     self.mox.StubOutWithMock(securitygroup.ListSecurityGroupRule,
                              "extend_list")
     securitygroup.ListSecurityGroupRule.extend_list(mox.IsA(list),
                                                     mox.IgnoreArg())
     self._test_list_resources(resources, cmd,
                               sort_key=["name", "id"],
                               sort_dir=["asc", "desc"])
    def test_extend_list_exceed_max_uri_len(self):
        data = [{
            'name': 'default',
            'security_group_id': 'secgroupid%02d' % i,
            'remote_group_id': 'remgroupid%02d' % i
        } for i in range(10)]
        data.append({
            'name': 'default',
            'security_group_id': 'secgroupid10',
            'remote_group_id': None
        })
        resources = "security_groups"

        cmd = securitygroup.ListSecurityGroupRule(test_cli20.MyApp(sys.stdout),
                                                  None)
        path = getattr(self.client, resources + '_path')
        responses = self._build_test_data(data, excess=1)

        known_args, _vs = cmd.get_parser('list' + resources).parse_known_args()
        mock_request_side_effects = []
        mock_request_calls = []
        mock_check_uri_side_effects = [exceptions.RequestURITooLong(excess=1)]
        mock_check_uri_calls = [mock.call(mock.ANY)]
        for item in responses:
            mock_request_side_effects.append(item['response'])
            mock_request_calls.append(
                mock.call(test_cli20.MyUrlComparator(
                    test_cli20.end_url(path, item['filter']), self.client),
                          'GET',
                          body=None,
                          headers=test_cli20.ContainsKeyValue(
                              {'X-Auth-Token': test_cli20.TOKEN})))
            mock_check_uri_side_effects.append(None)
            mock_check_uri_calls.append(mock.call(mock.ANY))

        with mock.patch.object(cmd, "get_client",
                               return_value=self.client) as mock_get_client, \
                mock.patch.object(self.client.httpclient,
                                  "request") as mock_request, \
                mock.patch.object(self.client.httpclient,
                                  "_check_uri_length") as mock_check_uri:
            mock_request.side_effect = mock_request_side_effects
            mock_check_uri.side_effect = mock_check_uri_side_effects
            cmd.extend_list(data, known_args)

        mock_get_client.assert_called_once_with()
        mock_request.assert_has_calls(mock_request_calls)
        mock_check_uri.assert_has_calls(mock_check_uri_calls)
        self.assertEqual(len(mock_request_calls), mock_request.call_count)
        self.assertEqual(len(mock_check_uri_calls), mock_check_uri.call_count)
    def _test_extend_list(self, mox_calls, data):
        resources = "security_groups"

        cmd = securitygroup.ListSecurityGroupRule(test_cli20.MyApp(sys.stdout),
                                                  None)
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")

        cmd.get_client().MultipleTimes().AndReturn(self.client)
        path = getattr(self.client, resources + '_path')
        mox_calls(path, data)
        self.mox.ReplayAll()
        known_args, _vs = cmd.get_parser('list' + resources).parse_known_args()

        cmd.extend_list(data, known_args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
Exemple #7
0
    def _test_extend_list(self, mox_calls):
        resources = "security_groups"

        data = [{'name': 'default',
                 'security_group_id': 'secgroupid%02d' % i,
                 'remote_group_id': 'remgroupid%02d' % i}
                for i in range(10)]

        cmd = securitygroup.ListSecurityGroupRule(
            test_cli20.MyApp(sys.stdout), None)
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")

        cmd.get_client().MultipleTimes().AndReturn(self.client)
        path = getattr(self.client, resources + '_path')
        mox_calls(path, data)
        self.mox.ReplayAll()
        known_args, _vs = cmd.get_parser(
            'list' + resources).parse_known_args()

        cmd.extend_list(data, known_args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
    def _test_list_security_group_rules_extend(self,
                                               data=None,
                                               expected=None,
                                               args=(),
                                               conv=True,
                                               query_field=False):
        def setup_list_stub(resources, data, query):
            reses = {resources: data}
            resstr = self.client.serialize(reses)
            resp = (test_cli20.MyResp(200), resstr)
            path = getattr(self.client, resources + '_path')
            self.client.httpclient.request(
                test_cli20.MyUrlComparator(test_cli20.end_url(path, query),
                                           self.client),
                'GET',
                body=None,
                headers=mox.ContainsKeyValue('X-Auth-Token',
                                             test_cli20.TOKEN)).AndReturn(resp)

        # Setup the default data
        _data = {
            'cols': ['id', 'security_group_id', 'remote_group_id'],
            'data': [('ruleid1', 'myid1', 'myid1'),
                     ('ruleid2', 'myid2', 'myid3'),
                     ('ruleid3', 'myid2', 'myid2')]
        }
        _expected = {
            'cols': ['id', 'security_group', 'remote_group'],
            'data': [('ruleid1', 'group1', 'group1'),
                     ('ruleid2', 'group2', 'group3'),
                     ('ruleid3', 'group2', 'group2')]
        }
        if data is None:
            data = _data
        list_data = [dict(zip(data['cols'], d)) for d in data['data']]
        if expected is None:
            expected = {}
        expected['cols'] = expected.get('cols', _expected['cols'])
        expected['data'] = expected.get('data', _expected['data'])

        cmd = securitygroup.ListSecurityGroupRule(test_cli20.MyApp(sys.stdout),
                                                  None)
        self.mox.StubOutWithMock(cmd, 'get_client')
        self.mox.StubOutWithMock(self.client.httpclient, 'request')
        cmd.get_client().AndReturn(self.client)
        query = ''
        if query_field:
            query = '&'.join(['fields=' + f for f in data['cols']])
        setup_list_stub('security_group_rules', list_data, query)
        if conv:
            cmd.get_client().AndReturn(self.client)
            sec_ids = set()
            for n in data['data']:
                sec_ids.add(n[1])
                sec_ids.add(n[2])
            filters = ''
            for id in sec_ids:
                filters = filters + "&id=%s" % id
            setup_list_stub('security_groups', [{
                'id': 'myid1',
                'name': 'group1'
            }, {
                'id': 'myid2',
                'name': 'group2'
            }, {
                'id': 'myid3',
                'name': 'group3'
            }],
                            query='fields=id&fields=name' + filters)
        self.mox.ReplayAll()

        cmd_parser = cmd.get_parser('list_security_group_rules')
        parsed_args = cmd_parser.parse_args(args)
        result = cmd.get_data(parsed_args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
        # Check columns
        self.assertEqual(result[0], expected['cols'])
        # Check data
        _result = [x for x in result[1]]
        self.assertEqual(len(_result), len(expected['data']))
        for res, exp in zip(_result, expected['data']):
            self.assertEqual(len(res), len(exp))
            self.assertEqual(res, exp)
    def _test_list_security_group_rules_extend(self,
                                               api_data,
                                               expected,
                                               args=(),
                                               conv=True,
                                               query_fields=None):
        def setup_list_stub(resources, data, query, mock_calls, mock_returns):
            reses = {resources: data}
            resstr = self.client.serialize(reses)
            resp = (test_cli20.MyResp(200), resstr)
            path = getattr(self.client, resources + '_path')
            mock_calls.append(
                mock.call(test_cli20.MyUrlComparator(
                    test_cli20.end_url(path, query), self.client),
                          'GET',
                          body=None,
                          headers=test_cli20.ContainsKeyValue(
                              {'X-Auth-Token': test_cli20.TOKEN})))
            mock_returns.append(resp)

        cmd = securitygroup.ListSecurityGroupRule(test_cli20.MyApp(sys.stdout),
                                                  None)
        query = ''
        if query_fields:
            query = '&'.join(['fields=' + f for f in query_fields])
        mock_request_calls = []
        mock_request_returns = []
        setup_list_stub('security_group_rules', api_data, query,
                        mock_request_calls, mock_request_returns)
        if conv:
            sec_ids = set()
            for n in api_data:
                sec_ids.add(n['security_group_id'])
                if n.get('remote_group_id'):
                    sec_ids.add(n['remote_group_id'])
            filters = ''
            for id in sec_ids:
                filters = filters + "&id=%s" % id
            setup_list_stub('security_groups', [{
                'id': 'myid1',
                'name': 'group1'
            }, {
                'id': 'myid2',
                'name': 'group2'
            }, {
                'id': 'myid3',
                'name': 'group3'
            }], 'fields=id&fields=name' + filters, mock_request_calls,
                            mock_request_returns)

        cmd_parser = cmd.get_parser('list_security_group_rules')
        parsed_args = cmd_parser.parse_args(args)

        with mock.patch.object(cmd, "get_client",
                               return_value=self.client) as mock_get_client, \
                mock.patch.object(self.client.httpclient,
                                  "request") as mock_request:
            mock_request.side_effect = mock_request_returns
            result = cmd.take_action(parsed_args)

        self.assert_mock_multiple_calls_with_same_arguments(
            mock_get_client, mock.call(), None)
        mock_request.assert_has_calls(mock_request_calls)
        self.assertEqual(len(mock_request_calls), mock_request.call_count)
        self.assertEqual(expected['cols'], result[0])
        # Check data
        _result = [x for x in result[1]]
        self.assertEqual(len(expected['data']), len(_result))
        for res, exp in zip(_result, expected['data']):
            self.assertEqual(len(exp), len(res))
            self.assertEqual(exp, res)