def make_clients(self): config = {'type': 'aws', 'region': 'east', 'name': 'model-a'} env = JujuData('model-a', config, juju_home='foo') env.user_name = 'me' source_client = fake_juju_client(env) dest_client = fake_juju_client(env) return source_client, dest_client
def test_assert_user_permissions(self): User = namedtuple('user', ['name', 'permissions', 'expect']) read_user = User('readuser', 'read', [True, False, False, False, False, False]) write_user = User('writeuser', 'write', [True, True, False, True, False, False]) admin_user = User('adminuser', 'admin', [True, True, True, True, False, False]) users = [read_user, write_user, admin_user] for user in users: fake_client = fake_juju_client() fake_admin_client = fake_juju_client() ac = patch("assess_user_grant_revoke.assert_admin_model", return_value=True) with patch("jujupy.ModelClient.revoke", return_value=True): with patch("assess_user_grant_revoke.assert_read_model", return_value=True) as read_mock: with patch("assess_user_grant_revoke.assert_write_model", return_value=True) as write_mock: with ac as admin_mock: assert_user_permissions(user, fake_client, fake_admin_client) self.assertEqual(read_mock.call_count, 2) self.assertEqual(write_mock.call_count, 2) self.assertEqual(admin_mock.call_count, 2)
def test_same_home(self): initial_client = fake_juju_client(version='1.25') other_client = fake_juju_client( env=initial_client.env, _backend=initial_client._backend.clone(version='2.0.0')) bs_manager = FakeBootstrapManager(initial_client) bs_manager.permanent = True test_control_heterogeneous(bs_manager, other_client, True) self.assertEqual(initial_client.env.juju_home, other_client.env.juju_home)
def test_gives_second_manager_unique_env(self): ret_bs = [ Mock(client=fake_juju_client(), temp_env_name='testing-env-name'), Mock(client=fake_juju_client())] with temp_dir() as log_dir: args = argparse.Namespace(logs=log_dir) with patch.object(BootstrapManager, 'from_args', side_effect=ret_bs): bs1, bs2 = amm.get_bootstrap_managers(args) self.assertEqual(bs2.temp_env_name, 'testing-env-name-b')
def test_returns_two_bs_managers(self): ret_bs = [ Mock(client=fake_juju_client()), Mock(client=fake_juju_client())] with temp_dir() as log_dir: args = argparse.Namespace(logs=log_dir) with patch.object( BootstrapManager, 'from_args', side_effect=ret_bs): bs1, bs2 = amm.get_bootstrap_managers(args) self.assertEqual(bs1, ret_bs[0]) self.assertEqual(bs2, ret_bs[1])
def test_get_controller_hostname(self): controller_client = Mock(wraps=fake_juju_client()) client = Mock(wraps=fake_juju_client()) with patch.object(client, 'get_controller_client', return_value=controller_client): with patch.object(controller_client, 'run', return_value=' maas-node-x\n') as run_mock: self.assertEqual('maas-node-x', get_controller_hostname(client)) run_mock.assert_called_once_with(['hostname'], machines=['0'], use_json=False)
def test_gives_second_manager_unique_env(self): ret_bs = [ Mock(client=fake_juju_client(), temp_env_name='testing-env-name'), Mock(client=fake_juju_client()) ] with temp_dir() as log_dir: args = argparse.Namespace(logs=log_dir) with patch.object(BootstrapManager, 'from_args', side_effect=ret_bs): bs1, bs2 = amm.get_bootstrap_managers(args) self.assertEqual(bs2.temp_env_name, 'testing-env-name-b')
def test_creates_unique_log_dirs(self): ret_bs = [ Mock(client=fake_juju_client()), Mock(client=fake_juju_client())] args = argparse.Namespace(logs='/some/path') with patch.object(BootstrapManager, 'from_args', side_effect=ret_bs): with patch.object(amm, '_new_log_dir') as log_dir: bs1, bs2 = amm.get_bootstrap_managers(args) self.assertEqual(2, log_dir.call_count) self.assertEqual( log_dir.mock_calls, [call(args.logs, 'a'), call(args.logs, 'b')])
def test_creates_unique_log_dirs(self): ret_bs = [ Mock(client=fake_juju_client()), Mock(client=fake_juju_client()) ] args = argparse.Namespace(logs='/some/path') with patch.object(BootstrapManager, 'from_args', side_effect=ret_bs): with patch.object(amm, '_new_log_dir') as log_dir: bs1, bs2 = amm.get_bootstrap_managers(args) self.assertEqual(2, log_dir.call_count) self.assertEqual(log_dir.mock_calls, [call(args.logs, 'a'), call(args.logs, 'b')])
def test_returns_two_bs_managers(self): ret_bs = [ Mock(client=fake_juju_client()), Mock(client=fake_juju_client()) ] with temp_dir() as log_dir: args = argparse.Namespace(logs=log_dir) with patch.object(BootstrapManager, 'from_args', side_effect=ret_bs): bs1, bs2 = amm.get_bootstrap_managers(args) self.assertEqual(bs1, ret_bs[0]) self.assertEqual(bs2, ret_bs[1])
def test_make_expected_disk_2(self): client = fake_juju_client() data = make_expected_disk(client, 2, 'foo/0') expected = { "storage": { "disks/1": { "kind": "block", "attachments": { "units": { "foo/0": { "location": "", "life": "alive" } } }, "life": "alive" }, "disks/2": { "kind": "block", "attachments": { "units": { "foo/0": { "location": "", "life": "alive" } } }, "life": "alive" } } } self.assertEqual(expected, data)
def test_neighbor_visibility(self): args = parse_args([]) net_health = AssessNetworkHealth(args) client = Mock(wraps=fake_juju_client()) client.bootstrap() now = datetime.now() + timedelta(days=1) with patch('utility.until_timeout.now', return_value=now): with patch.object(client, 'get_status', return_value=status): with patch.object(client, 'run', return_value=curl_result): client.deploy('ubuntu', num=2, series='trusty') client.deploy('network-health', series='trusty') out = net_health.neighbor_visibility(client) expected = { 'network-health': {}, 'ubuntu': { 'ubuntu/0': { '1.1.1.1': True, '1.1.1.2': True }, 'ubuntu/1': { '1.1.1.1': True, '1.1.1.2': True } } } self.assertEqual(expected, out)
def get_clients(initial, other, base_env, debug, agent_url): """Return the clients to use for testing.""" if initial == 'FAKE': environment = SimpleEnvironment.from_config(base_env) client = fake_juju_client(env=environment) return client, client, client else: initial_client = client_from_config(base_env, initial, debug=debug) environment = initial_client.env if agent_url is None: environment.discard_option('tools-metadata-url') other_client = initial_client.clone_path_cls(other) # System juju is assumed to be released and the best choice for tearing # down environments reliably. (For example, 1.18.x cannot tear down # environments with alpha agent-versions.) try: released_client = initial_client.clone_path_cls(None) except IncompatibleConfigClass: # If initial_client's config class is incompatible with the system # juju, use initial client for teardown. released_client = initial_client # If released_client is a different major version, it cannot tear down # initial client, so use initial client for teardown. if ( isinstance(released_client, EnvJujuClient1X) != isinstance(initial_client, EnvJujuClient1X) ): released_client = initial_client else: # If system juju is used, ensure it has identical env to # initial_client. released_client.env = initial_client.env return initial_client, other_client, released_client
def test_dummy_deployment(self): args = parse_args([]) net_health = AssessNetworkHealth(args) client = Mock(wraps=fake_juju_client()) client.bootstrap() net_health.setup_dummy_deployment(client, series) client.deploy.assert_called_once_with('ubuntu', num=2, series='trusty')
def test_deploy_charm_with_subordinate_charm(self): fake_client = Mock(wraps=fake_juju_client()) fake_client.bootstrap() deploy_charm_with_subordinate_charm(fake_client, 'xenial') fake_client.deploy.assert_has_calls( [call('dummy-sink'), call('dummy-subordinate')]) fake_client.wait_for_started.assert_has_calls([call()] * 2)
def test_assess_juju_output_successfully(self): fake_client = Mock(wraps=fake_juju_client()) app_status = Status( { 'applications': { 'dummy-sink': { 'units': { 'dummy-sink/0': { 'juju-status': { 'current': 'idle', 'since': 'DD MM YYYY hh:mm:ss', 'version': '2.0.0', }, 'subordinates': { 'dummy-subordinate/0': { 'juju-status': { 'current': 'idle', 'since': 'DD MM YYYY hh:mm:ss', 'version': '2.0.0' } } } } } } } }, '') fake_client.bootstrap() fake_client.get_status.return_value = app_status assess_juju_status(fake_client, "xenial") self.assertIn('assess juju-status attribute done successfully', self.log_stream.getvalue())
def test_returns_expected_details(self): client = fake_juju_client() client.bootstrap() client.deploy('mongodb') self.assertEqual( dict(mongodb=1), pd.get_client_details(client))
def test_bundle_deployment(self): args = parse_args([]) net_health = AssessNetworkHealth(args) client = Mock(wraps=fake_juju_client()) client.bootstrap() net_health.setup_bundle_deployment(client, bundle_string) client.deploy_bundle.assert_called_once_with(bundle_string)
def test_destroy_model_fails(self): fake_client = Mock(wraps=fake_juju_client()) fake_client.bootstrap() fake_client.get_juju_output.return_value = list_model_initial pattern = 'Juju failed to unset model after it was destroyed' with self.assertRaisesRegexp(JujuAssertionError, pattern): destroy_model(fake_client, fake_client)
def test_switch_model_fails(self): fake_client = Mock(wraps=fake_juju_client()) fake_client.bootstrap() fake_client.get_juju_output.return_value = list_model_switch pattern = 'Expected test-tmp-env got bar-tmp-env' with self.assertRaisesRegexp(JujuAssertionError, pattern): switch_model(fake_client, 'foo-tmp-env', 'test-tmp-env')
def test_raises_JujuAssertionError_when_source_doesnt_match(self): client = fake_juju_client() with patch.object(client, 'get_model_config') as gmc_mock: gmc_mock.return_value = { 'testattr': {'source': 'default', 'value': False}} with self.assertRaises(JujuAssertionError): amct.assert_config_value(client, 'testattr', 'model', False)
def test_prepare_temp_metadata(self): client = fake_juju_client() with patch('assess_bootstrap.prepare_metadata', autospec=True) as prepare_mock: with prepare_temp_metadata(client) as metadata_dir: pass prepare_mock.assert_called_once_with(client, metadata_dir, None, None)
def test_calls_provided_test(self): client = fake_juju_client() with temp_dir() as juju_home: client.env.juju_home = juju_home bs_manager = make_bootstrap_manager(client) bs_manager.log_dir = os.path.join(juju_home, 'log-dir') os.mkdir(bs_manager.log_dir) timing = gpr.TimingData(datetime.utcnow(), datetime.utcnow()) deploy_details = gpr.DeployDetails('test', dict(), timing) noop_test = Mock(return_value=deploy_details) pprof_collector = Mock() with patch.object(gpr, 'dump_performance_metrics_logs', autospec=True): with patch.object(gpr, 'generate_reports', autospec=True): with patch.object( gpr, 'PPROFCollector', autospec=True) as p_pc: p_pc.return_value = pprof_collector gpr.run_perfscale_test( noop_test, bs_manager, get_default_args()) noop_test.assert_called_once_with( client, pprof_collector, get_default_args())
def test_returns_machine_id_for_ha_enabled(self): client = fake_juju_client() client.bootstrap() client.enable_ha() self.assertListEqual( ['0', '1', '2'], gpr.get_controller_machine_ids(client.get_controller_client()))
def make_fake_client(): fake_client = fake_juju_client() old_backend = fake_client._backend fake_client._backend = FakeBackendShellEnv( old_backend.controller_state, old_backend.feature_flags, old_backend.version, old_backend.full_path, old_backend.debug) return fake_client
def test_setup_for_ha_enabled(self): client = fake_juju_client() client.bootstrap() client.enable_ha() admin_client = client.get_controller_client() with patch.object( gpr, '_setup_system_monitoring', autospec=True) as m_ssm: with patch.object( gpr, '_enable_monitoring', autospec=True) as m_em: self.assertListEqual( ['0', '1', '2'], gpr.setup_system_monitoring(admin_client)) self.assertListEqual( m_ssm.call_args_list, [ call(admin_client, '0'), call(admin_client, '1'), call(admin_client, '2')]) self.assertListEqual( m_em.call_args_list, [ call(admin_client, '0'), call(admin_client, '1'), call(admin_client, '2')])
def test_iter_steps_context(self): client = fake_juju_client() bs_manager = FakeBootstrapManager(client) quickstart = QuickstartTest(bs_manager, '/tmp/bundle.yaml', 2) step_iter = quickstart.iter_steps() self.assertIs(False, bs_manager.entered_top) self.assertIs(False, bs_manager.exited_top) self.assertIs(False, bs_manager.entered_bootstrap) self.assertIs(False, bs_manager.exited_bootstrap) step_iter.next() models = client._backend.controller_state.models backing_state = models[client.model_name] self.assertEqual('/tmp/bundle.yaml', backing_state.current_bundle) self.assertIs(True, bs_manager.entered_top) self.assertIs(True, bs_manager.entered_bootstrap) self.assertIs(False, bs_manager.exited_bootstrap) self.assertIs(False, bs_manager.entered_runtime) self.assertIs(False, bs_manager.exited_runtime) step_iter.next() self.assertIs(True, bs_manager.exited_bootstrap) self.assertIs(True, bs_manager.entered_runtime) self.assertIs(False, bs_manager.exited_runtime) with patch.object(client, 'wait_for_deploy_started') as wfds_mock: step_iter.next() wfds_mock.assert_called_once_with(2) self.assertIs(False, bs_manager.exited_runtime) with patch.object(client, 'wait_for_started') as wfs_mock: step_iter.next() wfs_mock.assert_called_once_with(3600) self.assertIs(False, bs_manager.exited_runtime) with self.assertRaises(StopIteration): step_iter.next() self.assertIs(True, bs_manager.exited_runtime) self.assertIs(True, bs_manager.exited_top)
def test_multiple_constraints(self): fake_client = Mock(wraps=fake_juju_client()) with patch('assess_constraints.prepare_constraint_test', autospec=True, side_effect=[ { 'root-disk': '8G', 'cpu-power': '40' }, { 'root-disk': '15G', 'cpu-power': '20' }, { 'root-disk': '15G', 'cpu-power': '40' }, ]) as prepare_mock: assess_multiple_constraints(fake_client, 'test', root_disk='15G', cpu_power='40') self.assertEqual(3, prepare_mock.call_count) prepare_mock.assert_has_calls([ call(fake_client, Constraints(cpu_power='40'), 'test-part0'), call(fake_client, Constraints(root_disk='15G'), 'test-part1'), call(fake_client, Constraints(root_disk='15G', cpu_power='40'), 'test-whole'), ])
def test_returns_machine_id_for_ha_enabled(self): client = fake_juju_client() client.bootstrap() client.enable_ha() self.assertListEqual(['0', '1', '2'], gpr.get_controller_machine_ids( client.get_controller_client()))
def test_asssess_show_cloud_mismatch(self): client = fake_juju_client() with override_show_cloud( self, client, { 'localhost1': { 'defined': 'local', 'type': 'maas', 'description': 'Metal As A Service', }, 'localhost2': { 'defined': 'local', 'type': 'openstack', 'description': 'Openstack Cloud', }, }): with self.assertRaises(JujuAssertionError): assess_show_cloud( client, { 'localhost1': { 'type': 'openstack' }, 'localhost2': { 'type': 'openstack' }, })
def test_calls_provided_test(self): client = fake_juju_client() with temp_dir() as juju_home: client.env.juju_home = juju_home bs_manager = make_bootstrap_manager(client) bs_manager.log_dir = os.path.join(juju_home, 'log-dir') os.mkdir(bs_manager.log_dir) timing = gpr.TimingData(datetime.utcnow(), datetime.utcnow()) deploy_details = gpr.DeployDetails('test', dict(), timing) noop_test = Mock(return_value=deploy_details) pprof_collector = Mock() with patch.object(gpr, 'dump_performance_metrics_logs', autospec=True): with patch.object(gpr, 'generate_reports', autospec=True): with patch.object(gpr, 'PPROFCollector', autospec=True) as p_pc: p_pc.return_value = pprof_collector gpr.run_perfscale_test(noop_test, bs_manager, get_default_args()) noop_test.assert_called_once_with(client, pprof_collector, get_default_args())
def test_root_disk_constraints(self): fake_client = Mock(wraps=fake_juju_client()) with patch('assess_constraints.prepare_constraint_test', autospec=True, return_value={'root-disk': '8G'}) as prepare_mock: with self.assertRaises(JujuAssertionError): assess_root_disk_constraints(fake_client, ['8G', '16G']) self.assertEqual(2, prepare_mock.call_count)
def test_apply_condition_raises_ErrUnitCondition(self): client = fake_juju_client() remote = FakeRemote() with patch('run_deployer.remote_from_unit', return_value=remote) as rfu_mock: with self.assertRaises(ErrUnitCondition): apply_condition(client, 'bla/0:foo') rfu_mock.assert_called_once_with(client, 'bla/0')
def test_apply_condition_clock_skew(self): client = fake_juju_client() remote = FakeRemote() with patch('run_deployer.remote_from_unit', return_value=remote, autospec=True) as ru_mock: apply_condition(client, 'bla/0:clock_skew') ru_mock.assert_called_once_with(client, 'bla/0') self.assertEqual(CLOCK_SKEW_SCRIPT, remote.command)
def test_cpu_power_constraints(self): fake_client = Mock(wraps=fake_juju_client()) with patch('assess_constraints.prepare_constraint_test', autospec=True, return_value={'cpu-power': '20'}) as prepare_mock: with self.assertRaises(JujuAssertionError): assess_cpu_power_constraints(fake_client, ['10', '30']) self.assertEqual(2, prepare_mock.call_count)
def test_cpu_power_constraints(self): fake_client = Mock(wraps=fake_juju_client()) with patch('assess_constraints.prepare_constraint_test', autospec=True, return_value={'cpu-power': '20'} ) as prepare_mock: with self.assertRaises(JujuAssertionError): assess_cpu_power_constraints(fake_client, ['10', '30']) self.assertEqual(2, prepare_mock.call_count)
def test_returns_when_migration_status_found(self): client = fake_juju_client() with patch.object( client, 'get_juju_output', autospec=True, return_value=self.migration_status_yaml): with patch.object(amm, 'sleep', autospec=True) as m_sleep: amm.wait_for_migrating(client) self.assertEqual(m_sleep.call_count, 0)
def test_add_model_fails(self): fake_client = Mock(wraps=fake_juju_client()) fake_client.bootstrap() fake_client.get_juju_output.return_value = list_model_initial fake_client.add_model.return_value = fake_client pattern = 'Expected test-tmp-env got foo-tmp-env' with self.assertRaisesRegexp(JujuAssertionError, pattern): add_model(fake_client)
def test_root_disk_constraints(self): fake_client = Mock(wraps=fake_juju_client()) with patch('assess_constraints.prepare_constraint_test', autospec=True, return_value={'root-disk': '8G'} ) as prepare_mock: with self.assertRaises(JujuAssertionError): assess_root_disk_constraints(fake_client, ['8G', '16G']) self.assertEqual(2, prepare_mock.call_count)
def test_no_leader_only_has_controller(self, ti_mock, wsss_mock): client = fake_juju_client() bs_manager = make_bs_manager(client) client.bootstrap() bs_manager.has_controller = True delete_controller_members(bs_manager, client.get_controller_client(), leader_only=False) self.assertIs(False, bs_manager.has_controller)
def test_assess_ha_recovery(self): client = fake_juju_client() bs_manager = Mock(client=client, known_hosts={}, has_controller=False) with patch.object(client, 'juju', autospec=True) as j_mock: with patch.object(client, 'get_status', autospec=True) as gs_mock: assess_ha_recovery(bs_manager, client) j_mock.assert_called_once_with('status', (), check=True, timeout=300) gs_mock.assert_called_once_with(timeout=300) self.assertIsTrue(bs_manager.has_controller)
def cloud_client(self, clouds): client = fake_juju_client(juju_home=self.juju_home) client.env.load_yaml() def dump(cloud_name, cloud): client.env.write_clouds(client.env.juju_home, clouds) with patch.object(client, 'add_cloud_interactive', dump): yield client
def test_assert_landscape_bundle(self): client = fake_juju_client() services = ['haproxy', 'landscape-server', 'postgresql', 'rabbitmq-server'] with patch('verify_landscape_bundle.verify_services', autospec=True) as vs_mock: assess_landscape_bundle(client) vs_mock.assert_called_once_with(client, services, scheme='https', text='Landscape', haproxy_exposed=True)
def make_fake_client(): fake_client = fake_juju_client() old_backend = fake_client._backend fake_client._backend = FakeBackendShellEnv(old_backend.controller_state, old_backend.feature_flags, old_backend.version, old_backend.full_path, old_backend.debug) return fake_client
def test_respects_machine_id_0(self): client = fake_juju_client() client.bootstrap() client.deploy('fill-logs') with patch('assess_log_rotation.test_rotation') as tr_mock: assess_machine_rotation(client) tr_mock.assert_called_once_with( client, '/var/log/juju/machine-0.log', 'machine-0', 'fill-machine', 'machine-size', 'megs=300', 'machine=0')
def test_application_hardware(self): fake_client = fake_juju_client() with patch('assess_constraints.application_machines', autospec=True, return_value=['7']) as am_mock: with patch('assess_constraints.machine_hardware', autospec=True, return_value='test') as mh_mock: data = application_hardware(fake_client, 'fakejob') self.assertEqual('test', data) am_mock.assert_called_once_with(fake_client, 'fakejob') mh_mock.assert_called_once_with(fake_client, '7')
def test_migrate_model_to_controller_admin(self): source_client, dest_client = self.make_clients() mt_client = fake_juju_client(source_client.env) mt_client._backend.controller_state.add_model('model-a') with patch.object(dest_client, 'clone', return_value=mt_client): with patch.object(source_client, 'controller_juju') as cj_mock: with patch('assess_model_migration.wait_for_model'): amm.migrate_model_to_controller( source_client, dest_client, include_user_name=True) cj_mock.assert_called_once_with('migrate', ('me/model-a', 'model-a'))