blob: 966b30d35a5f4f49be85669de0b5922eb56daa95 [file] [log] [blame]
Daniel Mellado3c0aeab2016-01-29 11:30:25 +00001# Copyright 2012 OpenStack Foundation
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may
5# not use this file except in compliance with the License. You may obtain
6# a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations
14# under the License.
15
Ihar Hrachyshka59382252016-04-05 15:54:33 +020016import functools
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +020017import math
Ihar Hrachyshka59382252016-04-05 15:54:33 +020018
Daniel Mellado3c0aeab2016-01-29 11:30:25 +000019import netaddr
Chandan Kumarc125fd12017-11-15 19:41:01 +053020from neutron_lib import constants as const
21from tempest.common import utils as tutils
Daniel Mellado3c0aeab2016-01-29 11:30:25 +000022from tempest.lib.common.utils import data_utils
23from tempest.lib import exceptions as lib_exc
24from tempest import test
25
Chandan Kumar667d3d32017-09-22 12:24:06 +053026from neutron_tempest_plugin.api import clients
27from neutron_tempest_plugin.common import constants
28from neutron_tempest_plugin.common import utils
29from neutron_tempest_plugin import config
30from neutron_tempest_plugin import exceptions
Daniel Mellado3c0aeab2016-01-29 11:30:25 +000031
32CONF = config.CONF
33
34
35class BaseNetworkTest(test.BaseTestCase):
36
37 """
38 Base class for the Neutron tests that use the Tempest Neutron REST client
39
40 Per the Neutron API Guide, API v1.x was removed from the source code tree
41 (docs.openstack.org/api/openstack-network/2.0/content/Overview-d1e71.html)
42 Therefore, v2.x of the Neutron API is assumed. It is also assumed that the
43 following options are defined in the [network] section of etc/tempest.conf:
44
45 project_network_cidr with a block of cidr's from which smaller blocks
46 can be allocated for tenant networks
47
48 project_network_mask_bits with the mask bits to be used to partition
49 the block defined by tenant-network_cidr
50
51 Finally, it is assumed that the following option is defined in the
52 [service_available] section of etc/tempest.conf
53
54 neutron as True
55 """
56
57 force_tenant_isolation = False
58 credentials = ['primary']
59
60 # Default to ipv4.
Federico Ressi0ddc93b2018-04-09 12:01:48 +020061 _ip_version = const.IP_VERSION_4
Daniel Mellado3c0aeab2016-01-29 11:30:25 +000062
Federico Ressi61b564e2018-07-06 08:10:31 +020063 # Derive from BaseAdminNetworkTest class to have this initialized
64 admin_client = None
65
Daniel Mellado3c0aeab2016-01-29 11:30:25 +000066 @classmethod
67 def get_client_manager(cls, credential_type=None, roles=None,
68 force_new=None):
Genadi Chereshnyacc395c02016-07-25 12:17:37 +030069 manager = super(BaseNetworkTest, cls).get_client_manager(
70 credential_type=credential_type,
71 roles=roles,
72 force_new=force_new
73 )
Daniel Mellado3c0aeab2016-01-29 11:30:25 +000074 # Neutron uses a different clients manager than the one in the Tempest
Jens Harbott860b46a2017-11-15 21:23:15 +000075 # save the original in case mixed tests need it
76 if credential_type == 'primary':
77 cls.os_tempest = manager
Daniel Mellado3c0aeab2016-01-29 11:30:25 +000078 return clients.Manager(manager.credentials)
79
80 @classmethod
81 def skip_checks(cls):
82 super(BaseNetworkTest, cls).skip_checks()
83 if not CONF.service_available.neutron:
84 raise cls.skipException("Neutron support is required")
Federico Ressi0ddc93b2018-04-09 12:01:48 +020085 if (cls._ip_version == const.IP_VERSION_6 and
86 not CONF.network_feature_enabled.ipv6):
Daniel Mellado3c0aeab2016-01-29 11:30:25 +000087 raise cls.skipException("IPv6 Tests are disabled.")
Jakub Libosvar1982aa12017-05-30 11:15:33 +000088 for req_ext in getattr(cls, 'required_extensions', []):
Chandan Kumarc125fd12017-11-15 19:41:01 +053089 if not tutils.is_extension_enabled(req_ext, 'network'):
Jakub Libosvar1982aa12017-05-30 11:15:33 +000090 msg = "%s extension not enabled." % req_ext
91 raise cls.skipException(msg)
Daniel Mellado3c0aeab2016-01-29 11:30:25 +000092
93 @classmethod
94 def setup_credentials(cls):
95 # Create no network resources for these test.
96 cls.set_network_resources()
97 super(BaseNetworkTest, cls).setup_credentials()
98
99 @classmethod
100 def setup_clients(cls):
101 super(BaseNetworkTest, cls).setup_clients()
fumihiko kakumaa216fc12017-07-14 10:43:29 +0900102 cls.client = cls.os_primary.network_client
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000103
104 @classmethod
105 def resource_setup(cls):
106 super(BaseNetworkTest, cls).resource_setup()
107
108 cls.networks = []
Miguel Lavalle124378b2016-09-21 16:41:47 -0500109 cls.admin_networks = []
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000110 cls.subnets = []
Kevin Bentonba3651c2017-09-01 17:13:01 -0700111 cls.admin_subnets = []
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000112 cls.ports = []
113 cls.routers = []
114 cls.floating_ips = []
115 cls.metering_labels = []
116 cls.service_profiles = []
117 cls.flavors = []
118 cls.metering_label_rules = []
119 cls.qos_rules = []
120 cls.qos_policies = []
121 cls.ethertype = "IPv" + str(cls._ip_version)
122 cls.address_scopes = []
123 cls.admin_address_scopes = []
124 cls.subnetpools = []
125 cls.admin_subnetpools = []
Itzik Brownbac51dc2016-10-31 12:25:04 +0000126 cls.security_groups = []
Chandan Kumarc125fd12017-11-15 19:41:01 +0530127 cls.projects = []
Nguyen Phuong An67993fc2017-11-24 11:30:25 +0700128 cls.log_objects = []
Federico Ressi0ddc93b2018-04-09 12:01:48 +0200129 cls.reserved_subnet_cidrs = set()
Federico Ressiab286e42018-06-19 09:52:10 +0200130 cls.keypairs = []
Federico Ressi82e83e32018-07-03 14:19:55 +0200131 cls.trunks = []
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000132
133 @classmethod
134 def resource_cleanup(cls):
135 if CONF.service_available.neutron:
Federico Ressi82e83e32018-07-03 14:19:55 +0200136 # Clean up trunks
137 for trunk in cls.trunks:
138 cls._try_delete_resource(cls.delete_trunk, trunk)
139
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000140 # Clean up floating IPs
141 for floating_ip in cls.floating_ips:
142 cls._try_delete_resource(cls.client.delete_floatingip,
143 floating_ip['id'])
144 # Clean up routers
145 for router in cls.routers:
146 cls._try_delete_resource(cls.delete_router,
147 router)
148 # Clean up metering label rules
149 for metering_label_rule in cls.metering_label_rules:
150 cls._try_delete_resource(
151 cls.admin_client.delete_metering_label_rule,
152 metering_label_rule['id'])
153 # Clean up metering labels
154 for metering_label in cls.metering_labels:
155 cls._try_delete_resource(
156 cls.admin_client.delete_metering_label,
157 metering_label['id'])
158 # Clean up flavors
159 for flavor in cls.flavors:
160 cls._try_delete_resource(
161 cls.admin_client.delete_flavor,
162 flavor['id'])
163 # Clean up service profiles
164 for service_profile in cls.service_profiles:
165 cls._try_delete_resource(
166 cls.admin_client.delete_service_profile,
167 service_profile['id'])
168 # Clean up ports
169 for port in cls.ports:
170 cls._try_delete_resource(cls.client.delete_port,
171 port['id'])
172 # Clean up subnets
173 for subnet in cls.subnets:
174 cls._try_delete_resource(cls.client.delete_subnet,
175 subnet['id'])
Kevin Bentonba3651c2017-09-01 17:13:01 -0700176 # Clean up admin subnets
177 for subnet in cls.admin_subnets:
178 cls._try_delete_resource(cls.admin_client.delete_subnet,
179 subnet['id'])
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000180 # Clean up networks
181 for network in cls.networks:
Federico Ressi61b564e2018-07-06 08:10:31 +0200182 cls._try_delete_resource(cls.delete_network, network)
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000183
Miguel Lavalle124378b2016-09-21 16:41:47 -0500184 # Clean up admin networks
185 for network in cls.admin_networks:
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000186 cls._try_delete_resource(cls.admin_client.delete_network,
187 network['id'])
188
Itzik Brownbac51dc2016-10-31 12:25:04 +0000189 # Clean up security groups
190 for secgroup in cls.security_groups:
191 cls._try_delete_resource(cls.client.delete_security_group,
192 secgroup['id'])
193
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000194 for subnetpool in cls.subnetpools:
195 cls._try_delete_resource(cls.client.delete_subnetpool,
196 subnetpool['id'])
197
198 for subnetpool in cls.admin_subnetpools:
199 cls._try_delete_resource(cls.admin_client.delete_subnetpool,
200 subnetpool['id'])
201
202 for address_scope in cls.address_scopes:
203 cls._try_delete_resource(cls.client.delete_address_scope,
204 address_scope['id'])
205
206 for address_scope in cls.admin_address_scopes:
207 cls._try_delete_resource(
208 cls.admin_client.delete_address_scope,
209 address_scope['id'])
210
Chandan Kumarc125fd12017-11-15 19:41:01 +0530211 for project in cls.projects:
212 cls._try_delete_resource(
213 cls.identity_admin_client.delete_project,
214 project['id'])
215
Sławek Kapłońskie100c4d2017-08-23 21:18:34 +0000216 # Clean up QoS rules
217 for qos_rule in cls.qos_rules:
218 cls._try_delete_resource(cls.admin_client.delete_qos_rule,
219 qos_rule['id'])
220 # Clean up QoS policies
221 # as all networks and ports are already removed, QoS policies
222 # shouldn't be "in use"
223 for qos_policy in cls.qos_policies:
224 cls._try_delete_resource(cls.admin_client.delete_qos_policy,
225 qos_policy['id'])
226
Nguyen Phuong An67993fc2017-11-24 11:30:25 +0700227 # Clean up log_objects
228 for log_object in cls.log_objects:
229 cls._try_delete_resource(cls.admin_client.delete_log,
230 log_object['id'])
231
Federico Ressiab286e42018-06-19 09:52:10 +0200232 for keypair in cls.keypairs:
233 cls._try_delete_resource(cls.delete_keypair, keypair)
234
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000235 super(BaseNetworkTest, cls).resource_cleanup()
236
237 @classmethod
238 def _try_delete_resource(cls, delete_callable, *args, **kwargs):
239 """Cleanup resources in case of test-failure
240
241 Some resources are explicitly deleted by the test.
242 If the test failed to delete a resource, this method will execute
243 the appropriate delete methods. Otherwise, the method ignores NotFound
244 exceptions thrown for resources that were correctly deleted by the
245 test.
246
247 :param delete_callable: delete method
248 :param args: arguments for delete method
249 :param kwargs: keyword arguments for delete method
250 """
251 try:
252 delete_callable(*args, **kwargs)
253 # if resource is not found, this means it was deleted in the test
254 except lib_exc.NotFound:
255 pass
256
257 @classmethod
Federico Ressi61b564e2018-07-06 08:10:31 +0200258 def create_network(cls, network_name=None, client=None, external=None,
259 shared=None, provider_network_type=None,
260 provider_physical_network=None,
261 provider_segmentation_id=None, **kwargs):
262 """Create a network.
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000263
Federico Ressi61b564e2018-07-06 08:10:31 +0200264 When client is not provider and admin_client is attribute is not None
265 (for example when using BaseAdminNetworkTest base class) and using any
266 of the convenience parameters (external, shared, provider_network_type,
267 provider_physical_network and provider_segmentation_id) it silently
268 uses admin_client. If the network is not shared then it uses the same
269 project_id as regular client.
270
271 :param network_name: Human-readable name of the network
272
273 :param client: client to be used for connecting to network service
274
275 :param external: indicates whether the network has an external routing
276 facility that's not managed by the networking service.
277
278 :param shared: indicates whether this resource is shared across all
279 projects. By default, only administrative users can change this value.
280 If True and admin_client attribute is not None, then the network is
281 created under administrative project.
282
283 :param provider_network_type: the type of physical network that this
284 network should be mapped to. For example, 'flat', 'vlan', 'vxlan', or
285 'gre'. Valid values depend on a networking back-end.
286
287 :param provider_physical_network: the physical network where this
288 network should be implemented. The Networking API v2.0 does not provide
289 a way to list available physical networks. For example, the Open
290 vSwitch plug-in configuration file defines a symbolic name that maps to
291 specific bridges on each compute host.
292
293 :param provider_segmentation_id: The ID of the isolated segment on the
294 physical network. The network_type attribute defines the segmentation
295 model. For example, if the network_type value is 'vlan', this ID is a
296 vlan identifier. If the network_type value is 'gre', this ID is a gre
297 key.
298
299 :param **kwargs: extra parameters to be forwarded to network service
300 """
301
302 name = (network_name or kwargs.pop('name', None) or
303 data_utils.rand_name('test-network-'))
304
305 # translate convenience parameters
306 admin_client_required = False
307 if provider_network_type:
308 admin_client_required = True
309 kwargs['provider:network_type'] = provider_network_type
310 if provider_physical_network:
311 admin_client_required = True
312 kwargs['provider:physical_network'] = provider_physical_network
313 if provider_segmentation_id:
314 admin_client_required = True
315 kwargs['provider:segmentation_id'] = provider_segmentation_id
316 if external is not None:
317 admin_client_required = True
318 kwargs['router:external'] = bool(external)
319 if shared is not None:
320 admin_client_required = True
321 kwargs['shared'] = bool(shared)
322
323 if not client:
324 if admin_client_required and cls.admin_client:
325 # For convenience silently switch to admin client
326 client = cls.admin_client
327 if not shared:
328 # Keep this network visible from current project
329 project_id = (kwargs.get('project_id') or
330 kwargs.get('tenant_id') or
331 cls.client.tenant_id)
332 kwargs.update(project_id=project_id, tenant_id=project_id)
333 else:
334 # Use default client
335 client = cls.client
336
337 network = client.create_network(name=name, **kwargs)['network']
338 network['client'] = client
339 cls.networks.append(network)
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000340 return network
341
342 @classmethod
Federico Ressi61b564e2018-07-06 08:10:31 +0200343 def delete_network(cls, network, client=None):
344 client = client or network.get('client') or cls.client
345 client.delete_network(network['id'])
346
347 @classmethod
348 def create_shared_network(cls, network_name=None, **kwargs):
349 return cls.create_network(name=network_name, shared=True, **kwargs)
Miguel Lavalle124378b2016-09-21 16:41:47 -0500350
351 @classmethod
352 def create_network_keystone_v3(cls, network_name=None, project_id=None,
353 tenant_id=None, client=None):
Federico Ressi61b564e2018-07-06 08:10:31 +0200354 params = {}
355 if project_id:
356 params['project_id'] = project_id
357 if tenant_id:
358 params['tenant_id'] = tenant_id
359 return cls.create_network(name=network_name, client=client, **params)
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000360
361 @classmethod
Sławek Kapłońskid98e27d2018-05-07 16:16:28 +0200362 def create_subnet(cls, network, gateway='', cidr=None, mask_bits=None,
Federico Ressi98f20ec2018-05-11 06:09:49 +0200363 ip_version=None, client=None, reserve_cidr=True,
364 **kwargs):
Federico Ressi0ddc93b2018-04-09 12:01:48 +0200365 """Wrapper utility that returns a test subnet.
366
367 Convenient wrapper for client.create_subnet method. It reserves and
368 allocates CIDRs to avoid creating overlapping subnets.
369
370 :param network: network where to create the subnet
371 network['id'] must contain the ID of the network
372
373 :param gateway: gateway IP address
374 It can be a str or a netaddr.IPAddress
375 If gateway is not given, then it will use default address for
376 given subnet CIDR, like "192.168.0.1" for "192.168.0.0/24" CIDR
Sławek Kapłońskid98e27d2018-05-07 16:16:28 +0200377 if gateway is given as None then no gateway will be assigned
Federico Ressi0ddc93b2018-04-09 12:01:48 +0200378
379 :param cidr: CIDR of the subnet to create
380 It can be either None, a str or a netaddr.IPNetwork instance
381
382 :param mask_bits: CIDR prefix length
383 It can be either None or a numeric value.
384 If cidr parameter is given then mask_bits is used to determinate a
385 sequence of valid CIDR to use as generated.
386 Please see netaddr.IPNetwork.subnet method documentation[1]
387
388 :param ip_version: ip version of generated subnet CIDRs
389 It can be None, IP_VERSION_4 or IP_VERSION_6
390 It has to match given either given CIDR and gateway
391
392 :param ip_version: numeric value (either IP_VERSION_4 or IP_VERSION_6)
393 this value must match CIDR and gateway IP versions if any of them is
394 given
395
396 :param client: client to be used to connect to network service
397
Federico Ressi98f20ec2018-05-11 06:09:49 +0200398 :param reserve_cidr: if True then it reserves assigned CIDR to avoid
399 using the same CIDR for further subnets in the scope of the same
400 test case class
401
Federico Ressi0ddc93b2018-04-09 12:01:48 +0200402 :param **kwargs: optional parameters to be forwarded to wrapped method
403
404 [1] http://netaddr.readthedocs.io/en/latest/tutorial_01.html#supernets-and-subnets # noqa
405 """
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000406
407 # allow tests to use admin client
408 if not client:
409 client = cls.client
410
Federico Ressi0ddc93b2018-04-09 12:01:48 +0200411 if gateway:
412 gateway_ip = netaddr.IPAddress(gateway)
413 if ip_version:
414 if ip_version != gateway_ip.version:
415 raise ValueError(
416 "Gateway IP version doesn't match IP version")
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000417 else:
Federico Ressi0ddc93b2018-04-09 12:01:48 +0200418 ip_version = gateway_ip.version
Sławek Kapłońskid98e27d2018-05-07 16:16:28 +0200419 else:
420 ip_version = ip_version or cls._ip_version
Federico Ressi0ddc93b2018-04-09 12:01:48 +0200421
422 for subnet_cidr in cls.get_subnet_cidrs(
423 ip_version=ip_version, cidr=cidr, mask_bits=mask_bits):
Federico Ressi98f20ec2018-05-11 06:09:49 +0200424 if gateway is not None:
425 kwargs['gateway_ip'] = str(gateway or (subnet_cidr.ip + 1))
426 try:
427 body = client.create_subnet(
428 network_id=network['id'],
429 cidr=str(subnet_cidr),
430 ip_version=subnet_cidr.version,
431 **kwargs)
432 break
433 except lib_exc.BadRequest as e:
434 if 'overlaps with another subnet' not in str(e):
435 raise
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000436 else:
437 message = 'Available CIDR for subnet creation could not be found'
438 raise ValueError(message)
439 subnet = body['subnet']
Kevin Bentonba3651c2017-09-01 17:13:01 -0700440 if client is cls.client:
441 cls.subnets.append(subnet)
442 else:
443 cls.admin_subnets.append(subnet)
Federico Ressi98f20ec2018-05-11 06:09:49 +0200444 if reserve_cidr:
445 cls.reserve_subnet_cidr(subnet_cidr)
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000446 return subnet
447
448 @classmethod
Federico Ressi0ddc93b2018-04-09 12:01:48 +0200449 def reserve_subnet_cidr(cls, addr, **ipnetwork_kwargs):
450 """Reserve given subnet CIDR making sure it is not used by create_subnet
451
452 :param addr: the CIDR address to be reserved
453 It can be a str or netaddr.IPNetwork instance
454
455 :param **ipnetwork_kwargs: optional netaddr.IPNetwork constructor
456 parameters
457 """
458
459 if not cls.try_reserve_subnet_cidr(addr, **ipnetwork_kwargs):
460 raise ValueError('Subnet CIDR already reserved: %r'.format(
461 addr))
462
463 @classmethod
464 def try_reserve_subnet_cidr(cls, addr, **ipnetwork_kwargs):
465 """Reserve given subnet CIDR if it hasn't been reserved before
466
467 :param addr: the CIDR address to be reserved
468 It can be a str or netaddr.IPNetwork instance
469
470 :param **ipnetwork_kwargs: optional netaddr.IPNetwork constructor
471 parameters
472
473 :return: True if it wasn't reserved before, False elsewhere.
474 """
475
476 subnet_cidr = netaddr.IPNetwork(addr, **ipnetwork_kwargs)
477 if subnet_cidr in cls.reserved_subnet_cidrs:
478 return False
479 else:
480 cls.reserved_subnet_cidrs.add(subnet_cidr)
481 return True
482
483 @classmethod
484 def get_subnet_cidrs(
485 cls, cidr=None, mask_bits=None, ip_version=None):
486 """Iterate over a sequence of unused subnet CIDR for IP version
487
488 :param cidr: CIDR of the subnet to create
489 It can be either None, a str or a netaddr.IPNetwork instance
490
491 :param mask_bits: CIDR prefix length
492 It can be either None or a numeric value.
493 If cidr parameter is given then mask_bits is used to determinate a
494 sequence of valid CIDR to use as generated.
495 Please see netaddr.IPNetwork.subnet method documentation[1]
496
497 :param ip_version: ip version of generated subnet CIDRs
498 It can be None, IP_VERSION_4 or IP_VERSION_6
499 It has to match given CIDR if given
500
501 :return: iterator over reserved CIDRs of type netaddr.IPNetwork
502
503 [1] http://netaddr.readthedocs.io/en/latest/tutorial_01.html#supernets-and-subnets # noqa
504 """
505
506 if cidr:
507 # Generate subnet CIDRs starting from given CIDR
508 # checking it is of requested IP version
509 cidr = netaddr.IPNetwork(cidr, version=ip_version)
510 else:
511 # Generate subnet CIDRs starting from configured values
512 ip_version = ip_version or cls._ip_version
513 if ip_version == const.IP_VERSION_4:
514 mask_bits = mask_bits or config.safe_get_config_value(
515 'network', 'project_network_mask_bits')
516 cidr = netaddr.IPNetwork(config.safe_get_config_value(
517 'network', 'project_network_cidr'))
518 elif ip_version == const.IP_VERSION_6:
519 mask_bits = config.safe_get_config_value(
520 'network', 'project_network_v6_mask_bits')
521 cidr = netaddr.IPNetwork(config.safe_get_config_value(
522 'network', 'project_network_v6_cidr'))
523 else:
524 raise ValueError('Invalid IP version: {!r}'.format(ip_version))
525
526 if mask_bits:
527 subnet_cidrs = cidr.subnet(mask_bits)
528 else:
529 subnet_cidrs = iter([cidr])
530
531 for subnet_cidr in subnet_cidrs:
532 if subnet_cidr not in cls.reserved_subnet_cidrs:
533 yield subnet_cidr
534
535 @classmethod
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000536 def create_port(cls, network, **kwargs):
537 """Wrapper utility that returns a test port."""
Edan Davidd75e48e2018-01-03 02:49:52 -0500538 if CONF.network.port_vnic_type and 'binding:vnic_type' not in kwargs:
539 kwargs['binding:vnic_type'] = CONF.network.port_vnic_type
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000540 body = cls.client.create_port(network_id=network['id'],
541 **kwargs)
542 port = body['port']
543 cls.ports.append(port)
544 return port
545
546 @classmethod
547 def update_port(cls, port, **kwargs):
548 """Wrapper utility that updates a test port."""
549 body = cls.client.update_port(port['id'],
550 **kwargs)
551 return body['port']
552
553 @classmethod
Genadi Chereshnyac0411e92016-07-11 16:59:42 +0300554 def _create_router_with_client(
555 cls, client, router_name=None, admin_state_up=False,
556 external_network_id=None, enable_snat=None, **kwargs
557 ):
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000558 ext_gw_info = {}
559 if external_network_id:
560 ext_gw_info['network_id'] = external_network_id
YAMAMOTO Takashi9bd4f972017-06-20 12:49:30 +0900561 if enable_snat is not None:
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000562 ext_gw_info['enable_snat'] = enable_snat
Genadi Chereshnyac0411e92016-07-11 16:59:42 +0300563 body = client.create_router(
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000564 router_name, external_gateway_info=ext_gw_info,
565 admin_state_up=admin_state_up, **kwargs)
566 router = body['router']
567 cls.routers.append(router)
568 return router
569
570 @classmethod
Genadi Chereshnyac0411e92016-07-11 16:59:42 +0300571 def create_router(cls, *args, **kwargs):
572 return cls._create_router_with_client(cls.client, *args, **kwargs)
573
574 @classmethod
575 def create_admin_router(cls, *args, **kwargs):
rajat294495c042017-06-28 15:37:16 +0530576 return cls._create_router_with_client(cls.os_admin.network_client,
Genadi Chereshnyac0411e92016-07-11 16:59:42 +0300577 *args, **kwargs)
578
579 @classmethod
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000580 def create_floatingip(cls, external_network_id):
581 """Wrapper utility that returns a test floating IP."""
582 body = cls.client.create_floatingip(
583 floating_network_id=external_network_id)
584 fip = body['floatingip']
585 cls.floating_ips.append(fip)
586 return fip
587
588 @classmethod
589 def create_router_interface(cls, router_id, subnet_id):
590 """Wrapper utility that returns a router interface."""
591 interface = cls.client.add_router_interface_with_subnet_id(
592 router_id, subnet_id)
593 return interface
594
595 @classmethod
Sławek Kapłońskiff294062016-12-04 15:00:54 +0000596 def get_supported_qos_rule_types(cls):
597 body = cls.client.list_qos_rule_types()
598 return [rule_type['type'] for rule_type in body['rule_types']]
599
600 @classmethod
Ihar Hrachyshkab7940d92016-06-10 13:44:22 +0200601 def create_qos_policy(cls, name, description=None, shared=False,
Hirofumi Ichihara39a6ee12017-08-23 13:55:12 +0900602 tenant_id=None, is_default=False):
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000603 """Wrapper utility that returns a test QoS policy."""
604 body = cls.admin_client.create_qos_policy(
Hirofumi Ichihara39a6ee12017-08-23 13:55:12 +0900605 name, description, shared, tenant_id, is_default)
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000606 qos_policy = body['policy']
607 cls.qos_policies.append(qos_policy)
608 return qos_policy
609
610 @classmethod
Sławek Kapłoński153f3452017-03-24 22:04:53 +0000611 def create_qos_bandwidth_limit_rule(cls, policy_id, max_kbps,
612 max_burst_kbps,
Chandan Kumarc125fd12017-11-15 19:41:01 +0530613 direction=const.EGRESS_DIRECTION):
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000614 """Wrapper utility that returns a test QoS bandwidth limit rule."""
615 body = cls.admin_client.create_bandwidth_limit_rule(
Sławek Kapłoński153f3452017-03-24 22:04:53 +0000616 policy_id, max_kbps, max_burst_kbps, direction)
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000617 qos_rule = body['bandwidth_limit_rule']
618 cls.qos_rules.append(qos_rule)
619 return qos_rule
620
621 @classmethod
Jakub Libosvar83704832017-12-06 16:02:28 +0000622 def delete_router(cls, router, client=None):
623 client = client or cls.client
624 body = client.list_router_interfaces(router['id'])
Chandan Kumarc125fd12017-11-15 19:41:01 +0530625 interfaces = [port for port in body['ports']
626 if port['device_owner'] in const.ROUTER_INTERFACE_OWNERS]
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000627 for i in interfaces:
628 try:
Jakub Libosvar83704832017-12-06 16:02:28 +0000629 client.remove_router_interface_with_subnet_id(
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000630 router['id'], i['fixed_ips'][0]['subnet_id'])
631 except lib_exc.NotFound:
632 pass
Jakub Libosvar83704832017-12-06 16:02:28 +0000633 client.delete_router(router['id'])
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000634
635 @classmethod
636 def create_address_scope(cls, name, is_admin=False, **kwargs):
637 if is_admin:
638 body = cls.admin_client.create_address_scope(name=name, **kwargs)
639 cls.admin_address_scopes.append(body['address_scope'])
640 else:
641 body = cls.client.create_address_scope(name=name, **kwargs)
642 cls.address_scopes.append(body['address_scope'])
643 return body['address_scope']
644
645 @classmethod
646 def create_subnetpool(cls, name, is_admin=False, **kwargs):
647 if is_admin:
648 body = cls.admin_client.create_subnetpool(name, **kwargs)
649 cls.admin_subnetpools.append(body['subnetpool'])
650 else:
651 body = cls.client.create_subnetpool(name, **kwargs)
652 cls.subnetpools.append(body['subnetpool'])
653 return body['subnetpool']
654
Chandan Kumarc125fd12017-11-15 19:41:01 +0530655 @classmethod
656 def create_project(cls, name=None, description=None):
657 test_project = name or data_utils.rand_name('test_project_')
658 test_description = description or data_utils.rand_name('desc_')
659 project = cls.identity_admin_client.create_project(
660 name=test_project,
661 description=test_description)['project']
662 cls.projects.append(project)
663 return project
664
665 @classmethod
666 def create_security_group(cls, name, **kwargs):
667 body = cls.client.create_security_group(name=name, **kwargs)
668 cls.security_groups.append(body['security_group'])
669 return body['security_group']
670
Federico Ressiab286e42018-06-19 09:52:10 +0200671 @classmethod
672 def create_keypair(cls, client=None, name=None, **kwargs):
673 client = client or cls.os_primary.keypairs_client
674 name = name or data_utils.rand_name('keypair-test')
675 keypair = client.create_keypair(name=name, **kwargs)['keypair']
676
677 # save client for later cleanup
678 keypair['client'] = client
679 cls.keypairs.append(keypair)
680 return keypair
681
682 @classmethod
683 def delete_keypair(cls, keypair, client=None):
684 client = (client or keypair.get('client') or
685 cls.os_primary.keypairs_client)
686 client.delete_keypair(keypair_name=keypair['name'])
687
Federico Ressi82e83e32018-07-03 14:19:55 +0200688 @classmethod
689 def create_trunk(cls, port=None, subports=None, client=None, **kwargs):
690 """Create network trunk
691
692 :param port: dictionary containing parent port ID (port['id'])
693 :param client: client to be used for connecting to networking service
694 :param **kwargs: extra parameters to be forwarded to network service
695
696 :returns: dictionary containing created trunk details
697 """
698 client = client or cls.client
699
700 if port:
701 kwargs['port_id'] = port['id']
702
703 trunk = client.create_trunk(subports=subports, **kwargs)['trunk']
704 # Save client reference for later deletion
705 trunk['client'] = client
706 cls.trunks.append(trunk)
707 return trunk
708
709 @classmethod
710 def delete_trunk(cls, trunk, client=None):
711 """Delete network trunk
712
713 :param trunk: dictionary containing trunk ID (trunk['id'])
714
715 :param client: client to be used for connecting to networking service
716 """
717 client = client or trunk.get('client') or cls.client
718 trunk.update(client.show_trunk(trunk['id'])['trunk'])
719
720 if not trunk['admin_state_up']:
721 # Cannot touch trunk before admin_state_up is True
722 client.update_trunk(trunk['id'], admin_state_up=True)
723 if trunk['sub_ports']:
724 # Removes trunk ports before deleting it
725 cls._try_delete_resource(client.remove_subports, trunk['id'],
726 trunk['sub_ports'])
727
728 # we have to detach the interface from the server before
729 # the trunk can be deleted.
730 parent_port = {'id': trunk['port_id']}
731
732 def is_parent_port_detached():
733 parent_port.update(client.show_port(parent_port['id'])['port'])
734 return not parent_port['device_id']
735
736 if not is_parent_port_detached():
737 # this could probably happen when trunk is deleted and parent port
738 # has been assigned to a VM that is still running. Here we are
739 # assuming that device_id points to such VM.
740 cls.os_primary.compute.InterfacesClient().delete_interface(
741 parent_port['device_id'], parent_port['id'])
742 utils.wait_until_true(is_parent_port_detached)
743
744 client.delete_trunk(trunk['id'])
745
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000746
747class BaseAdminNetworkTest(BaseNetworkTest):
748
749 credentials = ['primary', 'admin']
750
751 @classmethod
752 def setup_clients(cls):
753 super(BaseAdminNetworkTest, cls).setup_clients()
fumihiko kakumaa216fc12017-07-14 10:43:29 +0900754 cls.admin_client = cls.os_admin.network_client
Jakub Libosvarf5758012017-08-15 13:45:30 +0000755 cls.identity_admin_client = cls.os_admin.projects_client
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000756
757 @classmethod
758 def create_metering_label(cls, name, description):
759 """Wrapper utility that returns a test metering label."""
760 body = cls.admin_client.create_metering_label(
761 description=description,
762 name=data_utils.rand_name("metering-label"))
763 metering_label = body['metering_label']
764 cls.metering_labels.append(metering_label)
765 return metering_label
766
767 @classmethod
768 def create_metering_label_rule(cls, remote_ip_prefix, direction,
769 metering_label_id):
770 """Wrapper utility that returns a test metering label rule."""
771 body = cls.admin_client.create_metering_label_rule(
772 remote_ip_prefix=remote_ip_prefix, direction=direction,
773 metering_label_id=metering_label_id)
774 metering_label_rule = body['metering_label_rule']
775 cls.metering_label_rules.append(metering_label_rule)
776 return metering_label_rule
777
778 @classmethod
779 def create_flavor(cls, name, description, service_type):
780 """Wrapper utility that returns a test flavor."""
781 body = cls.admin_client.create_flavor(
782 description=description, service_type=service_type,
783 name=name)
784 flavor = body['flavor']
785 cls.flavors.append(flavor)
786 return flavor
787
788 @classmethod
789 def create_service_profile(cls, description, metainfo, driver):
790 """Wrapper utility that returns a test service profile."""
791 body = cls.admin_client.create_service_profile(
792 driver=driver, metainfo=metainfo, description=description)
793 service_profile = body['service_profile']
794 cls.service_profiles.append(service_profile)
795 return service_profile
796
797 @classmethod
Nguyen Phuong An67993fc2017-11-24 11:30:25 +0700798 def create_log(cls, name, description=None,
799 resource_type='security_group', resource_id=None,
800 target_id=None, event='ALL', enabled=True):
801 """Wrapper utility that returns a test log object."""
802 log_args = {'name': name,
803 'description': description,
804 'resource_type': resource_type,
805 'resource_id': resource_id,
806 'target_id': target_id,
807 'event': event,
808 'enabled': enabled}
809 body = cls.admin_client.create_log(**log_args)
810 log_object = body['log']
811 cls.log_objects.append(log_object)
812 return log_object
813
814 @classmethod
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000815 def get_unused_ip(cls, net_id, ip_version=None):
Gary Kotton011345f2016-06-15 08:04:31 -0700816 """Get an unused ip address in a allocation pool of net"""
Daniel Mellado3c0aeab2016-01-29 11:30:25 +0000817 body = cls.admin_client.list_ports(network_id=net_id)
818 ports = body['ports']
819 used_ips = []
820 for port in ports:
821 used_ips.extend(
822 [fixed_ip['ip_address'] for fixed_ip in port['fixed_ips']])
823 body = cls.admin_client.list_subnets(network_id=net_id)
824 subnets = body['subnets']
825
826 for subnet in subnets:
827 if ip_version and subnet['ip_version'] != ip_version:
828 continue
829 cidr = subnet['cidr']
830 allocation_pools = subnet['allocation_pools']
831 iterators = []
832 if allocation_pools:
833 for allocation_pool in allocation_pools:
834 iterators.append(netaddr.iter_iprange(
835 allocation_pool['start'], allocation_pool['end']))
836 else:
837 net = netaddr.IPNetwork(cidr)
838
839 def _iterip():
840 for ip in net:
841 if ip not in (net.network, net.broadcast):
842 yield ip
843 iterators.append(iter(_iterip()))
844
845 for iterator in iterators:
846 for ip in iterator:
847 if str(ip) not in used_ips:
848 return str(ip)
849
850 message = (
851 "net(%s) has no usable IP address in allocation pools" % net_id)
852 raise exceptions.InvalidConfiguration(message)
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200853
854
Sławek Kapłońskiff294062016-12-04 15:00:54 +0000855def require_qos_rule_type(rule_type):
856 def decorator(f):
857 @functools.wraps(f)
858 def wrapper(self, *func_args, **func_kwargs):
859 if rule_type not in self.get_supported_qos_rule_types():
860 raise self.skipException(
861 "%s rule type is required." % rule_type)
862 return f(self, *func_args, **func_kwargs)
863 return wrapper
864 return decorator
865
866
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200867def _require_sorting(f):
868 @functools.wraps(f)
869 def inner(self, *args, **kwargs):
Chandan Kumarc125fd12017-11-15 19:41:01 +0530870 if not tutils.is_extension_enabled("sorting", "network"):
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200871 self.skipTest('Sorting feature is required')
872 return f(self, *args, **kwargs)
873 return inner
874
875
876def _require_pagination(f):
877 @functools.wraps(f)
878 def inner(self, *args, **kwargs):
Chandan Kumarc125fd12017-11-15 19:41:01 +0530879 if not tutils.is_extension_enabled("pagination", "network"):
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200880 self.skipTest('Pagination feature is required')
881 return f(self, *args, **kwargs)
882 return inner
883
884
885class BaseSearchCriteriaTest(BaseNetworkTest):
886
887 # This should be defined by subclasses to reflect resource name to test
888 resource = None
889
Armando Migliaccio57581c62016-07-01 10:13:19 -0700890 field = 'name'
891
Ihar Hrachyshkaa8fe5a12016-05-24 14:50:58 +0200892 # NOTE(ihrachys): some names, like those starting with an underscore (_)
893 # are sorted differently depending on whether the plugin implements native
894 # sorting support, or not. So we avoid any such cases here, sticking to
895 # alphanumeric. Also test a case when there are multiple resources with the
896 # same name
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200897 resource_names = ('test1', 'abc1', 'test10', '123test') + ('test1',)
898
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200899 force_tenant_isolation = True
900
Ihar Hrachyshkaa8fe5a12016-05-24 14:50:58 +0200901 list_kwargs = {}
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200902
Ihar Hrachyshkab7940d92016-06-10 13:44:22 +0200903 list_as_admin = False
904
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +0200905 def assertSameOrder(self, original, actual):
906 # gracefully handle iterators passed
907 original = list(original)
908 actual = list(actual)
909 self.assertEqual(len(original), len(actual))
910 for expected, res in zip(original, actual):
Armando Migliaccio57581c62016-07-01 10:13:19 -0700911 self.assertEqual(expected[self.field], res[self.field])
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +0200912
913 @utils.classproperty
914 def plural_name(self):
915 return '%ss' % self.resource
916
Ihar Hrachyshkab7940d92016-06-10 13:44:22 +0200917 @property
918 def list_client(self):
919 return self.admin_client if self.list_as_admin else self.client
920
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200921 def list_method(self, *args, **kwargs):
Ihar Hrachyshkab7940d92016-06-10 13:44:22 +0200922 method = getattr(self.list_client, 'list_%s' % self.plural_name)
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200923 kwargs.update(self.list_kwargs)
924 return method(*args, **kwargs)
925
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +0200926 def get_bare_url(self, url):
927 base_url = self.client.base_url
928 self.assertTrue(url.startswith(base_url))
929 return url[len(base_url):]
930
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200931 @classmethod
932 def _extract_resources(cls, body):
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +0200933 return body[cls.plural_name]
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200934
935 def _test_list_sorts(self, direction):
936 sort_args = {
937 'sort_dir': direction,
Armando Migliaccio57581c62016-07-01 10:13:19 -0700938 'sort_key': self.field
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200939 }
940 body = self.list_method(**sort_args)
941 resources = self._extract_resources(body)
942 self.assertNotEmpty(
943 resources, "%s list returned is empty" % self.resource)
Armando Migliaccio57581c62016-07-01 10:13:19 -0700944 retrieved_names = [res[self.field] for res in resources]
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200945 expected = sorted(retrieved_names)
946 if direction == constants.SORT_DIRECTION_DESC:
947 expected = list(reversed(expected))
948 self.assertEqual(expected, retrieved_names)
949
950 @_require_sorting
951 def _test_list_sorts_asc(self):
952 self._test_list_sorts(constants.SORT_DIRECTION_ASC)
953
954 @_require_sorting
955 def _test_list_sorts_desc(self):
956 self._test_list_sorts(constants.SORT_DIRECTION_DESC)
957
958 @_require_pagination
959 def _test_list_pagination(self):
960 for limit in range(1, len(self.resource_names) + 1):
961 pagination_args = {
962 'limit': limit,
963 }
964 body = self.list_method(**pagination_args)
965 resources = self._extract_resources(body)
966 self.assertEqual(limit, len(resources))
967
968 @_require_pagination
969 def _test_list_no_pagination_limit_0(self):
970 pagination_args = {
971 'limit': 0,
972 }
973 body = self.list_method(**pagination_args)
974 resources = self._extract_resources(body)
Béla Vancsicsf1806182016-08-23 07:36:18 +0200975 self.assertGreaterEqual(len(resources), len(self.resource_names))
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200976
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +0200977 def _test_list_pagination_iteratively(self, lister):
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200978 # first, collect all resources for later comparison
979 sort_args = {
980 'sort_dir': constants.SORT_DIRECTION_ASC,
Armando Migliaccio57581c62016-07-01 10:13:19 -0700981 'sort_key': self.field
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200982 }
983 body = self.list_method(**sort_args)
984 expected_resources = self._extract_resources(body)
985 self.assertNotEmpty(expected_resources)
986
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +0200987 resources = lister(
988 len(expected_resources), sort_args
989 )
990
991 # finally, compare that the list retrieved in one go is identical to
992 # the one containing pagination results
993 self.assertSameOrder(expected_resources, resources)
994
995 def _list_all_with_marker(self, niterations, sort_args):
Ihar Hrachyshka59382252016-04-05 15:54:33 +0200996 # paginate resources one by one, using last fetched resource as a
997 # marker
998 resources = []
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +0200999 for i in range(niterations):
Ihar Hrachyshka59382252016-04-05 15:54:33 +02001000 pagination_args = sort_args.copy()
1001 pagination_args['limit'] = 1
1002 if resources:
1003 pagination_args['marker'] = resources[-1]['id']
1004 body = self.list_method(**pagination_args)
1005 resources_ = self._extract_resources(body)
1006 self.assertEqual(1, len(resources_))
1007 resources.extend(resources_)
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +02001008 return resources
Ihar Hrachyshka59382252016-04-05 15:54:33 +02001009
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +02001010 @_require_pagination
1011 @_require_sorting
1012 def _test_list_pagination_with_marker(self):
1013 self._test_list_pagination_iteratively(self._list_all_with_marker)
1014
1015 def _list_all_with_hrefs(self, niterations, sort_args):
1016 # paginate resources one by one, using next href links
1017 resources = []
1018 prev_links = {}
1019
1020 for i in range(niterations):
1021 if prev_links:
1022 uri = self.get_bare_url(prev_links['next'])
1023 else:
Ihar Hrachyshka7f79fe62016-06-07 21:23:44 +02001024 sort_args.update(self.list_kwargs)
Ihar Hrachyshkab7940d92016-06-10 13:44:22 +02001025 uri = self.list_client.build_uri(
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +02001026 self.plural_name, limit=1, **sort_args)
Ihar Hrachyshkab7940d92016-06-10 13:44:22 +02001027 prev_links, body = self.list_client.get_uri_with_links(
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +02001028 self.plural_name, uri
1029 )
1030 resources_ = self._extract_resources(body)
1031 self.assertEqual(1, len(resources_))
1032 resources.extend(resources_)
1033
1034 # The last element is empty and does not contain 'next' link
1035 uri = self.get_bare_url(prev_links['next'])
1036 prev_links, body = self.client.get_uri_with_links(
1037 self.plural_name, uri
1038 )
1039 self.assertNotIn('next', prev_links)
1040
1041 # Now walk backwards and compare results
1042 resources2 = []
1043 for i in range(niterations):
1044 uri = self.get_bare_url(prev_links['previous'])
Ihar Hrachyshkab7940d92016-06-10 13:44:22 +02001045 prev_links, body = self.list_client.get_uri_with_links(
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +02001046 self.plural_name, uri
1047 )
1048 resources_ = self._extract_resources(body)
1049 self.assertEqual(1, len(resources_))
1050 resources2.extend(resources_)
1051
1052 self.assertSameOrder(resources, reversed(resources2))
1053
1054 return resources
1055
1056 @_require_pagination
1057 @_require_sorting
1058 def _test_list_pagination_with_href_links(self):
1059 self._test_list_pagination_iteratively(self._list_all_with_hrefs)
1060
1061 @_require_pagination
1062 @_require_sorting
1063 def _test_list_pagination_page_reverse_with_href_links(
1064 self, direction=constants.SORT_DIRECTION_ASC):
1065 pagination_args = {
1066 'sort_dir': direction,
Armando Migliaccio57581c62016-07-01 10:13:19 -07001067 'sort_key': self.field,
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +02001068 }
1069 body = self.list_method(**pagination_args)
1070 expected_resources = self._extract_resources(body)
1071
1072 page_size = 2
1073 pagination_args['limit'] = page_size
1074
1075 prev_links = {}
1076 resources = []
1077 num_resources = len(expected_resources)
1078 niterations = int(math.ceil(float(num_resources) / page_size))
1079 for i in range(niterations):
1080 if prev_links:
1081 uri = self.get_bare_url(prev_links['previous'])
1082 else:
Ihar Hrachyshka7f79fe62016-06-07 21:23:44 +02001083 pagination_args.update(self.list_kwargs)
Ihar Hrachyshkab7940d92016-06-10 13:44:22 +02001084 uri = self.list_client.build_uri(
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +02001085 self.plural_name, page_reverse=True, **pagination_args)
Ihar Hrachyshkab7940d92016-06-10 13:44:22 +02001086 prev_links, body = self.list_client.get_uri_with_links(
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +02001087 self.plural_name, uri
1088 )
1089 resources_ = self._extract_resources(body)
Béla Vancsicsf1806182016-08-23 07:36:18 +02001090 self.assertGreaterEqual(page_size, len(resources_))
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +02001091 resources.extend(reversed(resources_))
1092
1093 self.assertSameOrder(expected_resources, reversed(resources))
1094
1095 @_require_pagination
1096 @_require_sorting
1097 def _test_list_pagination_page_reverse_asc(self):
1098 self._test_list_pagination_page_reverse(
1099 direction=constants.SORT_DIRECTION_ASC)
1100
1101 @_require_pagination
1102 @_require_sorting
1103 def _test_list_pagination_page_reverse_desc(self):
1104 self._test_list_pagination_page_reverse(
1105 direction=constants.SORT_DIRECTION_DESC)
1106
1107 def _test_list_pagination_page_reverse(self, direction):
1108 pagination_args = {
1109 'sort_dir': direction,
Armando Migliaccio57581c62016-07-01 10:13:19 -07001110 'sort_key': self.field,
Ihar Hrachyshkaaeb03a02016-05-18 20:03:18 +02001111 'limit': 3,
1112 }
1113 body = self.list_method(**pagination_args)
1114 expected_resources = self._extract_resources(body)
1115
1116 pagination_args['limit'] -= 1
1117 pagination_args['marker'] = expected_resources[-1]['id']
1118 pagination_args['page_reverse'] = True
1119 body = self.list_method(**pagination_args)
1120
1121 self.assertSameOrder(
1122 # the last entry is not included in 2nd result when used as a
1123 # marker
1124 expected_resources[:-1],
1125 self._extract_resources(body))
Victor Morales1be97b42016-09-05 08:50:06 -05001126
1127 def _test_list_validation_filters(self):
1128 validation_args = {
1129 'unknown_filter': 'value',
1130 }
1131 body = self.list_method(**validation_args)
1132 resources = self._extract_resources(body)
1133 for resource in resources:
1134 self.assertIn(resource['name'], self.resource_names)