blob: 0e8a90920f7d9ee08d7cf15431168c8c31d624d3 [file] [log] [blame]
Jude Cross986e3f52017-07-24 14:57:20 -07001# Copyright 2018 Rackspace US Inc. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
15import ipaddress
16import pkg_resources
17import random
Adam Harwellcd72b562018-05-07 11:37:22 -070018import requests
Jude Cross986e3f52017-07-24 14:57:20 -070019import shlex
20import six
21import string
22import subprocess
23import tempfile
Adam Harwellcd72b562018-05-07 11:37:22 -070024import time
Jude Cross986e3f52017-07-24 14:57:20 -070025
26from oslo_log import log as logging
27from oslo_utils import uuidutils
28from tempest import config
29from tempest.lib.common.utils import data_utils
30from tempest.lib.common.utils.linux import remote_client
Jude Cross986e3f52017-07-24 14:57:20 -070031from tempest.lib import exceptions
32from tempest import test
Michael Johnson04dc5cb2019-01-20 11:03:50 -080033import tenacity
Jude Cross986e3f52017-07-24 14:57:20 -070034
35from octavia_tempest_plugin import clients
36from octavia_tempest_plugin.common import constants as const
37from octavia_tempest_plugin.tests import validators
38from octavia_tempest_plugin.tests import waiters
39
40CONF = config.CONF
41LOG = logging.getLogger(__name__)
42
Michael Johnson04dc5cb2019-01-20 11:03:50 -080043RETRY_ATTEMPTS = 15
44RETRY_INITIAL_DELAY = 1
45RETRY_BACKOFF = 1
46RETRY_MAX = 5
47
Jude Cross986e3f52017-07-24 14:57:20 -070048
49class LoadBalancerBaseTest(test.BaseTestCase):
50 """Base class for load balancer tests."""
51
52 # Setup cls.os_roles_lb_member. cls.os_primary, cls.os_roles_lb_member,
53 # and cls.os_roles_lb_admin credentials.
54 credentials = ['admin', 'primary',
55 ['lb_member', CONF.load_balancer.member_role],
56 ['lb_member2', CONF.load_balancer.member_role],
57 ['lb_admin', CONF.load_balancer.admin_role]]
58
59 client_manager = clients.ManagerV2
Adam Harwelle029af22018-05-24 17:13:28 -070060 webserver1_response = 1
61 webserver2_response = 5
Michael Johnsondfd818a2018-08-21 20:54:54 -070062 used_ips = []
Jude Cross986e3f52017-07-24 14:57:20 -070063
64 @classmethod
65 def skip_checks(cls):
66 """Check if we should skip all of the children tests."""
67 super(LoadBalancerBaseTest, cls).skip_checks()
68
69 service_list = {
70 'load_balancer': CONF.service_available.load_balancer,
71 }
72
73 live_service_list = {
74 'compute': CONF.service_available.nova,
75 'image': CONF.service_available.glance,
76 'neutron': CONF.service_available.neutron
77 }
78
79 if not CONF.load_balancer.test_with_noop:
80 service_list.update(live_service_list)
81
82 for service, available in service_list.items():
83 if not available:
zhangzs2a6cf672018-11-10 16:13:11 +080084 skip_msg = ("{0} skipped as {1} service is not "
Jude Cross986e3f52017-07-24 14:57:20 -070085 "available.".format(cls.__name__, service))
86 raise cls.skipException(skip_msg)
87
88 # We must be able to reach our VIP and instances
89 if not (CONF.network.project_networks_reachable
90 or CONF.network.public_network_id):
91 msg = ('Either project_networks_reachable must be "true", or '
92 'public_network_id must be defined.')
93 raise cls.skipException(msg)
94
95 @classmethod
96 def setup_credentials(cls):
97 """Setup test credentials and network resources."""
98 # Do not auto create network resources
99 cls.set_network_resources()
100 super(LoadBalancerBaseTest, cls).setup_credentials()
101
102 @classmethod
103 def setup_clients(cls):
104 """Setup client aliases."""
105 super(LoadBalancerBaseTest, cls).setup_clients()
106 cls.lb_mem_float_ip_client = cls.os_roles_lb_member.floating_ips_client
107 cls.lb_mem_keypairs_client = cls.os_roles_lb_member.keypairs_client
108 cls.lb_mem_net_client = cls.os_roles_lb_member.networks_client
109 cls.lb_mem_ports_client = cls.os_roles_lb_member.ports_client
110 cls.lb_mem_routers_client = cls.os_roles_lb_member.routers_client
111 cls.lb_mem_SG_client = cls.os_roles_lb_member.security_groups_client
112 cls.lb_mem_SGr_client = (
113 cls.os_roles_lb_member.security_group_rules_client)
114 cls.lb_mem_servers_client = cls.os_roles_lb_member.servers_client
115 cls.lb_mem_subnet_client = cls.os_roles_lb_member.subnets_client
116 cls.mem_lb_client = cls.os_roles_lb_member.loadbalancer_client
Jude Crossfbbd2b42017-08-09 15:21:04 -0700117 cls.mem_listener_client = cls.os_roles_lb_member.listener_client
Adam Harwell8ffce3e2018-05-01 21:18:44 -0700118 cls.mem_pool_client = cls.os_roles_lb_member.pool_client
Adam Harwellde3e0542018-05-03 18:21:06 -0700119 cls.mem_member_client = cls.os_roles_lb_member.member_client
Adam Harwell60ed9d92018-05-10 13:23:13 -0700120 cls.mem_healthmonitor_client = (
121 cls.os_roles_lb_member.healthmonitor_client)
Adam Harwell446f8be2018-05-24 16:51:03 -0700122 cls.mem_l7policy_client = cls.os_roles_lb_member.l7policy_client
Adam Harwelle029af22018-05-24 17:13:28 -0700123 cls.mem_l7rule_client = cls.os_roles_lb_member.l7rule_client
Michael Johnson2b10e0a2019-01-25 15:42:13 -0800124 cls.lb_admin_amphora_client = cls.os_roles_lb_admin.amphora_client
Michael Johnsonaff2e862019-01-11 16:38:00 -0800125 cls.lb_admin_flavor_profile_client = (
126 cls.os_roles_lb_admin.flavor_profile_client)
Michael Johnsona2d03072019-01-14 17:18:21 -0800127 cls.lb_admin_flavor_client = cls.os_roles_lb_admin.flavor_client
128 cls.mem_flavor_client = cls.os_roles_lb_member.flavor_client
Michael Johnsonfc223fe2019-01-15 16:40:05 -0800129 cls.mem_provider_client = cls.os_roles_lb_member.provider_client
Carlos Goncalvesc2e12162019-02-14 23:57:44 +0100130 cls.os_admin_servers_client = cls.os_admin.servers_client
Michael Johnson77df0322019-01-15 18:27:58 -0800131 cls.lb_admin_capabilities_client = (
132 cls.os_roles_lb_admin.flavor_capabilities_client)
Jude Cross986e3f52017-07-24 14:57:20 -0700133
134 @classmethod
135 def resource_setup(cls):
136 """Setup resources needed by the tests."""
137 super(LoadBalancerBaseTest, cls).resource_setup()
138
139 conf_lb = CONF.load_balancer
140
Michael Johnsondfd818a2018-08-21 20:54:54 -0700141 cls.api_version = cls.mem_lb_client.get_max_api_version()
142
Jude Cross986e3f52017-07-24 14:57:20 -0700143 if conf_lb.test_subnet_override and not conf_lb.test_network_override:
144 raise exceptions.InvalidConfiguration(
145 "Configuration value test_network_override must be "
146 "specified if test_subnet_override is used.")
147
148 show_subnet = cls.lb_mem_subnet_client.show_subnet
149 if CONF.load_balancer.test_with_noop:
150 cls.lb_member_vip_net = {'id': uuidutils.generate_uuid()}
151 cls.lb_member_vip_subnet = {'id': uuidutils.generate_uuid()}
152 cls.lb_member_1_net = {'id': uuidutils.generate_uuid()}
153 cls.lb_member_1_subnet = {'id': uuidutils.generate_uuid()}
154 cls.lb_member_2_net = {'id': uuidutils.generate_uuid()}
155 cls.lb_member_2_subnet = {'id': uuidutils.generate_uuid()}
156 if CONF.load_balancer.test_with_ipv6:
Michael Johnson5a16ad32018-10-18 14:49:11 -0700157 cls.lb_member_vip_ipv6_net = {'id': uuidutils.generate_uuid()}
Jude Cross986e3f52017-07-24 14:57:20 -0700158 cls.lb_member_vip_ipv6_subnet = {'id':
159 uuidutils.generate_uuid()}
160 cls.lb_member_1_ipv6_subnet = {'id': uuidutils.generate_uuid()}
161 cls.lb_member_2_ipv6_subnet = {'id': uuidutils.generate_uuid()}
Michael Johnson590fbe12019-07-03 14:30:01 -0700162 cls.lb_member_vip_ipv6_subnet_stateful = True
Jude Cross986e3f52017-07-24 14:57:20 -0700163 return
164 elif CONF.load_balancer.test_network_override:
165 if conf_lb.test_subnet_override:
166 override_subnet = show_subnet(conf_lb.test_subnet_override)
167 else:
168 override_subnet = None
169
170 show_net = cls.lb_mem_net_client.show_network
171 override_network = show_net(conf_lb.test_network_override)
172 override_network = override_network.get('network')
173
174 cls.lb_member_vip_net = override_network
175 cls.lb_member_vip_subnet = override_subnet
176 cls.lb_member_1_net = override_network
177 cls.lb_member_1_subnet = override_subnet
178 cls.lb_member_2_net = override_network
179 cls.lb_member_2_subnet = override_subnet
180
181 if (CONF.load_balancer.test_with_ipv6 and
182 conf_lb.test_IPv6_subnet_override):
183 override_ipv6_subnet = show_subnet(
184 conf_lb.test_IPv6_subnet_override)
185 cls.lb_member_vip_ipv6_subnet = override_ipv6_subnet
186 cls.lb_member_1_ipv6_subnet = override_ipv6_subnet
187 cls.lb_member_2_ipv6_subnet = override_ipv6_subnet
Michael Johnson590fbe12019-07-03 14:30:01 -0700188 cls.lb_member_vip_ipv6_subnet_stateful = False
189 if (override_ipv6_subnet[0]['ipv6_address_mode'] ==
190 'dhcpv6-stateful'):
191 cls.lb_member_vip_ipv6_subnet_stateful = True
Jude Cross986e3f52017-07-24 14:57:20 -0700192 else:
193 cls.lb_member_vip_ipv6_subnet = None
194 cls.lb_member_1_ipv6_subnet = None
195 cls.lb_member_2_ipv6_subnet = None
196 else:
197 cls._create_networks()
198
199 LOG.debug('Octavia Setup: lb_member_vip_net = {}'.format(
200 cls.lb_member_vip_net[const.ID]))
201 if cls.lb_member_vip_subnet:
202 LOG.debug('Octavia Setup: lb_member_vip_subnet = {}'.format(
203 cls.lb_member_vip_subnet[const.ID]))
204 LOG.debug('Octavia Setup: lb_member_1_net = {}'.format(
205 cls.lb_member_1_net[const.ID]))
206 if cls.lb_member_1_subnet:
207 LOG.debug('Octavia Setup: lb_member_1_subnet = {}'.format(
208 cls.lb_member_1_subnet[const.ID]))
209 LOG.debug('Octavia Setup: lb_member_2_net = {}'.format(
210 cls.lb_member_2_net[const.ID]))
211 if cls.lb_member_2_subnet:
212 LOG.debug('Octavia Setup: lb_member_2_subnet = {}'.format(
213 cls.lb_member_2_subnet[const.ID]))
Michael Johnson124ba8b2018-08-30 16:06:05 -0700214 if CONF.load_balancer.test_with_ipv6:
215 if cls.lb_member_vip_ipv6_subnet:
216 LOG.debug('Octavia Setup: lb_member_vip_ipv6_subnet = '
217 '{}'.format(cls.lb_member_vip_ipv6_subnet[const.ID]))
218 if cls.lb_member_1_ipv6_subnet:
219 LOG.debug('Octavia Setup: lb_member_1_ipv6_subnet = {}'.format(
220 cls.lb_member_1_ipv6_subnet[const.ID]))
221 if cls.lb_member_2_ipv6_subnet:
222 LOG.debug('Octavia Setup: lb_member_2_ipv6_subnet = {}'.format(
223 cls.lb_member_2_ipv6_subnet[const.ID]))
Jude Cross986e3f52017-07-24 14:57:20 -0700224
Jude Cross986e3f52017-07-24 14:57:20 -0700225 @classmethod
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800226 # Neutron can be slow to clean up ports from the subnets/networks.
227 # Retry this delete a few times if we get a "Conflict" error to give
228 # neutron time to fully cleanup the ports.
229 @tenacity.retry(
230 retry=tenacity.retry_if_exception_type(exceptions.Conflict),
231 wait=tenacity.wait_incrementing(
232 RETRY_INITIAL_DELAY, RETRY_BACKOFF, RETRY_MAX),
233 stop=tenacity.stop_after_attempt(RETRY_ATTEMPTS))
234 def _logging_delete_network(cls, net_id):
235 try:
236 cls.lb_mem_net_client.delete_network(net_id)
237 except Exception:
238 LOG.error('Unable to delete network {}. Active ports:'.format(
239 net_id))
240 LOG.error(cls.lb_mem_ports_client.list_ports())
241 raise
242
243 @classmethod
244 # Neutron can be slow to clean up ports from the subnets/networks.
245 # Retry this delete a few times if we get a "Conflict" error to give
246 # neutron time to fully cleanup the ports.
247 @tenacity.retry(
248 retry=tenacity.retry_if_exception_type(exceptions.Conflict),
249 wait=tenacity.wait_incrementing(
250 RETRY_INITIAL_DELAY, RETRY_BACKOFF, RETRY_MAX),
251 stop=tenacity.stop_after_attempt(RETRY_ATTEMPTS))
252 def _logging_delete_subnet(cls, subnet_id):
253 try:
254 cls.lb_mem_subnet_client.delete_subnet(subnet_id)
255 except Exception:
256 LOG.error('Unable to delete subnet {}. Active ports:'.format(
257 subnet_id))
258 LOG.error(cls.lb_mem_ports_client.list_ports())
259 raise
260
261 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700262 def _create_networks(cls):
263 """Creates networks, subnets, and routers used in tests.
264
265 The following are expected to be defined and available to the tests:
266 cls.lb_member_vip_net
267 cls.lb_member_vip_subnet
268 cls.lb_member_vip_ipv6_subnet (optional)
269 cls.lb_member_1_net
270 cls.lb_member_1_subnet
271 cls.lb_member_1_ipv6_subnet (optional)
272 cls.lb_member_2_net
273 cls.lb_member_2_subnet
274 cls.lb_member_2_ipv6_subnet (optional)
275 """
276
277 # Create tenant VIP network
278 network_kwargs = {
279 'name': data_utils.rand_name("lb_member_vip_network")}
280 if CONF.network_feature_enabled.port_security:
281 # Note: Allowed Address Pairs requires port security
282 network_kwargs['port_security_enabled'] = True
283 result = cls.lb_mem_net_client.create_network(**network_kwargs)
284 cls.lb_member_vip_net = result['network']
285 LOG.info('lb_member_vip_net: {}'.format(cls.lb_member_vip_net))
286 cls.addClassResourceCleanup(
287 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800288 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700289 cls.lb_mem_net_client.show_network,
290 cls.lb_member_vip_net['id'])
291
292 # Create tenant VIP subnet
293 subnet_kwargs = {
294 'name': data_utils.rand_name("lb_member_vip_subnet"),
295 'network_id': cls.lb_member_vip_net['id'],
296 'cidr': CONF.load_balancer.vip_subnet_cidr,
297 'ip_version': 4}
298 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
299 cls.lb_member_vip_subnet = result['subnet']
300 LOG.info('lb_member_vip_subnet: {}'.format(cls.lb_member_vip_subnet))
301 cls.addClassResourceCleanup(
302 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800303 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700304 cls.lb_mem_subnet_client.show_subnet,
305 cls.lb_member_vip_subnet['id'])
306
307 # Create tenant VIP IPv6 subnet
308 if CONF.load_balancer.test_with_ipv6:
Adam Harwell2b9432f2019-05-02 13:56:09 -0600309 # See if ipv6-private-subnet exists and use it if so.
310 priv_ipv6_subnet = cls.os_admin.subnets_client.list_subnets(
311 name='ipv6-private-subnet')['subnets']
Michael Johnson5a16ad32018-10-18 14:49:11 -0700312
Michael Johnson590fbe12019-07-03 14:30:01 -0700313 cls.lb_member_vip_ipv6_subnet_stateful = False
Adam Harwell2b9432f2019-05-02 13:56:09 -0600314 if len(priv_ipv6_subnet) == 1:
Carlos Goncalves84af48c2019-07-25 15:51:30 +0200315 if (priv_ipv6_subnet[0]['ipv6_address_mode'] ==
316 'dhcpv6-stateful'):
317 cls.lb_member_vip_ipv6_subnet_stateful = True
Adam Harwell2b9432f2019-05-02 13:56:09 -0600318 cls.lb_member_vip_ipv6_subnet = priv_ipv6_subnet[0]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700319 cls.lb_member_vip_ipv6_net = {
Adam Harwell2b9432f2019-05-02 13:56:09 -0600320 'id': priv_ipv6_subnet[0]['network_id']}
Michael Johnson5a16ad32018-10-18 14:49:11 -0700321 else:
322 subnet_kwargs = {
323 'name': data_utils.rand_name("lb_member_vip_ipv6_subnet"),
324 'network_id': cls.lb_member_vip_net['id'],
325 'cidr': CONF.load_balancer.vip_ipv6_subnet_cidr,
326 'ip_version': 6}
327 result = cls.lb_mem_subnet_client.create_subnet(
328 **subnet_kwargs)
Michael Johnson7c5b9012019-05-28 11:02:29 -0700329 cls.lb_member_vip_ipv6_net = cls.lb_member_vip_net
Michael Johnson5a16ad32018-10-18 14:49:11 -0700330 cls.lb_member_vip_ipv6_subnet = result['subnet']
331 cls.addClassResourceCleanup(
332 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800333 cls._logging_delete_subnet,
Michael Johnson5a16ad32018-10-18 14:49:11 -0700334 cls.lb_mem_subnet_client.show_subnet,
335 cls.lb_member_vip_ipv6_subnet['id'])
Carlos Goncalves84af48c2019-07-25 15:51:30 +0200336
Jude Cross986e3f52017-07-24 14:57:20 -0700337 LOG.info('lb_member_vip_ipv6_subnet: {}'.format(
338 cls.lb_member_vip_ipv6_subnet))
Jude Cross986e3f52017-07-24 14:57:20 -0700339
340 # Create tenant member 1 network
341 network_kwargs = {
342 'name': data_utils.rand_name("lb_member_1_network")}
343 if CONF.network_feature_enabled.port_security:
344 if CONF.load_balancer.enable_security_groups:
345 network_kwargs['port_security_enabled'] = True
346 else:
347 network_kwargs['port_security_enabled'] = False
348 result = cls.lb_mem_net_client.create_network(**network_kwargs)
349 cls.lb_member_1_net = result['network']
350 LOG.info('lb_member_1_net: {}'.format(cls.lb_member_1_net))
351 cls.addClassResourceCleanup(
352 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800353 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700354 cls.lb_mem_net_client.show_network,
355 cls.lb_member_1_net['id'])
356
357 # Create tenant member 1 subnet
358 subnet_kwargs = {
359 'name': data_utils.rand_name("lb_member_1_subnet"),
360 'network_id': cls.lb_member_1_net['id'],
361 'cidr': CONF.load_balancer.member_1_ipv4_subnet_cidr,
362 'ip_version': 4}
363 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
364 cls.lb_member_1_subnet = result['subnet']
365 LOG.info('lb_member_1_subnet: {}'.format(cls.lb_member_1_subnet))
366 cls.addClassResourceCleanup(
367 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800368 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700369 cls.lb_mem_subnet_client.show_subnet,
370 cls.lb_member_1_subnet['id'])
371
372 # Create tenant member 1 ipv6 subnet
373 if CONF.load_balancer.test_with_ipv6:
374 subnet_kwargs = {
375 'name': data_utils.rand_name("lb_member_1_ipv6_subnet"),
376 'network_id': cls.lb_member_1_net['id'],
377 'cidr': CONF.load_balancer.member_1_ipv6_subnet_cidr,
378 'ip_version': 6}
379 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700380 cls.lb_member_1_subnet_prefix = (
381 CONF.load_balancer.member_1_ipv6_subnet_cidr.rpartition('/')[2]
382 )
383 assert(cls.lb_member_1_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700384 cls.lb_member_1_ipv6_subnet = result['subnet']
385 LOG.info('lb_member_1_ipv6_subnet: {}'.format(
386 cls.lb_member_1_ipv6_subnet))
387 cls.addClassResourceCleanup(
388 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800389 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700390 cls.lb_mem_subnet_client.show_subnet,
391 cls.lb_member_1_ipv6_subnet['id'])
392
393 # Create tenant member 2 network
394 network_kwargs = {
395 'name': data_utils.rand_name("lb_member_2_network")}
396 if CONF.network_feature_enabled.port_security:
397 if CONF.load_balancer.enable_security_groups:
398 network_kwargs['port_security_enabled'] = True
399 else:
400 network_kwargs['port_security_enabled'] = False
401 result = cls.lb_mem_net_client.create_network(**network_kwargs)
402 cls.lb_member_2_net = result['network']
403 LOG.info('lb_member_2_net: {}'.format(cls.lb_member_2_net))
404 cls.addClassResourceCleanup(
405 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800406 cls._logging_delete_network,
Jude Cross986e3f52017-07-24 14:57:20 -0700407 cls.lb_mem_net_client.show_network,
408 cls.lb_member_2_net['id'])
409
410 # Create tenant member 2 subnet
411 subnet_kwargs = {
412 'name': data_utils.rand_name("lb_member_2_subnet"),
413 'network_id': cls.lb_member_2_net['id'],
414 'cidr': CONF.load_balancer.member_2_ipv4_subnet_cidr,
415 'ip_version': 4}
416 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
417 cls.lb_member_2_subnet = result['subnet']
418 LOG.info('lb_member_2_subnet: {}'.format(cls.lb_member_2_subnet))
419 cls.addClassResourceCleanup(
420 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800421 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700422 cls.lb_mem_subnet_client.show_subnet,
423 cls.lb_member_2_subnet['id'])
424
425 # Create tenant member 2 ipv6 subnet
426 if CONF.load_balancer.test_with_ipv6:
427 subnet_kwargs = {
428 'name': data_utils.rand_name("lb_member_2_ipv6_subnet"),
429 'network_id': cls.lb_member_2_net['id'],
430 'cidr': CONF.load_balancer.member_2_ipv6_subnet_cidr,
431 'ip_version': 6}
432 result = cls.lb_mem_subnet_client.create_subnet(**subnet_kwargs)
Michael Johnsonbf916df2018-10-17 10:59:28 -0700433 cls.lb_member_2_subnet_prefix = (
434 CONF.load_balancer.member_2_ipv6_subnet_cidr.rpartition('/')[2]
435 )
436 assert(cls.lb_member_2_subnet_prefix.isdigit())
Jude Cross986e3f52017-07-24 14:57:20 -0700437 cls.lb_member_2_ipv6_subnet = result['subnet']
438 LOG.info('lb_member_2_ipv6_subnet: {}'.format(
439 cls.lb_member_2_ipv6_subnet))
440 cls.addClassResourceCleanup(
441 waiters.wait_for_not_found,
Michael Johnson04dc5cb2019-01-20 11:03:50 -0800442 cls._logging_delete_subnet,
Jude Cross986e3f52017-07-24 14:57:20 -0700443 cls.lb_mem_subnet_client.show_subnet,
444 cls.lb_member_2_ipv6_subnet['id'])
445
Adam Harwellcd72b562018-05-07 11:37:22 -0700446 @classmethod
Michael Johnson07c9a632018-06-07 13:27:42 -0700447 def _setup_lb_network_kwargs(cls, lb_kwargs, ip_version=None,
448 use_fixed_ip=False):
Adam Harwell60ed9d92018-05-10 13:23:13 -0700449 if not ip_version:
450 ip_version = 6 if CONF.load_balancer.test_with_ipv6 else 4
Michael Johnson5a16ad32018-10-18 14:49:11 -0700451 if cls.lb_member_vip_subnet or cls.lb_member_vip_ipv6_subnet:
Adam Harwellcd72b562018-05-07 11:37:22 -0700452 ip_index = data_utils.rand_int_id(start=10, end=100)
Michael Johnsondfd818a2018-08-21 20:54:54 -0700453 while ip_index in cls.used_ips:
454 ip_index = data_utils.rand_int_id(start=10, end=100)
455 cls.used_ips.append(ip_index)
Adam Harwellcd72b562018-05-07 11:37:22 -0700456 if ip_version == 4:
Adam Harwellcd72b562018-05-07 11:37:22 -0700457 subnet_id = cls.lb_member_vip_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700458 if CONF.load_balancer.test_with_noop:
459 lb_vip_address = '198.18.33.33'
460 else:
461 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
462 network = ipaddress.IPv4Network(subnet['subnet']['cidr'])
463 lb_vip_address = str(network[ip_index])
Adam Harwellcd72b562018-05-07 11:37:22 -0700464 else:
Adam Harwellcd72b562018-05-07 11:37:22 -0700465 subnet_id = cls.lb_member_vip_ipv6_subnet[const.ID]
Michael Johnson5a16ad32018-10-18 14:49:11 -0700466 if CONF.load_balancer.test_with_noop:
467 lb_vip_address = '2001:db8:33:33:33:33:33:33'
468 else:
469 subnet = cls.os_admin.subnets_client.show_subnet(subnet_id)
470 network = ipaddress.IPv6Network(subnet['subnet']['cidr'])
471 lb_vip_address = str(network[ip_index])
Michael Johnson590fbe12019-07-03 14:30:01 -0700472 # If the subnet is IPv6 slaac or dhcpv6-stateless
473 # neutron does not allow a fixed IP
474 if not cls.lb_member_vip_ipv6_subnet_stateful:
475 use_fixed_ip = False
Adam Harwellcd72b562018-05-07 11:37:22 -0700476 lb_kwargs[const.VIP_SUBNET_ID] = subnet_id
Michael Johnson07c9a632018-06-07 13:27:42 -0700477 if use_fixed_ip:
478 lb_kwargs[const.VIP_ADDRESS] = lb_vip_address
Adam Harwellcd72b562018-05-07 11:37:22 -0700479 if CONF.load_balancer.test_with_noop:
480 lb_kwargs[const.VIP_NETWORK_ID] = (
481 cls.lb_member_vip_net[const.ID])
482 else:
483 lb_kwargs[const.VIP_NETWORK_ID] = cls.lb_member_vip_net[const.ID]
484 lb_kwargs[const.VIP_SUBNET_ID] = None
485
486
487class LoadBalancerBaseTestWithCompute(LoadBalancerBaseTest):
488 @classmethod
489 def resource_setup(cls):
490 super(LoadBalancerBaseTestWithCompute, cls).resource_setup()
491 # If validation is disabled in this cloud, we won't be able to
492 # start the webservers, so don't even boot them.
493 if not CONF.validation.run_validation:
494 return
495
496 # Create a keypair for the webservers
497 keypair_name = data_utils.rand_name('lb_member_keypair')
498 result = cls.lb_mem_keypairs_client.create_keypair(
499 name=keypair_name)
500 cls.lb_member_keypair = result['keypair']
501 LOG.info('lb_member_keypair: {}'.format(cls.lb_member_keypair))
502 cls.addClassResourceCleanup(
503 waiters.wait_for_not_found,
504 cls.lb_mem_keypairs_client.delete_keypair,
505 cls.lb_mem_keypairs_client.show_keypair,
506 keypair_name)
507
508 if (CONF.load_balancer.enable_security_groups and
509 CONF.network_feature_enabled.port_security):
510 # Set up the security group for the webservers
511 SG_name = data_utils.rand_name('lb_member_SG')
512 cls.lb_member_sec_group = (
513 cls.lb_mem_SG_client.create_security_group(
514 name=SG_name)['security_group'])
515 cls.addClassResourceCleanup(
516 waiters.wait_for_not_found,
517 cls.lb_mem_SG_client.delete_security_group,
518 cls.lb_mem_SG_client.show_security_group,
519 cls.lb_member_sec_group['id'])
520
521 # Create a security group rule to allow 80-81 (test webservers)
522 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
523 direction='ingress',
524 security_group_id=cls.lb_member_sec_group['id'],
525 protocol='tcp',
526 ethertype='IPv4',
527 port_range_min=80,
528 port_range_max=81)['security_group_rule']
529 cls.addClassResourceCleanup(
530 waiters.wait_for_not_found,
531 cls.lb_mem_SGr_client.delete_security_group_rule,
532 cls.lb_mem_SGr_client.show_security_group_rule,
533 SGr['id'])
534 # Create a security group rule to allow 22 (ssh)
535 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
536 direction='ingress',
537 security_group_id=cls.lb_member_sec_group['id'],
538 protocol='tcp',
539 ethertype='IPv4',
540 port_range_min=22,
541 port_range_max=22)['security_group_rule']
542 cls.addClassResourceCleanup(
543 waiters.wait_for_not_found,
544 cls.lb_mem_SGr_client.delete_security_group_rule,
545 cls.lb_mem_SGr_client.show_security_group_rule,
546 SGr['id'])
547 if CONF.load_balancer.test_with_ipv6:
548 # Create a security group rule to allow 80-81 (test webservers)
549 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
550 direction='ingress',
551 security_group_id=cls.lb_member_sec_group['id'],
552 protocol='tcp',
553 ethertype='IPv6',
554 port_range_min=80,
555 port_range_max=81)['security_group_rule']
556 cls.addClassResourceCleanup(
557 waiters.wait_for_not_found,
558 cls.lb_mem_SGr_client.delete_security_group_rule,
559 cls.lb_mem_SGr_client.show_security_group_rule,
560 SGr['id'])
561 # Create a security group rule to allow 22 (ssh)
562 SGr = cls.lb_mem_SGr_client.create_security_group_rule(
563 direction='ingress',
564 security_group_id=cls.lb_member_sec_group['id'],
565 protocol='tcp',
566 ethertype='IPv6',
567 port_range_min=22,
568 port_range_max=22)['security_group_rule']
569 cls.addClassResourceCleanup(
570 waiters.wait_for_not_found,
571 cls.lb_mem_SGr_client.delete_security_group_rule,
572 cls.lb_mem_SGr_client.show_security_group_rule,
573 SGr['id'])
574
575 LOG.info('lb_member_sec_group: {}'.format(cls.lb_member_sec_group))
576
577 # Create webserver 1 instance
578 server_details = cls._create_webserver('lb_member_webserver1',
579 cls.lb_member_1_net)
580
581 cls.lb_member_webserver1 = server_details['server']
582 cls.webserver1_ip = server_details.get('ipv4_address')
583 cls.webserver1_ipv6 = server_details.get('ipv6_address')
584 cls.webserver1_public_ip = server_details['public_ipv4_address']
585
586 LOG.debug('Octavia Setup: lb_member_webserver1 = {}'.format(
587 cls.lb_member_webserver1[const.ID]))
588 LOG.debug('Octavia Setup: webserver1_ip = {}'.format(
589 cls.webserver1_ip))
590 LOG.debug('Octavia Setup: webserver1_ipv6 = {}'.format(
591 cls.webserver1_ipv6))
592 LOG.debug('Octavia Setup: webserver1_public_ip = {}'.format(
593 cls.webserver1_public_ip))
594
595 # Create webserver 2 instance
596 server_details = cls._create_webserver('lb_member_webserver2',
597 cls.lb_member_2_net)
598
599 cls.lb_member_webserver2 = server_details['server']
600 cls.webserver2_ip = server_details.get('ipv4_address')
601 cls.webserver2_ipv6 = server_details.get('ipv6_address')
602 cls.webserver2_public_ip = server_details['public_ipv4_address']
603
604 LOG.debug('Octavia Setup: lb_member_webserver2 = {}'.format(
605 cls.lb_member_webserver2[const.ID]))
606 LOG.debug('Octavia Setup: webserver2_ip = {}'.format(
607 cls.webserver2_ip))
608 LOG.debug('Octavia Setup: webserver2_ipv6 = {}'.format(
609 cls.webserver2_ipv6))
610 LOG.debug('Octavia Setup: webserver2_public_ip = {}'.format(
611 cls.webserver2_public_ip))
612
Michael Johnsonbf916df2018-10-17 10:59:28 -0700613 if CONF.load_balancer.test_with_ipv6:
614 # Enable the IPv6 nic in webserver 1
615 cls._enable_ipv6_nic_webserver(
616 cls.webserver1_public_ip, cls.lb_member_keypair['private_key'],
617 cls.webserver1_ipv6, cls.lb_member_1_subnet_prefix)
618
619 # Enable the IPv6 nic in webserver 2
620 cls._enable_ipv6_nic_webserver(
621 cls.webserver2_public_ip, cls.lb_member_keypair['private_key'],
622 cls.webserver2_ipv6, cls.lb_member_2_subnet_prefix)
623
Adam Harwellcd72b562018-05-07 11:37:22 -0700624 # Set up serving on webserver 1
625 cls._install_start_webserver(cls.webserver1_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700626 cls.lb_member_keypair['private_key'],
627 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700628
629 # Validate webserver 1
Adam Harwelle029af22018-05-24 17:13:28 -0700630 cls._validate_webserver(cls.webserver1_public_ip,
631 cls.webserver1_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700632
633 # Set up serving on webserver 2
634 cls._install_start_webserver(cls.webserver2_public_ip,
Adam Harwelle029af22018-05-24 17:13:28 -0700635 cls.lb_member_keypair['private_key'],
636 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700637
638 # Validate webserver 2
Adam Harwelle029af22018-05-24 17:13:28 -0700639 cls._validate_webserver(cls.webserver2_public_ip,
640 cls.webserver2_response)
Adam Harwellcd72b562018-05-07 11:37:22 -0700641
642 @classmethod
643 def _create_networks(cls):
644 super(LoadBalancerBaseTestWithCompute, cls)._create_networks()
Jude Cross986e3f52017-07-24 14:57:20 -0700645 # Create a router for the subnets (required for the floating IP)
646 router_name = data_utils.rand_name("lb_member_router")
647 result = cls.lb_mem_routers_client.create_router(
648 name=router_name, admin_state_up=True,
649 external_gateway_info=dict(
650 network_id=CONF.network.public_network_id))
651 cls.lb_member_router = result['router']
652 LOG.info('lb_member_router: {}'.format(cls.lb_member_router))
653 cls.addClassResourceCleanup(
654 waiters.wait_for_not_found,
655 cls.lb_mem_routers_client.delete_router,
656 cls.lb_mem_routers_client.show_router,
657 cls.lb_member_router['id'])
658
659 # Add VIP subnet to router
660 cls.lb_mem_routers_client.add_router_interface(
661 cls.lb_member_router['id'],
662 subnet_id=cls.lb_member_vip_subnet['id'])
663 cls.addClassResourceCleanup(
664 waiters.wait_for_not_found,
665 cls.lb_mem_routers_client.remove_router_interface,
666 cls.lb_mem_routers_client.remove_router_interface,
667 cls.lb_member_router['id'],
668 subnet_id=cls.lb_member_vip_subnet['id'])
669
670 # Add member subnet 1 to router
671 cls.lb_mem_routers_client.add_router_interface(
672 cls.lb_member_router['id'],
673 subnet_id=cls.lb_member_1_subnet['id'])
674 cls.addClassResourceCleanup(
675 waiters.wait_for_not_found,
Jude Cross986e3f52017-07-24 14:57:20 -0700676 cls.lb_mem_routers_client.remove_router_interface,
677 cls.lb_mem_routers_client.remove_router_interface,
678 cls.lb_member_router['id'], subnet_id=cls.lb_member_1_subnet['id'])
679
680 # Add member subnet 2 to router
681 cls.lb_mem_routers_client.add_router_interface(
682 cls.lb_member_router['id'],
683 subnet_id=cls.lb_member_2_subnet['id'])
684 cls.addClassResourceCleanup(
685 waiters.wait_for_not_found,
686 cls.lb_mem_routers_client.remove_router_interface,
687 cls.lb_mem_routers_client.remove_router_interface,
688 cls.lb_member_router['id'], subnet_id=cls.lb_member_2_subnet['id'])
689
690 @classmethod
691 def _create_webserver(cls, name, network):
692 """Creates a webserver with two ports.
693
694 webserver_details dictionary contains:
695 server - The compute server object
696 ipv4_address - The IPv4 address for the server (optional)
697 ipv6_address - The IPv6 address for the server (optional)
698 public_ipv4_address - The publicly accessible IPv4 address for the
699 server, this may be a floating IP (optional)
700
701 :param name: The name of the server to create.
702 :param network: The network to boot the server on.
703 :returns: webserver_details dictionary.
704 """
705 server_kwargs = {
706 'name': data_utils.rand_name(name),
707 'flavorRef': CONF.compute.flavor_ref,
708 'imageRef': CONF.compute.image_ref,
709 'key_name': cls.lb_member_keypair['name']}
710 if (CONF.load_balancer.enable_security_groups and
711 CONF.network_feature_enabled.port_security):
712 server_kwargs['security_groups'] = [
713 {'name': cls.lb_member_sec_group['name']}]
714 if not CONF.load_balancer.disable_boot_network:
715 server_kwargs['networks'] = [{'uuid': network['id']}]
716
717 # Replace the name for clouds that have limitations
718 if CONF.load_balancer.random_server_name_length:
719 r = random.SystemRandom()
720 server_kwargs['name'] = "m{}".format("".join(
721 [r.choice(string.ascii_uppercase + string.digits)
722 for _ in range(
723 CONF.load_balancer.random_server_name_length - 1)]
724 ))
725 if CONF.load_balancer.availability_zone:
726 server_kwargs['availability_zone'] = (
727 CONF.load_balancer.availability_zone)
728
729 server = cls.lb_mem_servers_client.create_server(
730 **server_kwargs)['server']
731 cls.addClassResourceCleanup(
732 waiters.wait_for_not_found,
733 cls.lb_mem_servers_client.delete_server,
734 cls.lb_mem_servers_client.show_server,
735 server['id'])
736 server = waiters.wait_for_status(
737 cls.lb_mem_servers_client.show_server,
738 server['id'], 'status', 'ACTIVE',
739 CONF.load_balancer.build_interval,
740 CONF.load_balancer.build_timeout,
741 root_tag='server')
742 webserver_details = {'server': server}
743 LOG.info('Created server: {}'.format(server))
744
745 addresses = server['addresses']
746 if CONF.load_balancer.disable_boot_network:
747 instance_network = addresses.values()[0]
748 else:
749 instance_network = addresses[network['name']]
750 for addr in instance_network:
751 if addr['version'] == 4:
752 webserver_details['ipv4_address'] = addr['addr']
753 if addr['version'] == 6:
754 webserver_details['ipv6_address'] = addr['addr']
755
756 if CONF.validation.connect_method == 'floating':
757 result = cls.lb_mem_ports_client.list_ports(
758 network_id=network['id'],
759 mac_address=instance_network[0]['OS-EXT-IPS-MAC:mac_addr'])
760 port_id = result['ports'][0]['id']
761 result = cls.lb_mem_float_ip_client.create_floatingip(
762 floating_network_id=CONF.network.public_network_id,
763 port_id=port_id)
764 floating_ip = result['floatingip']
765 LOG.info('webserver1_floating_ip: {}'.format(floating_ip))
766 cls.addClassResourceCleanup(
767 waiters.wait_for_not_found,
768 cls.lb_mem_float_ip_client.delete_floatingip,
769 cls.lb_mem_float_ip_client.show_floatingip,
770 floatingip_id=floating_ip['id'])
771 webserver_details['public_ipv4_address'] = (
772 floating_ip['floating_ip_address'])
773 else:
774 webserver_details['public_ipv4_address'] = (
775 instance_network[0]['addr'])
776
777 return webserver_details
778
779 @classmethod
Adam Harwellcd72b562018-05-07 11:37:22 -0700780 def _install_start_webserver(cls, ip_address, ssh_key, start_id):
781 local_file = pkg_resources.resource_filename(
782 'octavia_tempest_plugin.contrib.httpd', 'httpd.bin')
783 dest_file = '/dev/shm/httpd.bin'
784
785 linux_client = remote_client.RemoteClient(
786 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
787 linux_client.validate_authentication()
788
789 with tempfile.NamedTemporaryFile() as key:
790 key.write(ssh_key.encode('utf-8'))
791 key.flush()
792 cmd = ("scp -v -o UserKnownHostsFile=/dev/null "
793 "-o StrictHostKeyChecking=no "
794 "-o ConnectTimeout={0} -o ConnectionAttempts={1} "
795 "-i {2} {3} {4}@{5}:{6}").format(
796 CONF.load_balancer.scp_connection_timeout,
797 CONF.load_balancer.scp_connection_attempts,
798 key.name, local_file, CONF.validation.image_ssh_user,
799 ip_address, dest_file)
800 args = shlex.split(cmd)
801 subprocess_args = {'stdout': subprocess.PIPE,
802 'stderr': subprocess.STDOUT,
803 'cwd': None}
804 proc = subprocess.Popen(args, **subprocess_args)
805 stdout, stderr = proc.communicate()
806 if proc.returncode != 0:
807 raise exceptions.CommandFailed(proc.returncode, cmd,
808 stdout, stderr)
Gregory Thiemongef72a8862019-08-06 17:25:42 +0200809
810 # Enabling memory overcommit allows to run golang static binaries
811 # compiled with a recent golang toolchain (>=1.11). Those binaries
812 # allocate a large amount of virtual memory at init time, and this
813 # allocation fails in tempest's nano flavor (64MB of RAM)
814 # (golang issue reported in https://github.com/golang/go/issues/28114,
815 # follow-up: https://github.com/golang/go/issues/28081)
816 # TODO(gthiemonge): Remove this call when golang issue is resolved.
817 linux_client.exec_command('sudo sh -c "echo 1 > '
818 '/proc/sys/vm/overcommit_memory"')
819
Adam Harwellcd72b562018-05-07 11:37:22 -0700820 linux_client.exec_command('sudo screen -d -m {0} -port 80 '
821 '-id {1}'.format(dest_file, start_id))
822 linux_client.exec_command('sudo screen -d -m {0} -port 81 '
823 '-id {1}'.format(dest_file, start_id + 1))
824
Michael Johnsonbf916df2018-10-17 10:59:28 -0700825 # Cirros does not configure the assigned IPv6 address by default
826 # so enable it manually like tempest does here:
827 # tempest/scenario/test_netowrk_v6.py turn_nic6_on()
828 @classmethod
829 def _enable_ipv6_nic_webserver(cls, ip_address, ssh_key,
830 ipv6_address, ipv6_prefix):
831 linux_client = remote_client.RemoteClient(
832 ip_address, CONF.validation.image_ssh_user, pkey=ssh_key)
833 linux_client.validate_authentication()
834
835 linux_client.exec_command('sudo ip address add {0}/{1} dev '
836 'eth0'.format(ipv6_address, ipv6_prefix))
837
Adam Harwellcd72b562018-05-07 11:37:22 -0700838 @classmethod
Jude Cross986e3f52017-07-24 14:57:20 -0700839 def _validate_webserver(cls, ip_address, start_id):
840 URL = 'http://{0}'.format(ip_address)
841 validators.validate_URL_response(URL, expected_body=str(start_id))
842 URL = 'http://{0}:81'.format(ip_address)
843 validators.validate_URL_response(URL, expected_body=str(start_id + 1))
844
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800845 def _wait_for_lb_functional(self, vip_address,
846 protocol='http', verify=True):
Adam Harwellcd72b562018-05-07 11:37:22 -0700847 session = requests.Session()
848 start = time.time()
849
850 while time.time() - start < CONF.load_balancer.build_timeout:
851 try:
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800852 session.get("{0}://{1}".format(protocol, vip_address),
853 timeout=2, verify=verify)
Adam Harwellcd72b562018-05-07 11:37:22 -0700854 time.sleep(1)
855 return
856 except Exception:
857 LOG.warning('Server is not passing initial traffic. Waiting.')
858 time.sleep(1)
859 LOG.error('Server did not begin passing traffic within the timeout '
860 'period. Failing test.')
861 raise Exception()
862
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800863 def check_members_balanced(self, vip_address, traffic_member_count=2,
864 protocol='http', verify=True):
Adam Harwellcd72b562018-05-07 11:37:22 -0700865 session = requests.Session()
866 response_counts = {}
867
Michael Johnson5a16ad32018-10-18 14:49:11 -0700868 if ipaddress.ip_address(vip_address).version == 6:
869 vip_address = '[{}]'.format(vip_address)
870
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800871 self._wait_for_lb_functional(vip_address, protocol, verify)
Adam Harwellcd72b562018-05-07 11:37:22 -0700872
873 # Send a number requests to lb vip
874 for i in range(20):
875 try:
Michael Johnson0a0f9b32019-01-02 16:58:21 -0800876 r = session.get('{0}://{1}'.format(protocol, vip_address),
877 timeout=2, verify=verify)
Adam Harwellcd72b562018-05-07 11:37:22 -0700878
879 if r.content in response_counts:
880 response_counts[r.content] += 1
881 else:
882 response_counts[r.content] = 1
883
884 except Exception:
885 LOG.exception('Failed to send request to loadbalancer vip')
886 raise Exception('Failed to connect to lb')
887
888 LOG.debug('Loadbalancer response totals: %s', response_counts)
889 # Ensure the correct number of members
Adam Harwell60ed9d92018-05-10 13:23:13 -0700890 self.assertEqual(traffic_member_count, len(response_counts))
Adam Harwellcd72b562018-05-07 11:37:22 -0700891
892 # Ensure both members got the same number of responses
893 self.assertEqual(1, len(set(response_counts.values())))
Adam Harwelle029af22018-05-24 17:13:28 -0700894
895 def assertConsistentResponse(self, response, url, method='GET', repeat=10,
896 redirect=False, timeout=2, **kwargs):
897 """Assert that a request to URL gets the expected response.
898
899 :param response: Expected response in format (status_code, content).
900 :param url: The URL to request.
901 :param method: The HTTP method to use (GET, POST, PUT, etc)
902 :param repeat: How many times to test the response.
903 :param data: Optional data to send in the request.
904 :param headers: Optional headers to send in the request.
905 :param cookies: Optional cookies to send in the request.
906 :param redirect: Is the request a redirect? If true, assume the passed
907 content should be the next URL in the chain.
Carlos Goncalvesc451ff92018-12-19 19:11:53 +0100908 :param timeout: Optional seconds to wait for the server to send data.
909
Adam Harwelle029af22018-05-24 17:13:28 -0700910 :return: boolean success status
911
912 :raises: testtools.matchers.MismatchError
913 """
914 session = requests.Session()
915 response_code, response_content = response
916
917 for i in range(0, repeat):
918 req = session.request(method, url, allow_redirects=not redirect,
919 timeout=timeout, **kwargs)
920 if response_code:
921 self.assertEqual(response_code, req.status_code)
922 if redirect:
923 self.assertTrue(req.is_redirect)
Carlos Goncalvesc451ff92018-12-19 19:11:53 +0100924 self.assertEqual(response_content,
925 session.get_redirect_target(req))
Adam Harwelle029af22018-05-24 17:13:28 -0700926 elif response_content:
927 self.assertEqual(six.text_type(response_content), req.text)