index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
24,854
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/scenarios/nova/hypervisors.py
|
# Copyright 2015 Cisco Systems Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.task import validation
from rally_openstack.common import consts
from rally_openstack.task import scenario
from rally_openstack.task.scenarios.nova import utils
"""Scenarios for Nova hypervisors."""
@validation.add("required_services", services=[consts.Service.NOVA])
@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(name="NovaHypervisors.list_hypervisors",
platform="openstack")
class ListHypervisors(utils.NovaScenario):
def run(self, detailed=True):
"""List hypervisors.
Measure the "nova hypervisor-list" command performance.
:param detailed: True if the hypervisor listing should contain
detailed information about all of them
"""
self._list_hypervisors(detailed)
@validation.add("required_services", services=[consts.Service.NOVA])
@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(name="NovaHypervisors.list_and_get_hypervisors",
platform="openstack")
class ListAndGetHypervisors(utils.NovaScenario):
def run(self, detailed=True):
"""List and Get hypervisors.
The scenario first lists all hypervisors, then get detailed information
of the listed hypervisors in turn.
Measure the "nova hypervisor-show" command performance.
:param detailed: True if the hypervisor listing should contain
detailed information about all of them
"""
hypervisors = self._list_hypervisors(detailed)
for hypervisor in hypervisors:
self._get_hypervisor(hypervisor)
@validation.add("required_services", services=[consts.Service.NOVA])
@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(name="NovaHypervisors.statistics_hypervisors",
platform="openstack")
class StatisticsHypervisors(utils.NovaScenario):
def run(self):
"""Get hypervisor statistics over all compute nodes.
Measure the "nova hypervisor-stats" command performance.
"""
self._statistics_hypervisors()
@validation.add("required_services", services=[consts.Service.NOVA])
@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(name="NovaHypervisors.list_and_get_uptime_hypervisors",
platform="openstack")
class ListAndGetUptimeHypervisors(utils.NovaScenario):
def run(self, detailed=True):
"""List hypervisors,then display the uptime of it.
The scenario first list all hypervisors,then display
the uptime of the listed hypervisors in turn.
Measure the "nova hypervisor-uptime" command performance.
:param detailed: True if the hypervisor listing should contain
detailed information about all of them
"""
hypervisors = self._list_hypervisors(detailed)
for hypervisor in hypervisors:
if hypervisor.state == "up":
self._uptime_hypervisor(hypervisor)
@validation.add("required_services", services=[consts.Service.NOVA])
@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(name="NovaHypervisors.list_and_search_hypervisors",
platform="openstack")
class ListAndSearchHypervisors(utils.NovaScenario):
def run(self, detailed=True):
"""List all servers belonging to specific hypervisor.
The scenario first list all hypervisors,then find its hostname,
then list all servers belonging to the hypervisor
Measure the "nova hypervisor-servers <hostname>" command performance.
:param detailed: True if the hypervisor listing should contain
detailed information about all of them
"""
hypervisors = self._list_hypervisors(detailed)
for hypervisor in hypervisors:
self._search_hypervisors(hypervisor.hypervisor_hostname)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,855
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/common/cfg/heat.py
|
# Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.common import cfg
OPTS = {"openstack": [
cfg.FloatOpt("heat_stack_create_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time(in sec) to sleep after creating a resource before "
"polling for it status."),
cfg.FloatOpt("heat_stack_create_timeout",
default=3600.0,
deprecated_group="benchmark",
help="Time(in sec) to wait for heat stack to be created."),
cfg.FloatOpt("heat_stack_create_poll_interval",
default=1.0,
deprecated_group="benchmark",
help="Time interval(in sec) between checks when waiting for "
"stack creation."),
cfg.FloatOpt("heat_stack_delete_timeout",
default=3600.0,
deprecated_group="benchmark",
help="Time(in sec) to wait for heat stack to be deleted."),
cfg.FloatOpt("heat_stack_delete_poll_interval",
default=1.0,
deprecated_group="benchmark",
help="Time interval(in sec) between checks when waiting for "
"stack deletion."),
cfg.FloatOpt("heat_stack_check_timeout",
default=3600.0,
deprecated_group="benchmark",
help="Time(in sec) to wait for stack to be checked."),
cfg.FloatOpt("heat_stack_check_poll_interval",
default=1.0,
deprecated_group="benchmark",
help="Time interval(in sec) between checks when waiting for "
"stack checking."),
cfg.FloatOpt("heat_stack_update_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time(in sec) to sleep after updating a resource before "
"polling for it status."),
cfg.FloatOpt("heat_stack_update_timeout",
default=3600.0,
deprecated_group="benchmark",
help="Time(in sec) to wait for stack to be updated."),
cfg.FloatOpt("heat_stack_update_poll_interval",
default=1.0,
deprecated_group="benchmark",
help="Time interval(in sec) between checks when waiting for "
"stack update."),
cfg.FloatOpt("heat_stack_suspend_timeout",
default=3600.0,
deprecated_group="benchmark",
help="Time(in sec) to wait for stack to be suspended."),
cfg.FloatOpt("heat_stack_suspend_poll_interval",
default=1.0,
deprecated_group="benchmark",
help="Time interval(in sec) between checks when waiting for "
"stack suspend."),
cfg.FloatOpt("heat_stack_resume_timeout",
default=3600.0,
deprecated_group="benchmark",
help="Time(in sec) to wait for stack to be resumed."),
cfg.FloatOpt("heat_stack_resume_poll_interval",
default=1.0,
deprecated_group="benchmark",
help="Time interval(in sec) between checks when waiting for "
"stack resume."),
cfg.FloatOpt("heat_stack_snapshot_timeout",
default=3600.0,
deprecated_group="benchmark",
help="Time(in sec) to wait for stack snapshot to "
"be created."),
cfg.FloatOpt("heat_stack_snapshot_poll_interval",
default=1.0,
deprecated_group="benchmark",
help="Time interval(in sec) between checks when waiting for "
"stack snapshot to be created."),
cfg.FloatOpt("heat_stack_restore_timeout",
default=3600.0,
deprecated_group="benchmark",
help="Time(in sec) to wait for stack to be restored from "
"snapshot."),
cfg.FloatOpt("heat_stack_restore_poll_interval",
default=1.0,
deprecated_group="benchmark",
help="Time interval(in sec) between checks when waiting for "
"stack to be restored."),
cfg.FloatOpt("heat_stack_scale_timeout",
default=3600.0,
deprecated_group="benchmark",
help="Time (in sec) to wait for stack to scale up or down."),
cfg.FloatOpt("heat_stack_scale_poll_interval",
default=1.0,
deprecated_group="benchmark",
help="Time interval (in sec) between checks when waiting for "
"a stack to scale up or down.")
]}
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,856
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/murano/test_packages.py
|
# Copyright 2015: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally_openstack.task.scenarios.murano import packages
from tests.unit import test
MURANO_SCENARIO = ("rally_openstack.task.scenarios.murano."
"packages.MuranoPackages")
class MuranoPackagesTestCase(test.TestCase):
def setUp(self):
super(MuranoPackagesTestCase, self).setUp()
self.mock_remove = mock.patch("os.remove")
self.mock_remove.start()
def tearDown(self):
super(MuranoPackagesTestCase, self).tearDown()
self.mock_remove.stop()
def mock_modules(self, scenario):
scenario._import_package = mock.Mock()
scenario._zip_package = mock.Mock()
scenario._list_packages = mock.Mock()
scenario._delete_package = mock.Mock()
scenario._update_package = mock.Mock()
scenario._filter_applications = mock.Mock()
def test_make_zip_import_and_list_packages(self):
scenario = packages.ImportAndListPackages()
self.mock_modules(scenario)
scenario.run("foo_package.zip")
scenario._import_package.assert_called_once_with(
scenario._zip_package.return_value)
scenario._zip_package.assert_called_once_with("foo_package.zip")
scenario._list_packages.assert_called_once_with(
include_disabled=False)
def test_import_and_delete_package(self):
scenario = packages.ImportAndDeletePackage()
self.mock_modules(scenario)
fake_package = mock.Mock()
scenario._import_package.return_value = fake_package
scenario.run("foo_package.zip")
scenario._import_package.assert_called_once_with(
scenario._zip_package.return_value)
scenario._delete_package.assert_called_once_with(fake_package)
def test_package_lifecycle(self):
scenario = packages.PackageLifecycle()
self.mock_modules(scenario)
fake_package = mock.Mock()
scenario._import_package.return_value = fake_package
scenario.run("foo_package.zip", {"category": "Web"}, "add")
scenario._import_package.assert_called_once_with(
scenario._zip_package.return_value)
scenario._update_package.assert_called_once_with(
fake_package, {"category": "Web"}, "add")
scenario._delete_package.assert_called_once_with(fake_package)
def test_import_and_filter_applications(self):
scenario = packages.ImportAndFilterApplications()
self.mock_modules(scenario)
fake_package = mock.Mock()
scenario._import_package.return_value = fake_package
scenario.run("foo_package.zip", {"category": "Web"})
scenario._import_package.assert_called_once_with(
scenario._zip_package.return_value)
scenario._filter_applications.assert_called_once_with(
{"category": "Web"}
)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,857
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/sahara/test_clusters.py
|
# Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally_openstack.task.scenarios.sahara import clusters
from tests.unit import test
BASE = "rally_openstack.task.scenarios.sahara.clusters"
class SaharaClustersTestCase(test.ScenarioTestCase):
@mock.patch("%s.CreateAndDeleteCluster._delete_cluster" % BASE)
@mock.patch("%s.CreateAndDeleteCluster._launch_cluster" % BASE,
return_value=mock.MagicMock(id=42))
def test_create_and_delete_cluster(self,
mock_launch_cluster,
mock_delete_cluster):
scenario = clusters.CreateAndDeleteCluster(self.context)
scenario.context = {
"tenant": {
"sahara": {
"image": "test_image",
}
}
}
scenario.run(master_flavor="test_flavor_m",
worker_flavor="test_flavor_w",
workers_count=5,
plugin_name="test_plugin",
hadoop_version="test_version")
mock_launch_cluster.assert_called_once_with(
flavor_id=None,
master_flavor_id="test_flavor_m",
worker_flavor_id="test_flavor_w",
image_id="test_image",
workers_count=5,
plugin_name="test_plugin",
hadoop_version="test_version",
floating_ip_pool=None,
volumes_per_node=None,
volumes_size=None,
auto_security_group=None,
security_groups=None,
node_configs=None,
cluster_configs=None,
enable_anti_affinity=False,
enable_proxy=False,
use_autoconfig=True)
mock_delete_cluster.assert_called_once_with(
mock_launch_cluster.return_value)
@mock.patch("%s.CreateAndDeleteCluster._delete_cluster" % BASE)
@mock.patch("%s.CreateAndDeleteCluster._launch_cluster" % BASE,
return_value=mock.MagicMock(id=42))
def test_create_and_delete_cluster_deprecated_flavor(self,
mock_launch_cluster,
mock_delete_cluster):
scenario = clusters.CreateAndDeleteCluster(self.context)
scenario.context = {
"tenant": {
"sahara": {
"image": "test_image",
}
}
}
scenario.run(flavor="test_deprecated_arg",
master_flavor=None,
worker_flavor=None,
workers_count=5,
plugin_name="test_plugin",
hadoop_version="test_version")
mock_launch_cluster.assert_called_once_with(
flavor_id="test_deprecated_arg",
master_flavor_id=None,
worker_flavor_id=None,
image_id="test_image",
workers_count=5,
plugin_name="test_plugin",
hadoop_version="test_version",
floating_ip_pool=None,
volumes_per_node=None,
volumes_size=None,
auto_security_group=None,
security_groups=None,
node_configs=None,
cluster_configs=None,
enable_anti_affinity=False,
enable_proxy=False,
use_autoconfig=True)
mock_delete_cluster.assert_called_once_with(
mock_launch_cluster.return_value)
@mock.patch("%s.CreateScaleDeleteCluster._delete_cluster" % BASE)
@mock.patch("%s.CreateScaleDeleteCluster._scale_cluster" % BASE)
@mock.patch("%s.CreateScaleDeleteCluster._launch_cluster" % BASE,
return_value=mock.MagicMock(id=42))
def test_create_scale_delete_cluster(self,
mock_launch_cluster,
mock_scale_cluster,
mock_delete_cluster):
self.clients("sahara").clusters.get.return_value = mock.MagicMock(
id=42, status="active"
)
scenario = clusters.CreateScaleDeleteCluster(self.context)
scenario.context = {
"tenant": {
"sahara": {
"image": "test_image",
}
}
}
scenario.run(master_flavor="test_flavor_m",
worker_flavor="test_flavor_w",
workers_count=5,
deltas=[1, -1],
plugin_name="test_plugin",
hadoop_version="test_version")
mock_launch_cluster.assert_called_once_with(
flavor_id=None,
master_flavor_id="test_flavor_m",
worker_flavor_id="test_flavor_w",
image_id="test_image",
workers_count=5,
plugin_name="test_plugin",
hadoop_version="test_version",
floating_ip_pool=None,
volumes_per_node=None,
volumes_size=None,
auto_security_group=None,
security_groups=None,
node_configs=None,
cluster_configs=None,
enable_anti_affinity=False,
enable_proxy=False,
use_autoconfig=True)
mock_scale_cluster.assert_has_calls([
mock.call(
self.clients("sahara").clusters.get.return_value,
1),
mock.call(
self.clients("sahara").clusters.get.return_value,
-1),
])
mock_delete_cluster.assert_called_once_with(
self.clients("sahara").clusters.get.return_value)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,858
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/contexts/nova/test_keypairs.py
|
# Copyright 2014: Rackspace UK
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally_openstack.task.contexts.nova import keypairs
from tests.unit import test
CTX = "rally_openstack.task.contexts.nova"
class KeyPairContextTestCase(test.TestCase):
def setUp(self):
super(KeyPairContextTestCase, self).setUp()
self.users = 2
task = {"uuid": "foo_task_id"}
self.ctx_with_keys = {
"users": [
{
"keypair": {
"id": "key_id_1",
"key": "key_1",
"name": "key_name_1"
},
"credential": "credential_1"
},
{
"keypair": {
"id": "key_id_2",
"key": "key_2",
"name": "key_name_2"
},
"credential": "credential_2"
},
],
"task": task
}
self.ctx_without_keys = {
"users": [{"credential": "credential_1"},
{"credential": "credential_2"}],
"task": task
}
def test_keypair_setup(self):
keypair_ctx = keypairs.Keypair(self.ctx_without_keys)
keypair_ctx._generate_keypair = mock.Mock(side_effect=[
{"id": "key_id_1", "key": "key_1", "name": "key_name_1"},
{"id": "key_id_2", "key": "key_2", "name": "key_name_2"},
])
keypair_ctx.setup()
self.assertEqual(keypair_ctx.context, self.ctx_with_keys)
keypair_ctx._generate_keypair.assert_has_calls(
[mock.call("credential_1"), mock.call("credential_2")])
@mock.patch("%s.keypairs.resource_manager.cleanup" % CTX)
def test_keypair_cleanup(self, mock_cleanup):
keypair_ctx = keypairs.Keypair(self.ctx_with_keys)
keypair_ctx.cleanup()
mock_cleanup.assert_called_once_with(
names=["nova.keypairs"],
users=self.ctx_with_keys["users"],
superclass=keypairs.Keypair,
task_id=self.ctx_with_keys["task"]["uuid"])
@mock.patch("rally_openstack.common.osclients.Clients")
def test_keypair_generate(self, mock_clients):
mock_keypairs = mock_clients.return_value.nova.return_value.keypairs
mock_keypair = mock_keypairs.create.return_value
mock_keypair.public_key = "public_key"
mock_keypair.private_key = "private_key"
mock_keypair.id = "key_id"
keypair_ctx = keypairs.Keypair(self.ctx_without_keys)
keypair_ctx.generate_random_name = mock.Mock()
key = keypair_ctx._generate_keypair("credential")
self.assertEqual({
"id": "key_id",
"name": keypair_ctx.generate_random_name.return_value,
"private": "private_key",
"public": "public_key"
}, key)
mock_clients.assert_has_calls([
mock.call().nova().keypairs.create(
keypair_ctx.generate_random_name.return_value),
])
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,859
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/verification/tempest/manager.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import re
import shutil
import subprocess
import yaml
from rally import exceptions
from rally.plugins.verification import testr
from rally.verification import manager
from rally.verification import utils
from rally_openstack.verification.tempest import config
from rally_openstack.verification.tempest import consts
AVAILABLE_SETS = (list(consts.TempestTestSets)
+ list(consts.TempestApiTestSets)
+ list(consts.TempestScenarioTestSets))
@manager.configure(name="tempest", platform="openstack",
default_repo="https://opendev.org/openstack/tempest",
context={"tempest": {}, "testr": {}})
class TempestManager(testr.TestrLauncher):
"""Tempest verifier.
**Description**:
Quote from official documentation:
This is a set of integration tests to be run against a live OpenStack
cluster. Tempest has batteries of tests for OpenStack API validation,
Scenarios, and other specific tests useful in validating an OpenStack
deployment.
Rally supports features listed below:
* *cloning Tempest*: repository and version can be specified
* *installation*: system-wide with checking existence of required
packages or in virtual environment
* *configuration*: options are discovered via OpenStack API, but you can
override them if you need
* *running*: pre-creating all required resources(i.e images, tenants,
etc), prepare arguments, launching Tempest, live-progress output
* *results*: all verifications are stored in db, you can built reports,
compare verification at whatever you want time.
Appeared in Rally 0.8.0 *(actually, it appeared long time ago with first
revision of Verification Component, but 0.8.0 is mentioned since it is
first release after Verification Component redesign)*
"""
RUN_ARGS = {"set": "Name of predefined set of tests. Known names: %s"
% ", ".join(AVAILABLE_SETS)}
@property
def run_environ(self):
env = super(TempestManager, self).run_environ
env["TEMPEST_CONFIG_DIR"] = os.path.dirname(self.configfile)
env["TEMPEST_CONFIG"] = os.path.basename(self.configfile)
# TODO(andreykurilin): move it to Testr base class
env["OS_TEST_PATH"] = os.path.join(self.repo_dir,
"tempest/test_discover")
return env
@property
def configfile(self):
return os.path.join(self.home_dir, "tempest.conf")
def validate_args(self, args):
"""Validate given arguments."""
super(TempestManager, self).validate_args(args)
if args.get("pattern"):
pattern = args["pattern"].split("=", 1)
if len(pattern) == 1:
pass # it is just a regex
elif pattern[0] == "set":
if pattern[1] not in AVAILABLE_SETS:
raise exceptions.ValidationError(
"Test set '%s' not found in available "
"Tempest test sets. Available sets are '%s'."
% (pattern[1], "', '".join(AVAILABLE_SETS)))
else:
raise exceptions.ValidationError(
"'pattern' argument should be a regexp or set name "
"(format: 'tempest.api.identity.v3', 'set=smoke').")
def configure(self, extra_options=None):
"""Configure Tempest."""
utils.create_dir(self.home_dir)
tcm = config.TempestConfigfileManager(self.verifier.env)
return tcm.create(self.configfile, extra_options)
def is_configured(self):
"""Check whether Tempest is configured or not."""
return os.path.exists(self.configfile)
def get_configuration(self):
"""Get Tempest configuration."""
with open(self.configfile) as f:
return f.read()
def extend_configuration(self, extra_options):
"""Extend Tempest configuration with extra options."""
return utils.extend_configfile(extra_options, self.configfile)
def override_configuration(self, new_configuration):
"""Override Tempest configuration by new configuration."""
with open(self.configfile, "w") as f:
f.write(new_configuration)
def install_extension(self, source, version=None, extra_settings=None):
"""Install a Tempest plugin."""
if extra_settings:
raise NotImplementedError(
"'%s' verifiers don't support extra installation settings "
"for extensions." % self.get_name())
version = version or "master"
egg = re.sub(r"\.git$", "", os.path.basename(source.strip("/")))
full_source = "git+{0}@{1}#egg={2}".format(source, version, egg)
# NOTE(ylobankov): Use 'develop mode' installation to provide an
# ability to advanced users to change tests or
# develop new ones in verifier repo on the fly.
cmd = ["pip", "install",
"--src", os.path.join(self.base_dir, "extensions"),
"-e", full_source]
if self.verifier.system_wide:
cmd.insert(2, "--no-deps")
utils.check_output(cmd, cwd=self.base_dir, env=self.environ)
# Very often Tempest plugins are inside projects and requirements
# for plugins are listed in the test-requirements.txt file.
test_reqs_path = os.path.join(self.base_dir, "extensions",
egg, "test-requirements.txt")
if os.path.exists(test_reqs_path):
if not self.verifier.system_wide:
utils.check_output(["pip", "install", "-r", test_reqs_path],
cwd=self.base_dir, env=self.environ)
else:
self.check_system_wide(reqs_file_path=test_reqs_path)
def list_extensions(self):
"""List all installed Tempest plugins."""
# TODO(andreykurilin): find a better way to list tempest plugins
cmd = ("from tempest.test_discover import plugins; "
"plugins_manager = plugins.TempestTestPluginManager(); "
"plugins_map = plugins_manager.get_plugin_load_tests_tuple(); "
"plugins_list = ["
" {'name': p.name, "
" 'entry_point': p.entry_point_target, "
" 'location': plugins_map[p.name][1]} "
" for p in plugins_manager.ext_plugins.extensions]; "
"print(plugins_list)")
try:
output = utils.check_output(["python", "-c", cmd],
cwd=self.base_dir, env=self.environ,
debug_output=False).strip()
except subprocess.CalledProcessError:
raise exceptions.RallyException(
"Cannot list installed Tempest plugins for verifier %s." %
self.verifier)
return yaml.safe_load(output)
def uninstall_extension(self, name):
"""Uninstall a Tempest plugin."""
for ext in self.list_extensions():
if ext["name"] == name and os.path.exists(ext["location"]):
shutil.rmtree(ext["location"])
break
else:
raise exceptions.RallyException(
"There is no Tempest plugin with name '%s'. "
"Are you sure that it was installed?" % name)
def list_tests(self, pattern=""):
"""List all Tempest tests."""
if pattern:
pattern = self._transform_pattern(pattern)
return super(TempestManager, self).list_tests(pattern)
def prepare_run_args(self, run_args):
"""Prepare 'run_args' for testr context."""
if run_args.get("pattern"):
run_args["pattern"] = self._transform_pattern(run_args["pattern"])
return run_args
@staticmethod
def _transform_pattern(pattern):
"""Transform pattern into Tempest-specific pattern."""
parsed_pattern = pattern.split("=", 1)
if len(parsed_pattern) == 2:
if parsed_pattern[0] == "set":
if parsed_pattern[1] in consts.TempestTestSets:
return "smoke" if parsed_pattern[1] == "smoke" else ""
elif parsed_pattern[1] in consts.TempestApiTestSets:
return "tempest.api.%s" % parsed_pattern[1]
else:
return "tempest.%s" % parsed_pattern[1]
return pattern # it is just a regex
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,860
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/common/services/heat/test_main.py
|
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally_openstack.common.services.heat import main
from tests.unit import test
class Stack(main.Stack):
def __init__(self):
self.scenario = mock.Mock()
class StackTestCase(test.ScenarioTestCase):
@mock.patch("rally_openstack.common.services.heat.main.open",
create=True)
def test___init__(self, mock_open):
reads = [mock.Mock(), mock.Mock()]
reads[0].read.return_value = "template_contents"
reads[1].read.return_value = "file1_contents"
mock_open.side_effect = reads
stack = main.Stack("scenario", "task", "template",
parameters="parameters",
files={"f1_name": "f1_path"})
self.assertEqual("template_contents", stack.template)
self.assertEqual({"f1_name": "file1_contents"}, stack.files)
self.assertEqual([mock.call("template"), mock.call("f1_path")],
mock_open.mock_calls)
reads[0].read.assert_called_once_with()
reads[1].read.assert_called_once_with()
@mock.patch("rally_openstack.common.services.heat.main.utils")
def test__wait(self, mock_utils):
fake_stack = mock.Mock()
stack = Stack()
stack.stack = fake_stack = mock.Mock()
stack._wait(["ready_statuses"], ["failure_statuses"])
mock_utils.wait_for_status.assert_called_once_with(
fake_stack, check_interval=1.0,
ready_statuses=["ready_statuses"],
failure_statuses=["failure_statuses"],
timeout=3600.0,
update_resource=mock_utils.get_from_manager())
@mock.patch("rally.task.atomic")
@mock.patch("rally_openstack.common.services.heat.main.open")
@mock.patch("rally_openstack.common.services.heat.main.Stack._wait")
def test_create(self, mock_stack__wait, mock_open, mock_task_atomic):
mock_scenario = mock.MagicMock(_atomic_actions=[])
mock_scenario.generate_random_name.return_value = "fake_name"
mock_open().read.return_value = "fake_content"
mock_new_stack = {
"stack": {
"id": "fake_id"
}
}
mock_scenario.clients("heat").stacks.create.return_value = (
mock_new_stack)
stack = main.Stack(
scenario=mock_scenario, task=mock.Mock(),
template=mock.Mock(), files={}
)
stack.create()
mock_scenario.clients("heat").stacks.create.assert_called_once_with(
files={}, parameters=None, stack_name="fake_name",
template="fake_content"
)
mock_scenario.clients("heat").stacks.get.assert_called_once_with(
"fake_id")
mock_stack__wait.assert_called_once_with(["CREATE_COMPLETE"],
["CREATE_FAILED"])
@mock.patch("rally.task.atomic")
@mock.patch("rally_openstack.common.services.heat.main.open")
@mock.patch("rally_openstack.common.services.heat.main.Stack._wait")
def test_update(self, mock_stack__wait, mock_open, mock_task_atomic):
mock_scenario = mock.MagicMock(
stack_id="fake_id", _atomic_actions=[])
mock_parameters = mock.Mock()
mock_open().read.return_value = "fake_content"
stack = main.Stack(
scenario=mock_scenario, task=mock.Mock(),
template=None, files={}, parameters=mock_parameters
)
stack.stack_id = "fake_id"
stack.parameters = mock_parameters
stack.update({"foo": "bar"})
mock_scenario.clients("heat").stacks.update.assert_called_once_with(
"fake_id", files={}, template="fake_content",
parameters=mock_parameters
)
mock_stack__wait.assert_called_once_with(["UPDATE_COMPLETE"],
["UPDATE_FAILED"])
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,861
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/keystone/test_basic.py
|
# Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
import ddt
from rally import exceptions
from rally_openstack.task.scenarios.keystone import basic
from tests.unit import test
@ddt.ddt
class KeystoneBasicTestCase(test.ScenarioTestCase):
def get_test_context(self):
context = super(KeystoneBasicTestCase, self).get_test_context()
context.update({
"admin": {
"id": "fake_user_id",
"credential": mock.MagicMock()
},
"user": {
"id": "fake_user_id",
"credential": mock.MagicMock()
},
"tenant": {"id": "fake_tenant_id",
"name": "fake_tenant_name"}
})
return context
def setUp(self):
super(KeystoneBasicTestCase, self).setUp()
patch = mock.patch(
"rally_openstack.common.services.identity.identity.Identity")
self.addCleanup(patch.stop)
self.mock_identity = patch.start()
def test_create_user(self):
scenario = basic.CreateUser(self.context)
scenario.run(password="tttt", project_id="id")
self.mock_identity.return_value.create_user.assert_called_once_with(
password="tttt", project_id="id")
def test_create_delete_user(self):
identity_service = self.mock_identity.return_value
fake_email = "abcd"
fake_user = identity_service.create_user.return_value
scenario = basic.CreateDeleteUser(self.context)
scenario.run(email=fake_email, enabled=True)
identity_service.create_user.assert_called_once_with(
email=fake_email, enabled=True)
identity_service.delete_user.assert_called_once_with(fake_user.id)
def test_create_user_set_enabled_and_delete(self):
identity_service = self.mock_identity.return_value
scenario = basic.CreateUserSetEnabledAndDelete(self.context)
fake_email = "abcd"
fake_user = identity_service.create_user.return_value
scenario.run(enabled=True, email=fake_email)
identity_service.create_user.assert_called_once_with(
email=fake_email, enabled=True)
identity_service.update_user.assert_called_once_with(
fake_user.id, enabled=False)
identity_service.delete_user.assert_called_once_with(fake_user.id)
def test_user_authenticate_and_validate_token(self):
identity_service = self.mock_identity.return_value
scenario = basic.AuthenticateUserAndValidateToken(self.context)
fake_token = identity_service.fetch_token.return_value
scenario.run()
identity_service.fetch_token.assert_called_once_with()
identity_service.validate_token.assert_called_once_with(fake_token)
def test_create_tenant(self):
scenario = basic.CreateTenant(self.context)
scenario.run(enabled=True)
self.mock_identity.return_value.create_project.assert_called_once_with(
enabled=True)
def test_create_tenant_with_users(self):
identity_service = self.mock_identity.return_value
fake_project = identity_service.create_project.return_value
number_of_users = 1
scenario = basic.CreateTenantWithUsers(self.context)
scenario.run(users_per_tenant=number_of_users, enabled=True)
identity_service.create_project.assert_called_once_with(enabled=True)
identity_service.create_users.assert_called_once_with(
fake_project.id, number_of_users=number_of_users)
def test_create_and_list_users(self):
scenario = basic.CreateAndListUsers(self.context)
passwd = "tttt"
project_id = "id"
scenario.run(password=passwd, project_id=project_id)
self.mock_identity.return_value.create_user.assert_called_once_with(
password=passwd, project_id=project_id)
self.mock_identity.return_value.list_users.assert_called_once_with()
def test_create_and_list_tenants(self):
identity_service = self.mock_identity.return_value
scenario = basic.CreateAndListTenants(self.context)
scenario.run(enabled=True)
identity_service.create_project.assert_called_once_with(enabled=True)
identity_service.list_projects.assert_called_once_with()
def test_assign_and_remove_user_role(self):
fake_tenant = self.context["tenant"]["id"]
fake_user = self.context["user"]["id"]
fake_role = mock.MagicMock()
self.mock_identity.return_value.create_role.return_value = fake_role
scenario = basic.AddAndRemoveUserRole(self.context)
scenario.run()
self.mock_identity.return_value.create_role.assert_called_once_with()
self.mock_identity.return_value.add_role.assert_called_once_with(
role_id=fake_role.id, user_id=fake_user, project_id=fake_tenant)
self.mock_identity.return_value.revoke_role.assert_called_once_with(
fake_role.id, user_id=fake_user, project_id=fake_tenant)
def test_create_and_delete_role(self):
fake_role = mock.MagicMock()
self.mock_identity.return_value.create_role.return_value = fake_role
scenario = basic.CreateAndDeleteRole(self.context)
scenario.run()
self.mock_identity.return_value.create_role.assert_called_once_with()
self.mock_identity.return_value.delete_role.assert_called_once_with(
fake_role.id)
def test_create_and_get_role(self):
fake_role = mock.MagicMock()
self.mock_identity.return_value.create_role.return_value = fake_role
scenario = basic.CreateAndGetRole(self.context)
scenario.run()
self.mock_identity.return_value.create_role.assert_called_once_with()
self.mock_identity.return_value.get_role.assert_called_once_with(
fake_role.id)
def test_create_and_list_user_roles(self):
scenario = basic.CreateAddAndListUserRoles(self.context)
fake_tenant = self.context["tenant"]["id"]
fake_user = self.context["user"]["id"]
fake_role = mock.MagicMock()
self.mock_identity.return_value.create_role.return_value = fake_role
scenario.run()
self.mock_identity.return_value.create_role.assert_called_once_with()
self.mock_identity.return_value.add_role.assert_called_once_with(
user_id=fake_user, role_id=fake_role.id, project_id=fake_tenant)
self.mock_identity.return_value.list_roles.assert_called_once_with(
user_id=fake_user, project_id=fake_tenant)
def test_create_and_list_roles(self):
# Positive case
scenario = basic.CreateAddListRoles(self.context)
create_kwargs = {"fakewargs": "name"}
list_kwargs = {"fakewargs": "f"}
self.mock_identity.return_value.create_role = mock.Mock(
return_value="role1")
self.mock_identity.return_value.list_roles = mock.Mock(
return_value=("role1", "role2"))
scenario.run(create_role_kwargs=create_kwargs,
list_role_kwargs=list_kwargs)
self.mock_identity.return_value.create_role.assert_called_once_with(
**create_kwargs)
self.mock_identity.return_value.list_roles.assert_called_once_with(
**list_kwargs)
# Negative case 1: role isn't created
self.mock_identity.return_value.create_role.return_value = None
self.assertRaises(exceptions.RallyAssertionError,
scenario.run, create_role_kwargs=create_kwargs,
list_role_kwargs=list_kwargs)
self.mock_identity.return_value.create_role.assert_called_with(
**create_kwargs)
# Negative case 2: role was created but included into list
self.mock_identity.return_value.create_role.return_value = "role3"
self.assertRaises(exceptions.RallyAssertionError,
scenario.run, create_role_kwargs=create_kwargs,
list_role_kwargs=list_kwargs)
self.mock_identity.return_value.create_role.assert_called_with(
**create_kwargs)
self.mock_identity.return_value.list_roles.assert_called_with(
**list_kwargs)
@ddt.data(None, "keystone", "fooservice")
def test_get_entities(self, service_name):
identity_service = self.mock_identity.return_value
fake_project = identity_service.create_project.return_value
fake_user = identity_service.create_user.return_value
fake_role = identity_service.create_role.return_value
fake_service = identity_service.create_service.return_value
scenario = basic.GetEntities(self.context)
scenario.run(service_name)
identity_service.create_project.assert_called_once_with()
identity_service.create_user.assert_called_once_with(
project_id=fake_project.id)
identity_service.create_role.assert_called_once_with()
identity_service.get_project.assert_called_once_with(fake_project.id)
identity_service.get_user.assert_called_once_with(fake_user.id)
identity_service.get_role.assert_called_once_with(fake_role.id)
if service_name is None:
identity_service.create_service.assert_called_once_with()
self.assertFalse(identity_service.get_service_by_name.called)
identity_service.get_service.assert_called_once_with(
fake_service.id)
else:
identity_service.get_service_by_name.assert_called_once_with(
service_name)
self.assertFalse(identity_service.create_service.called)
identity_service.get_service.assert_called_once_with(
identity_service.get_service_by_name.return_value.id)
def test_create_and_delete_service(self):
identity_service = self.mock_identity.return_value
scenario = basic.CreateAndDeleteService(self.context)
service_type = "test_service_type"
description = "test_description"
fake_service = identity_service.create_service.return_value
scenario.run(service_type=service_type, description=description)
identity_service.create_service.assert_called_once_with(
service_type=service_type, description=description)
identity_service.delete_service.assert_called_once_with(
fake_service.id)
def test_create_update_and_delete_tenant(self):
identity_service = self.mock_identity.return_value
scenario = basic.CreateUpdateAndDeleteTenant(self.context)
gen_name = mock.MagicMock()
basic.CreateUpdateAndDeleteTenant.generate_random_name = gen_name
fake_project = identity_service.create_project.return_value
scenario.run()
identity_service.create_project.assert_called_once_with()
identity_service.update_project.assert_called_once_with(
fake_project.id, description=gen_name.return_value,
name=gen_name.return_value)
identity_service.delete_project(fake_project.id)
def test_create_user_update_password(self):
identity_service = self.mock_identity.return_value
scenario = basic.CreateUserUpdatePassword(self.context)
fake_password = "pswd"
fake_user = identity_service.create_user.return_value
scenario.generate_random_name = mock.MagicMock(
return_value=fake_password)
scenario.run()
scenario.generate_random_name.assert_called_once_with()
identity_service.create_user.assert_called_once_with()
identity_service.update_user.assert_called_once_with(
fake_user.id, password=fake_password)
def test_create_and_update_user(self):
identity_service = self.mock_identity.return_value
scenario = basic.CreateAndUpdateUser(self.context)
scenario.admin_clients("keystone").users.get = mock.MagicMock()
fake_user = identity_service.create_user.return_value
create_args = {"fakearg1": "f"}
update_args = {"fakearg1": "fakearg"}
setattr(self.admin_clients("keystone").users.get.return_value,
"fakearg1", "fakearg")
scenario.run(create_user_kwargs=create_args,
update_user_kwargs=update_args)
identity_service.create_user.assert_called_once_with(**create_args)
identity_service.update_user.assert_called_once_with(
fake_user.id, **update_args)
def test_create_and_list_services(self):
identity_service = self.mock_identity.return_value
scenario = basic.CreateAndListServices(self.context)
service_type = "test_service_type"
description = "test_description"
scenario.run(service_type=service_type, description=description)
identity_service.create_service.assert_called_once_with(
service_type=service_type, description=description)
identity_service.list_services.assert_called_once_with()
def test_create_and_list_ec2credentials(self):
identity_service = self.mock_identity.return_value
scenario = basic.CreateAndListEc2Credentials(self.context)
scenario.run()
identity_service.create_ec2credentials.assert_called_once_with(
self.context["user"]["id"],
project_id=self.context["tenant"]["id"])
identity_service.list_ec2credentials.assert_called_with(
self.context["user"]["id"])
def test_create_and_delete_ec2credential(self):
identity_service = self.mock_identity.return_value
fake_creds = identity_service.create_ec2credentials.return_value
scenario = basic.CreateAndDeleteEc2Credential(self.context)
scenario.run()
identity_service.create_ec2credentials.assert_called_once_with(
self.context["user"]["id"],
project_id=self.context["tenant"]["id"])
identity_service.delete_ec2credential.assert_called_once_with(
self.context["user"]["id"], access=fake_creds.access)
def test_add_and_remove_user_role(self):
context = self.context
tenant_id = context["tenant"]["id"]
user_id = context["user"]["id"]
fake_role = mock.MagicMock()
self.mock_identity.return_value.create_role.return_value = fake_role
scenario = basic.AddAndRemoveUserRole(context)
scenario.run()
self.mock_identity.return_value.create_role.assert_called_once_with()
self.mock_identity.return_value.add_role.assert_called_once_with(
role_id=fake_role.id, user_id=user_id, project_id=tenant_id)
self.mock_identity.return_value.revoke_role.assert_called_once_with(
fake_role.id, user_id=user_id, project_id=tenant_id)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,862
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/senlin/test_clusters.py
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally_openstack.task.scenarios.senlin import clusters
from tests.unit import test
class SenlinClustersTestCase(test.ScenarioTestCase):
def test_create_and_delete_cluster(self):
mock_cluster = mock.Mock()
self.context["tenant"] = {"profile": "fake_profile_id"}
scenario = clusters.CreateAndDeleteCluster(self.context)
scenario._create_cluster = mock.Mock(return_value=mock_cluster)
scenario._delete_cluster = mock.Mock()
scenario.run(desired_capacity=1, min_size=0,
max_size=3, timeout=60, metadata={"k2": "v2"})
scenario._create_cluster.assert_called_once_with("fake_profile_id",
1, 0, 3, 60,
{"k2": "v2"})
scenario._delete_cluster.assert_called_once_with(mock_cluster)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,863
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/contexts/quotas/test_quotas.py
|
# Copyright 2014: Dassault Systemes
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
from unittest import mock
import ddt
from rally.common import logging
from rally.task import context
from rally_openstack.task.contexts.quotas import quotas
from tests.unit import test
QUOTAS_PATH = "rally_openstack.task.contexts.quotas"
@ddt.ddt
class QuotasTestCase(test.TestCase):
def setUp(self):
super(QuotasTestCase, self).setUp()
self.unlimited = -1
self.context = {
"config": {
},
"tenants": {
"t1": {"credential": mock.MagicMock()},
"t2": {"credential": mock.MagicMock()}},
"admin": {"credential": mock.MagicMock()},
"task": mock.MagicMock()
}
@ddt.data(("cinder", "backup_gigabytes"),
("cinder", "backups"),
("cinder", "gigabytes"),
("cinder", "snapshots"),
("cinder", "volumes"),
("manila", "gigabytes"),
("manila", "share_networks"),
("manila", "shares"),
("manila", "snapshot_gigabytes"),
("manila", "snapshots"),
("neutron", "floatingip"),
("neutron", "health_monitor"),
("neutron", "network"),
("neutron", "pool"),
("neutron", "port"),
("neutron", "router"),
("neutron", "security_group"),
("neutron", "security_group_rule"),
("neutron", "subnet"),
("neutron", "vip"),
("nova", "cores"),
("nova", "fixed_ips"),
("nova", "floating_ips"),
("nova", "injected_file_content_bytes"),
("nova", "injected_file_path_bytes"),
("nova", "injected_files"),
("nova", "instances"),
("nova", "key_pairs"),
("nova", "metadata_items"),
("nova", "ram"),
("nova", "security_group_rules"),
("nova", "security_groups"),
("nova", "server_group_members"),
("nova", "server_groups"))
@ddt.unpack
def test_validate(self, group, parameter):
configs = [
({group: {parameter: self.unlimited}}, True),
({group: {parameter: 0}}, True),
({group: {parameter: 10000}}, True),
({group: {parameter: 2.5}}, False),
({group: {parameter: "-1"}}, False),
({group: {parameter: -2}}, False),
]
for config, valid in configs:
results = context.Context.validate(
"quotas", None, None, config, vtype="syntax")
if valid:
self.assertEqual([], results)
else:
self.assertGreater(len(results), 0)
@mock.patch("%s.quotas.osclients.Clients" % QUOTAS_PATH)
@mock.patch("%s.cinder_quotas.CinderQuotas" % QUOTAS_PATH)
@ddt.data(True, False)
def test_cinder_quotas(self, ex_users, mock_cinder_quotas, mock_clients):
cinder_quo = mock_cinder_quotas.return_value
ctx = copy.deepcopy(self.context)
if ex_users:
ctx["existing_users"] = None
ctx["config"]["quotas"] = {
"cinder": {
"volumes": self.unlimited,
"snapshots": self.unlimited,
"gigabytes": self.unlimited
}
}
tenants = ctx["tenants"]
cinder_quotas = ctx["config"]["quotas"]["cinder"]
cinder_quo.get.return_value = cinder_quotas
with quotas.Quotas(ctx) as quotas_ctx:
quotas_ctx.setup()
if ex_users:
self.assertEqual([mock.call(tenant) for tenant in tenants],
cinder_quo.get.call_args_list)
self.assertEqual([mock.call(tenant, **cinder_quotas)
for tenant in tenants],
cinder_quo.update.call_args_list)
mock_cinder_quotas.reset_mock()
if ex_users:
self.assertEqual([mock.call(tenant, **cinder_quotas)
for tenant in tenants],
cinder_quo.update.call_args_list)
else:
self.assertEqual([mock.call(tenant) for tenant in tenants],
cinder_quo.delete.call_args_list)
@mock.patch("%s.quotas.osclients.Clients" % QUOTAS_PATH)
@mock.patch("%s.nova_quotas.NovaQuotas" % QUOTAS_PATH)
@ddt.data(True, False)
def test_nova_quotas(self, ex_users, mock_nova_quotas, mock_clients):
nova_quo = mock_nova_quotas.return_value
ctx = copy.deepcopy(self.context)
if ex_users:
ctx["existing_users"] = None
ctx["config"]["quotas"] = {
"nova": {
"instances": self.unlimited,
"cores": self.unlimited,
"ram": self.unlimited,
"floating-ips": self.unlimited,
"fixed-ips": self.unlimited,
"metadata_items": self.unlimited,
"injected_files": self.unlimited,
"injected_file_content_bytes": self.unlimited,
"injected_file_path_bytes": self.unlimited,
"key_pairs": self.unlimited,
"security_groups": self.unlimited,
"security_group_rules": self.unlimited,
}
}
tenants = ctx["tenants"]
nova_quotas = ctx["config"]["quotas"]["nova"]
nova_quo.get.return_value = nova_quotas
with quotas.Quotas(ctx) as quotas_ctx:
quotas_ctx.setup()
if ex_users:
self.assertEqual([mock.call(tenant) for tenant in tenants],
nova_quo.get.call_args_list)
self.assertEqual([mock.call(tenant, **nova_quotas)
for tenant in tenants],
nova_quo.update.call_args_list)
mock_nova_quotas.reset_mock()
if ex_users:
self.assertEqual([mock.call(tenant, **nova_quotas)
for tenant in tenants],
nova_quo.update.call_args_list)
else:
self.assertEqual([mock.call(tenant) for tenant in tenants],
nova_quo.delete.call_args_list)
@mock.patch("%s.quotas.osclients.Clients" % QUOTAS_PATH)
@mock.patch("%s.neutron_quotas.NeutronQuotas" % QUOTAS_PATH)
@ddt.data(True, False)
def test_neutron_quotas(self, ex_users, mock_neutron_quotas, mock_clients):
neutron_quo = mock_neutron_quotas.return_value
ctx = copy.deepcopy(self.context)
if ex_users:
ctx["existing_users"] = None
ctx["config"]["quotas"] = {
"neutron": {
"network": self.unlimited,
"subnet": self.unlimited,
"port": self.unlimited,
"router": self.unlimited,
"floatingip": self.unlimited,
"security_group": self.unlimited,
"security_group_rule": self.unlimited
}
}
tenants = ctx["tenants"]
neutron_quotas = ctx["config"]["quotas"]["neutron"]
neutron_quo.get.return_value = neutron_quotas
with quotas.Quotas(ctx) as quotas_ctx:
quotas_ctx.setup()
if ex_users:
self.assertEqual([mock.call(tenant) for tenant in tenants],
neutron_quo.get.call_args_list)
self.assertEqual([mock.call(tenant, **neutron_quotas)
for tenant in tenants],
neutron_quo.update.call_args_list)
neutron_quo.reset_mock()
if ex_users:
self.assertEqual([mock.call(tenant, **neutron_quotas)
for tenant in tenants],
neutron_quo.update.call_args_list)
else:
self.assertEqual([mock.call(tenant) for tenant in tenants],
neutron_quo.delete.call_args_list)
@mock.patch("rally_openstack.task.contexts."
"quotas.quotas.osclients.Clients")
@mock.patch("rally_openstack.task.contexts."
"quotas.nova_quotas.NovaQuotas")
@mock.patch("rally_openstack.task.contexts."
"quotas.cinder_quotas.CinderQuotas")
@mock.patch("rally_openstack.task.contexts."
"quotas.neutron_quotas.NeutronQuotas")
def test_no_quotas(self, mock_neutron_quotas, mock_cinder_quotas,
mock_nova_quotas, mock_clients):
ctx = copy.deepcopy(self.context)
if "quotas" in ctx["config"]:
del ctx["config"]["quotas"]
with quotas.Quotas(ctx) as quotas_ctx:
quotas_ctx.setup()
self.assertFalse(mock_cinder_quotas.update.called)
self.assertFalse(mock_nova_quotas.update.called)
self.assertFalse(mock_neutron_quotas.update.called)
self.assertFalse(mock_cinder_quotas.delete.called)
self.assertFalse(mock_nova_quotas.delete.called)
self.assertFalse(mock_neutron_quotas.delete.called)
@ddt.data(
{"quotas_ctxt": {"nova": {"cpu": 1}},
"quotas_class_path": "nova_quotas.NovaQuotas"},
{"quotas_ctxt": {"neutron": {"network": 2}},
"quotas_class_path": "neutron_quotas.NeutronQuotas"},
{"quotas_ctxt": {"cinder": {"volumes": 3}},
"quotas_class_path": "cinder_quotas.CinderQuotas"},
{"quotas_ctxt": {"manila": {"shares": 4}},
"quotas_class_path": "manila_quotas.ManilaQuotas"},
{"quotas_ctxt": {"designate": {"domains": 5}},
"quotas_class_path": "designate_quotas.DesignateQuotas"},
)
@ddt.unpack
def test_exception_during_cleanup(self, quotas_ctxt, quotas_class_path):
quotas_path = "%s.%s" % (QUOTAS_PATH, quotas_class_path)
with mock.patch(quotas_path) as mock_quotas:
mock_quotas.return_value.update.side_effect = Exception
ctx = copy.deepcopy(self.context)
ctx["config"]["quotas"] = quotas_ctxt
quotas_instance = quotas.Quotas(ctx)
quotas_instance.original_quotas = []
for service in quotas_ctxt:
for tenant in self.context["tenants"]:
quotas_instance.original_quotas.append(
(service, tenant, quotas_ctxt[service]))
# NOTE(boris-42): ensure that cleanup didn't raise exceptions.
with logging.LogCatcher(quotas.LOG) as log:
quotas_instance.cleanup()
log.assertInLogs("Failed to restore quotas for tenant")
self.assertEqual(mock_quotas.return_value.update.call_count,
len(self.context["tenants"]))
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,864
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/contexts/cinder/test_volumes.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
from unittest import mock
import ddt
from rally.task import context
from rally_openstack.task.contexts.cinder import volumes
from tests.unit import test
CTX = "rally_openstack.task.contexts"
SERVICE = "rally_openstack.common.services.storage"
@ddt.ddt
class VolumeGeneratorTestCase(test.ScenarioTestCase):
def _gen_tenants(self, count):
tenants = {}
for id_ in range(count):
tenants[str(id_)] = {"name": str(id_)}
return tenants
def test_init(self):
self.context.update({
"config": {
"volumes": {
"size": 1,
"volumes_per_tenant": 5,
}
}
})
inst = volumes.VolumeGenerator(self.context)
self.assertEqual(inst.config, self.context["config"]["volumes"])
@ddt.data({"config": {"size": 1, "volumes_per_tenant": 5}},
{"config": {"size": 1, "type": None, "volumes_per_tenant": 5}},
{"config": {"size": 1, "type": -1, "volumes_per_tenant": 5},
"valid": False})
@ddt.unpack
@mock.patch("%s.block.BlockStorage" % SERVICE)
def test_setup(self, mock_block_storage, config, valid=True):
results = context.Context.validate("volumes", None, None, config)
if valid:
self.assertEqual([], results)
else:
self.assertEqual(1, len(results))
from rally_openstack.common.services.storage import block
created_volume = block.Volume(id="uuid", size=config["size"],
name="vol", status="avaiable")
mock_service = mock_block_storage.return_value
mock_service.create_volume.return_value = created_volume
users_per_tenant = 5
volumes_per_tenant = config.get("volumes_per_tenant", 5)
tenants = self._gen_tenants(2)
users = []
for id_ in tenants:
for i in range(users_per_tenant):
users.append({"id": i, "tenant_id": id_,
"credential": mock.MagicMock()})
self.context.update({
"config": {
"users": {
"tenants": 2,
"users_per_tenant": 5,
"concurrent": 10,
},
"volumes": config
},
"admin": {
"credential": mock.MagicMock()
},
"users": users,
"tenants": tenants
})
new_context = copy.deepcopy(self.context)
for id_ in tenants.keys():
new_context["tenants"][id_].setdefault("volumes", [])
for i in range(volumes_per_tenant):
new_context["tenants"][id_]["volumes"].append(
mock_service.create_volume.return_value._as_dict())
volumes_ctx = volumes.VolumeGenerator(self.context)
volumes_ctx.setup()
self.assertEqual(new_context, self.context)
@mock.patch("%s.cinder.volumes.resource_manager.cleanup" % CTX)
def test_cleanup(self, mock_cleanup):
tenants_count = 2
users_per_tenant = 5
volumes_per_tenant = 5
tenants = self._gen_tenants(tenants_count)
users = []
for id_ in tenants.keys():
for i in range(users_per_tenant):
users.append({"id": i, "tenant_id": id_,
"credential": "credential"})
tenants[id_].setdefault("volumes", [])
for j in range(volumes_per_tenant):
tenants[id_]["volumes"].append({"id": "uuid"})
self.context.update({
"config": {
"users": {
"tenants": 2,
"users_per_tenant": 5,
"concurrent": 10,
},
"volumes": {
"size": 1,
"volumes_per_tenant": 5,
}
},
"admin": {
"credential": mock.MagicMock()
},
"users": users,
"tenants": tenants
})
volumes_ctx = volumes.VolumeGenerator(self.context)
volumes_ctx.cleanup()
mock_cleanup.assert_called_once_with(
names=["cinder.volumes"], users=self.context["users"],
superclass=volumes_ctx.__class__,
task_id=self.context["owner_id"])
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,865
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/nova/test_keypairs.py
|
# Copyright 2015: Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally import exceptions
from rally_openstack.task.scenarios.nova import keypairs
from tests.unit import fakes
from tests.unit import test
class NovaKeypairTestCase(test.ScenarioTestCase):
def test_create_and_list_keypairs(self):
fake_nova_client = fakes.FakeNovaClient()
fake_nova_client.keypairs.create("keypair")
fake_keypair = list(fake_nova_client.keypairs.cache.values())[0]
scenario = keypairs.CreateAndListKeypairs(self.context)
scenario._create_keypair = mock.MagicMock()
scenario._list_keypairs = mock.MagicMock()
scenario._list_keypairs.return_value = [fake_keypair] * 3
# Positive case:
scenario._create_keypair.return_value = fake_keypair.id
scenario.run(fakearg="fakearg")
scenario._create_keypair.assert_called_once_with(fakearg="fakearg")
scenario._list_keypairs.assert_called_once_with()
# Negative case1: keypair isn't created
scenario._create_keypair.return_value = None
self.assertRaises(exceptions.RallyAssertionError,
scenario.run, fakearg="fakearg")
scenario._create_keypair.assert_called_with(fakearg="fakearg")
# Negative case2: new keypair not in the list of keypairs
scenario._create_keypair.return_value = "fake_keypair"
self.assertRaises(exceptions.RallyAssertionError,
scenario.run, fakearg="fakearg")
scenario._create_keypair.assert_called_with(fakearg="fakearg")
scenario._list_keypairs.assert_called_with()
def test_create_and_get_keypair(self):
scenario = keypairs.CreateAndGetKeypair(self.context)
fake_keypair = mock.MagicMock()
scenario._create_keypair = mock.MagicMock()
scenario._get_keypair = mock.MagicMock()
scenario._create_keypair.return_value = fake_keypair
scenario.run(fakearg="fakearg")
scenario._create_keypair.assert_called_once_with(fakearg="fakearg")
scenario._get_keypair.assert_called_once_with(fake_keypair)
def test_create_and_delete_keypair(self):
scenario = keypairs.CreateAndDeleteKeypair(self.context)
scenario.generate_random_name = mock.MagicMock(return_value="name")
scenario._create_keypair = mock.MagicMock(return_value="foo_keypair")
scenario._delete_keypair = mock.MagicMock()
scenario.run(fakearg="fakearg")
scenario._create_keypair.assert_called_once_with(fakearg="fakearg")
scenario._delete_keypair.assert_called_once_with("foo_keypair")
def test_boot_and_delete_server_with_keypair(self):
scenario = keypairs.BootAndDeleteServerWithKeypair(self.context)
scenario.generate_random_name = mock.MagicMock(return_value="name")
scenario._create_keypair = mock.MagicMock(return_value="foo_keypair")
scenario._boot_server = mock.MagicMock(return_value="foo_server")
scenario._delete_server = mock.MagicMock()
scenario._delete_keypair = mock.MagicMock()
fake_server_args = {
"foo": 1,
"bar": 2,
}
scenario.run("img", 1, boot_server_kwargs=fake_server_args,
fake_arg1="foo", fake_arg2="bar")
scenario._create_keypair.assert_called_once_with(
fake_arg1="foo", fake_arg2="bar")
scenario._boot_server.assert_called_once_with(
"img", 1, foo=1, bar=2, key_name="foo_keypair")
scenario._delete_server.assert_called_once_with("foo_server")
scenario._delete_keypair.assert_called_once_with("foo_keypair")
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,866
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/common/services/storage/test_cinder_v2.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally.common import cfg
from rally_openstack.common.services.storage import cinder_v2
from tests.unit import fakes
from tests.unit import test
BASE_PATH = "rally_openstack.common.services.storage"
CONF = cfg.CONF
class CinderV2ServiceTestCase(test.ScenarioTestCase):
def setUp(self):
super(CinderV2ServiceTestCase, self).setUp()
self.clients = mock.MagicMock()
self.cinder = self.clients.cinder.return_value
self.name_generator = mock.MagicMock()
self.service = cinder_v2.CinderV2Service(
self.clients, name_generator=self.name_generator)
def atomic_actions(self):
return self.service._atomic_actions
def test_create_volume(self):
self.service.generate_random_name = mock.MagicMock(
return_value="volume")
self.service._wait_available_volume = mock.MagicMock()
self.service._wait_available_volume.return_value = fakes.FakeVolume()
return_volume = self.service.create_volume(1)
kwargs = {"name": "volume",
"description": None,
"consistencygroup_id": None,
"snapshot_id": None,
"source_volid": None,
"volume_type": None,
"availability_zone": None,
"metadata": None,
"imageRef": None,
"scheduler_hints": None}
self.cinder.volumes.create.assert_called_once_with(1, **kwargs)
self.service._wait_available_volume.assert_called_once_with(
self.cinder.volumes.create.return_value)
self.assertEqual(self.service._wait_available_volume.return_value,
return_volume)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.create_volume")
@mock.patch("%s.cinder_v2.random" % BASE_PATH)
def test_create_volume_with_size_range(self, mock_random):
mock_random.randint.return_value = 3
self.service._wait_available_volume = mock.MagicMock()
self.service._wait_available_volume.return_value = fakes.FakeVolume()
return_volume = self.service.create_volume(
size={"min": 1, "max": 5}, name="volume")
kwargs = {"name": "volume",
"description": None,
"consistencygroup_id": None,
"snapshot_id": None,
"source_volid": None,
"volume_type": None,
"availability_zone": None,
"metadata": None,
"imageRef": None,
"scheduler_hints": None}
self.cinder.volumes.create.assert_called_once_with(
3, **kwargs)
self.service._wait_available_volume.assert_called_once_with(
self.cinder.volumes.create.return_value)
self.assertEqual(self.service._wait_available_volume.return_value,
return_volume)
def test_update_volume(self):
return_value = {"volume": fakes.FakeVolume()}
self.cinder.volumes.update.return_value = return_value
self.assertEqual(return_value["volume"],
self.service.update_volume(1))
self.cinder.volumes.update.assert_called_once_with(1)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.update_volume")
def test_update_volume_with_name_description(self):
return_value = {"volume": fakes.FakeVolume()}
self.cinder.volumes.update.return_value = return_value
return_volume = self.service.update_volume(
1, name="volume", description="fake")
self.cinder.volumes.update.assert_called_once_with(
1, name="volume", description="fake")
self.assertEqual(return_value["volume"], return_volume)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.update_volume")
def test_list_volumes(self):
self.assertEqual(self.cinder.volumes.list.return_value,
self.service.list_volumes(
detailed=False, search_opts=None, limit=1,
marker=None, sort=None
))
self.cinder.volumes.list.assert_called_once_with(
detailed=False, search_opts=None, limit=1,
marker=None, sort=None
)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.list_volumes")
def test_list_types(self):
self.assertEqual(self.cinder.volume_types.list.return_value,
self.service.list_types(search_opts=None,
is_public=None))
self.cinder.volume_types.list.assert_called_once_with(
search_opts=None, is_public=None)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.list_types")
def test_create_snapshot(self):
self.service._wait_available_volume = mock.MagicMock()
self.service._wait_available_volume.return_value = fakes.FakeVolume()
self.service.generate_random_name = mock.MagicMock(
return_value="snapshot")
return_snapshot = self.service.create_snapshot(1)
self.cinder.volume_snapshots.create.assert_called_once_with(
1, name="snapshot", description=None, force=False,
metadata=None)
self.service._wait_available_volume.assert_called_once_with(
self.cinder.volume_snapshots.create.return_value)
self.assertEqual(self.service._wait_available_volume.return_value,
return_snapshot)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.create_snapshot")
def test_create_snapshot_with_name(self):
self.service._wait_available_volume = mock.MagicMock()
self.service._wait_available_volume.return_value = fakes.FakeVolume()
return_snapshot = self.service.create_snapshot(1, name="snapshot")
self.cinder.volume_snapshots.create.assert_called_once_with(
1, name="snapshot", description=None, force=False,
metadata=None)
self.service._wait_available_volume.assert_called_once_with(
self.cinder.volume_snapshots.create.return_value)
self.assertEqual(self.service._wait_available_volume.return_value,
return_snapshot)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.create_snapshot")
def test_create_backup(self):
self.service._wait_available_volume = mock.MagicMock()
self.service._wait_available_volume.return_value = fakes.FakeVolume()
self.service.generate_random_name = mock.MagicMock(
return_value="backup")
return_backup = self.service.create_backup(1)
self.cinder.backups.create.assert_called_once_with(
1, name="backup", description=None, container=None,
incremental=False, force=False, snapshot_id=None)
self.service._wait_available_volume.assert_called_once_with(
self.cinder.backups.create.return_value)
self.assertEqual(self.service._wait_available_volume.return_value,
return_backup)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.create_backup")
def test_create_backup_with_name(self):
self.service._wait_available_volume = mock.MagicMock()
self.service._wait_available_volume.return_value = fakes.FakeVolume()
return_backup = self.service.create_backup(1, name="backup")
self.cinder.backups.create.assert_called_once_with(
1, name="backup", description=None, container=None,
incremental=False, force=False, snapshot_id=None)
self.service._wait_available_volume.assert_called_once_with(
self.cinder.backups.create.return_value)
self.assertEqual(self.service._wait_available_volume.return_value,
return_backup)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.create_backup")
def test_create_volume_type(self):
self.service.generate_random_name = mock.MagicMock(
return_value="volume_type")
return_type = self.service.create_volume_type(name=None,
description=None,
is_public=True)
self.cinder.volume_types.create.assert_called_once_with(
name="volume_type", description=None, is_public=True)
self.assertEqual(self.cinder.volume_types.create.return_value,
return_type)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.create_volume_type")
def test_create_volume_type_with_name_(self):
return_type = self.service.create_volume_type(name="type",
description=None,
is_public=True)
self.cinder.volume_types.create.assert_called_once_with(
name="type", description=None, is_public=True)
self.assertEqual(self.cinder.volume_types.create.return_value,
return_type)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.create_volume_type")
def test_update_volume_type(self):
volume_type = mock.Mock()
name = "random_name"
self.service.generate_random_name = mock.MagicMock(
return_value=name)
description = "test update"
result = self.service.update_volume_type(
volume_type,
description=description,
name=self.service.generate_random_name(),
is_public=None
)
self.assertEqual(
self.cinder.volume_types.update.return_value,
result)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.update_volume_type")
def test_add_type_access(self):
volume_type = mock.Mock()
project = mock.Mock()
type_access = self.service.add_type_access(volume_type,
project=project)
add_project_access = self.cinder.volume_type_access.add_project_access
add_project_access.assert_called_once_with(
volume_type, project)
self.assertEqual(add_project_access.return_value,
type_access)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.add_type_access")
def test_list_type_access(self):
volume_type = mock.Mock()
type_access = self.service.list_type_access(volume_type)
self.cinder.volume_type_access.list.assert_called_once_with(
volume_type)
self.assertEqual(self.cinder.volume_type_access.list.return_value,
type_access)
self._test_atomic_action_timer(self.atomic_actions(),
"cinder_v2.list_type_access")
class UnifiedCinderV2ServiceTestCase(test.TestCase):
def setUp(self):
super(UnifiedCinderV2ServiceTestCase, self).setUp()
self.clients = mock.MagicMock()
self.service = cinder_v2.UnifiedCinderV2Service(self.clients)
self.service._impl = mock.MagicMock()
def test__unify_volume(self):
class SomeVolume(object):
id = 1
name = "volume"
size = 1
status = "st"
volume = self.service._unify_volume(SomeVolume())
self.assertEqual(1, volume.id)
self.assertEqual("volume", volume.name)
self.assertEqual(1, volume.size)
self.assertEqual("st", volume.status)
def test__unify_volume_with_dict(self):
some_volume = {"name": "volume", "id": 1, "size": 1, "status": "st"}
volume = self.service._unify_volume(some_volume)
self.assertEqual(1, volume.id)
self.assertEqual("volume", volume.name)
self.assertEqual(1, volume.size)
self.assertEqual("st", volume.status)
def test__unify_snapshot(self):
class SomeSnapshot(object):
id = 1
name = "snapshot"
volume_id = "volume"
status = "st"
snapshot = self.service._unify_snapshot(SomeSnapshot())
self.assertEqual(1, snapshot.id)
self.assertEqual("snapshot", snapshot.name)
self.assertEqual("volume", snapshot.volume_id)
self.assertEqual("st", snapshot.status)
def test_create_volume(self):
self.service._unify_volume = mock.MagicMock()
self.assertEqual(self.service._unify_volume.return_value,
self.service.create_volume(1))
self.service._impl.create_volume.assert_called_once_with(
1, availability_zone=None, consistencygroup_id=None,
description=None, imageRef=None,
metadata=None, name=None,
scheduler_hints=None, snapshot_id=None,
source_volid=None, volume_type=None)
self.service._unify_volume.assert_called_once_with(
self.service._impl.create_volume.return_value)
def test_list_volumes(self):
self.service._unify_volume = mock.MagicMock()
self.service._impl.list_volumes.return_value = ["vol"]
self.assertEqual([self.service._unify_volume.return_value],
self.service.list_volumes(detailed=True))
self.service._impl.list_volumes.assert_called_once_with(
detailed=True, limit=None, marker=None, search_opts=None,
sort=None)
self.service._unify_volume.assert_called_once_with("vol")
def test_get_volume(self):
self.service._unify_volume = mock.MagicMock()
self.assertEqual(self.service._unify_volume.return_value,
self.service.get_volume(1))
self.service._impl.get_volume.assert_called_once_with(1)
self.service._unify_volume.assert_called_once_with(
self.service._impl.get_volume.return_value)
def test_extend_volume(self):
self.service._unify_volume = mock.MagicMock()
self.assertEqual(self.service._unify_volume.return_value,
self.service.extend_volume("volume", new_size=1))
self.service._impl.extend_volume.assert_called_once_with("volume",
new_size=1)
self.service._unify_volume.assert_called_once_with(
self.service._impl.extend_volume.return_value)
def test_update_volume(self):
self.service._unify_volume = mock.MagicMock()
self.assertEqual(
self.service._unify_volume.return_value,
self.service.update_volume(1, name="volume",
description="fake"))
self.service._impl.update_volume.assert_called_once_with(
1, description="fake", name="volume")
self.service._unify_volume.assert_called_once_with(
self.service._impl.update_volume.return_value)
def test_list_types(self):
self.assertEqual(
self.service._impl.list_types.return_value,
self.service.list_types(search_opts=None, is_public=True))
self.service._impl.list_types.assert_called_once_with(
search_opts=None, is_public=True)
def test_create_snapshot(self):
self.service._unify_snapshot = mock.MagicMock()
self.assertEqual(
self.service._unify_snapshot.return_value,
self.service.create_snapshot(1, force=False,
name=None,
description=None,
metadata=None))
self.service._impl.create_snapshot.assert_called_once_with(
1, force=False, name=None, description=None, metadata=None)
self.service._unify_snapshot.assert_called_once_with(
self.service._impl.create_snapshot.return_value)
def test_list_snapshots(self):
self.service._unify_snapshot = mock.MagicMock()
self.service._impl.list_snapshots.return_value = ["snapshot"]
self.assertEqual([self.service._unify_snapshot.return_value],
self.service.list_snapshots(detailed=True))
self.service._impl.list_snapshots.assert_called_once_with(
detailed=True)
self.service._unify_snapshot.assert_called_once_with(
"snapshot")
def test_create_backup(self):
self.service._unify_backup = mock.MagicMock()
self.assertEqual(
self.service._unify_backup.return_value,
self.service.create_backup(1, container=None,
name=None,
description=None,
incremental=False,
force=False,
snapshot_id=None))
self.service._impl.create_backup.assert_called_once_with(
1, container=None, name=None, description=None,
incremental=False, force=False, snapshot_id=None)
self.service._unify_backup(
self.service._impl.create_backup.return_value)
def test_create_volume_type(self):
self.assertEqual(
self.service._impl.create_volume_type.return_value,
self.service.create_volume_type(name="type",
description="desp",
is_public=True))
self.service._impl.create_volume_type.assert_called_once_with(
name="type", description="desp", is_public=True)
def test_restore_backup(self):
self.service._unify_volume = mock.MagicMock()
self.assertEqual(self.service._unify_volume.return_value,
self.service.restore_backup(1, volume_id=1))
self.service._impl.restore_backup.assert_called_once_with(1,
volume_id=1)
self.service._unify_volume.assert_called_once_with(
self.service._impl.restore_backup.return_value)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,867
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/magnum/test_clusters.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
import ddt
from rally import exceptions
from rally_openstack.task.scenarios.magnum import clusters
from tests.unit import test
@ddt.ddt
class MagnumClustersTestCase(test.ScenarioTestCase):
@staticmethod
def _get_context():
context = test.get_test_context()
context.update({
"tenant": {
"id": "rally_tenant_id"
},
"user": {"id": "fake_user_id",
"credential": mock.MagicMock()},
"config": {}
})
return context
@ddt.data(
{"kwargs": {}},
{"kwargs": {"fakearg": "f"}})
def test_list_clusters(self, kwargs):
scenario = clusters.ListClusters()
scenario._list_clusters = mock.Mock()
scenario.run(**kwargs)
scenario._list_clusters.assert_called_once_with(**kwargs)
def test_create_cluster_with_existing_ct_and_list_clusters(self):
context = self._get_context()
scenario = clusters.CreateAndListClusters(context)
kwargs = {"fakearg": "f"}
fake_cluster1 = mock.Mock(uuid="a")
fake_cluster2 = mock.Mock(uuid="b")
fake_cluster3 = mock.Mock(uuid="c")
scenario._create_cluster = mock.Mock(return_value=fake_cluster1)
scenario._list_clusters = mock.Mock(return_value=[fake_cluster1,
fake_cluster2,
fake_cluster3])
run_kwargs = kwargs.copy()
run_kwargs["cluster_template_uuid"] = "existing_cluster_template_uuid"
# Positive case
scenario.run(2, **run_kwargs)
scenario._create_cluster.assert_called_once_with(
"existing_cluster_template_uuid", 2, keypair=mock.ANY, **kwargs)
scenario._list_clusters.assert_called_once_with(**kwargs)
# Negative case1: cluster isn't created
scenario._create_cluster.return_value = None
self.assertRaises(exceptions.RallyAssertionError,
scenario.run, 2, **run_kwargs)
scenario._create_cluster.assert_called_with(
"existing_cluster_template_uuid", 2, keypair=mock.ANY, **kwargs)
# Negative case2: created cluster not in the list of available clusters
scenario._create_cluster.return_value = mock.Mock(uuid="foo")
self.assertRaises(exceptions.RallyAssertionError,
scenario.run, 2, **run_kwargs)
scenario._create_cluster.assert_called_with(
"existing_cluster_template_uuid", 2, keypair=mock.ANY, **kwargs)
scenario._list_clusters.assert_called_with(**kwargs)
def test_create_and_list_clusters(self):
context = self._get_context()
context.update({
"tenant": {
"cluster_template": "rally_cluster_template_uuid"
}
})
scenario = clusters.CreateAndListClusters(context)
fake_cluster1 = mock.Mock(uuid="a")
fake_cluster2 = mock.Mock(uuid="b")
fake_cluster3 = mock.Mock(uuid="c")
kwargs = {"fakearg": "f"}
scenario._create_cluster = mock.Mock(return_value=fake_cluster1)
scenario._list_clusters = mock.Mock(return_value=[fake_cluster1,
fake_cluster2,
fake_cluster3])
# Positive case
scenario.run(2, **kwargs)
scenario._create_cluster.assert_called_once_with(
"rally_cluster_template_uuid", 2, keypair=mock.ANY, **kwargs)
scenario._list_clusters.assert_called_once_with(**kwargs)
# Negative case1: cluster isn't created
scenario._create_cluster.return_value = None
self.assertRaises(exceptions.RallyAssertionError,
scenario.run, 2, **kwargs)
scenario._create_cluster.assert_called_with(
"rally_cluster_template_uuid", 2, keypair=mock.ANY, **kwargs)
# Negative case2: created cluster not in the list of available clusters
scenario._create_cluster.return_value = mock.Mock(uuid="foo")
self.assertRaises(exceptions.RallyAssertionError,
scenario.run, 2, **kwargs)
scenario._create_cluster.assert_called_with(
"rally_cluster_template_uuid", 2, keypair=mock.ANY, **kwargs)
scenario._list_clusters.assert_called_with(**kwargs)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,868
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/contexts/swift/test_objects.py
|
# Copyright 2015: Cisco Systems, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally import exceptions
from rally_openstack.task.contexts.swift import objects
from tests.unit import test
class SwiftObjectGeneratorTestCase(test.TestCase):
@mock.patch("rally_openstack.common.osclients.Clients")
def test_setup(self, mock_clients):
containers_per_tenant = 2
objects_per_container = 7
context = test.get_test_context()
context.update({
"config": {
"swift_objects": {
"containers_per_tenant": containers_per_tenant,
"objects_per_container": objects_per_container,
"object_size": 1024,
"resource_management_workers": 10
}
},
"tenants": {
"t1": {"name": "t1_name"},
"t2": {"name": "t2_name"}
},
"users": [
{
"id": "u1",
"tenant_id": "t1",
"credential": mock.MagicMock()
},
{
"id": "u2",
"tenant_id": "t2",
"credential": mock.MagicMock()
}
]
})
objects_ctx = objects.SwiftObjectGenerator(context)
objects_ctx.setup()
for tenant_id in context["tenants"]:
containers = context["tenants"][tenant_id]["containers"]
self.assertEqual(containers_per_tenant, len(containers))
for container in containers:
self.assertEqual(objects_per_container,
len(container["objects"]))
@mock.patch("rally_openstack.common.osclients.Clients")
@mock.patch("rally_openstack.task.contexts.swift.utils."
"swift_utils.SwiftScenario")
def test_cleanup(self, mock_swift_scenario, mock_clients):
context = test.get_test_context()
context.update({
"config": {
"swift_objects": {
"resource_management_workers": 1
}
},
"tenants": {
"t1": {
"name": "t1_name",
"containers": [
{"user": {"id": "u1", "tenant_id": "t1",
"credential": "c1"},
"container": "c1",
"objects": ["o1", "o2", "o3"]}
]
},
"t2": {
"name": "t2_name",
"containers": [
{"user": {"id": "u2", "tenant_id": "t2",
"credential": "c2"},
"container": "c2",
"objects": ["o4", "o5", "o6"]}
]
}
}
})
objects_ctx = objects.SwiftObjectGenerator(context)
objects_ctx.cleanup()
expected_containers = ["c1", "c2"]
mock_swift_scenario.return_value._delete_container.assert_has_calls(
[mock.call(con) for con in expected_containers], any_order=True)
expected_objects = [("c1", "o1"), ("c1", "o2"), ("c1", "o3"),
("c2", "o4"), ("c2", "o5"), ("c2", "o6")]
mock_swift_scenario.return_value._delete_object.assert_has_calls(
[mock.call(con, obj) for con, obj in expected_objects],
any_order=True)
for tenant_id in context["tenants"]:
self.assertEqual(0,
len(context["tenants"][tenant_id]["containers"]))
@mock.patch("rally_openstack.common.osclients.Clients")
def test_setup_failure_clients_put_container(self, mock_clients):
context = test.get_test_context()
context.update({
"config": {
"swift_objects": {
"containers_per_tenant": 2,
"object_size": 10,
"resource_management_workers": 5
}
},
"tenants": {
"t1": {"name": "t1_name"},
"t2": {"name": "t2_name"}
},
"users": [
{
"id": "u1",
"tenant_id": "t1",
"credential": mock.MagicMock()
},
{
"id": "u2",
"tenant_id": "t2",
"credential": mock.MagicMock()
}
]
})
mock_swift = mock_clients.return_value.swift.return_value
mock_swift.put_container.side_effect = [Exception, True,
Exception, Exception]
objects_ctx = objects.SwiftObjectGenerator(context)
self.assertRaisesRegex(exceptions.ContextSetupFailure,
"containers, expected 4 but got 1",
objects_ctx.setup)
@mock.patch("rally_openstack.common.osclients.Clients")
def test_setup_failure_clients_put_object(self, mock_clients):
context = test.get_test_context()
context.update({
"tenants": {
"t1": {"name": "t1_name"},
"t2": {"name": "t2_name"}
},
"users": [
{
"id": "u1",
"tenant_id": "t1",
"credential": mock.MagicMock()
},
{
"id": "u2",
"tenant_id": "t2",
"credential": mock.MagicMock()
}
]
})
mock_swift = mock_clients.return_value.swift.return_value
mock_swift.put_object.side_effect = [Exception, True]
objects_ctx = objects.SwiftObjectGenerator(context)
self.assertRaisesRegex(exceptions.ContextSetupFailure,
"objects, expected 2 but got 1",
objects_ctx.setup)
@mock.patch("rally_openstack.common.osclients.Clients")
def test_cleanup_failure_clients_delete_container(self, mock_clients):
context = test.get_test_context()
context.update({
"tenants": {
"t1": {
"name": "t1_name",
"containers": [
{"user": {"id": "u1", "tenant_id": "t1",
"credential": mock.MagicMock()},
"container": "coooon",
"objects": []}] * 3
}
}
})
mock_swift = mock_clients.return_value.swift.return_value
mock_swift.delete_container.side_effect = [True, True, Exception]
objects_ctx = objects.SwiftObjectGenerator(context)
objects_ctx.cleanup()
self.assertEqual(1, len(context["tenants"]["t1"]["containers"]))
@mock.patch("rally_openstack.common.osclients.Clients")
def test_cleanup_failure_clients_delete_object(self, mock_clients):
context = test.get_test_context()
context.update({
"tenants": {
"t1": {
"name": "t1_name",
"containers": [
{"user": {"id": "u1", "tenant_id": "t1",
"credential": mock.MagicMock()},
"container": "c1",
"objects": ["oooo"] * 3}
]
}
}
})
mock_swift = mock_clients.return_value.swift.return_value
mock_swift.delete_object.side_effect = [True, Exception, True]
objects_ctx = objects.SwiftObjectGenerator(context)
objects_ctx._delete_containers = mock.MagicMock()
objects_ctx.cleanup()
self.assertEqual(
1, sum([len(container["objects"])
for container in context["tenants"]["t1"]["containers"]]))
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,869
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/common/osclients.py
|
# Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import os
from urllib.parse import urlparse
from urllib.parse import urlunparse
from rally.common import cfg
from rally.common import logging
from rally.common.plugin import plugin
from rally import exceptions
from rally_openstack.common import consts
from rally_openstack.common import credential as oscred
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
class AuthenticationFailed(exceptions.AuthenticationFailed):
error_code = 220
msg_fmt = ("Failed to authenticate to %(url)s for user '%(username)s'"
" in project '%(project)s': %(message)s")
msg_fmt_2 = "%(message)s"
def __init__(self, error, url, username, project):
kwargs = {
"error": error,
"url": url,
"username": username,
"project": project
}
self._helpful_trace = False
from keystoneauth1 import exceptions as ks_exc
if isinstance(error, (ks_exc.ConnectionError,
ks_exc.DiscoveryFailure)):
# this type of errors is general for all users no need to include
# username, project name. The original error message should be
# self-sufficient
self.msg_fmt = self.msg_fmt_2
message = error.message
if (message.startswith("Unable to establish connection to")
or isinstance(error, ks_exc.DiscoveryFailure)):
if "Max retries exceeded with url" in message:
if "HTTPConnectionPool" in message:
splitter = ": HTTPConnectionPool"
else:
splitter = ": HTTPSConnectionPool"
message = message.split(splitter, 1)[0]
elif isinstance(error, ks_exc.Unauthorized):
message = error.message.split(" (HTTP 401)", 1)[0]
else:
# something unexpected. include exception class as well.
self._helpful_trace = True
message = "[%s] %s" % (error.__class__.__name__, str(error))
super(AuthenticationFailed, self).__init__(message=message, **kwargs)
def is_trace_helpful(self):
return self._helpful_trace
def configure(name, default_version=None, default_service_type=None,
supported_versions=None):
"""OpenStack client class wrapper.
Each client class has to be wrapped by configure() wrapper. It
sets essential configuration of client classes.
:param name: Name of the client
:param default_version: Default version for client
:param default_service_type: Default service type of endpoint(If this
variable is not specified, validation will assume that your client
doesn't allow to specify service type.
:param supported_versions: List of supported versions(If this variable is
not specified, `OSClient.validate_version` method will raise an
exception that client doesn't support setting any versions. If this
logic is wrong for your client, you should override `validate_version`
in client object)
"""
def wrapper(cls):
cls = plugin.configure(name=name, platform="openstack")(cls)
cls._meta_set("default_version", default_version)
cls._meta_set("default_service_type", default_service_type)
cls._meta_set("supported_versions", supported_versions or [])
return cls
return wrapper
@plugin.base()
class OSClient(plugin.Plugin):
"""Base class for OpenStack clients"""
def __init__(self, credential, cache_obj=None):
self.credential = credential
if not isinstance(self.credential, oscred.OpenStackCredential):
self.credential = oscred.OpenStackCredential(**self.credential)
self.cache = cache_obj if cache_obj is not None else {}
def choose_version(self, version=None):
"""Return version string.
Choose version between transmitted(preferable value if present),
version from api_info(configured from a context) and default.
"""
# NOTE(andreykurilin): The result of choose is converted to string,
# since most of clients contain map for versioned modules, where a key
# is a string value of version. Example of map and its usage:
#
# from oslo_utils import importutils
# ...
# version_map = {"1": "someclient.v1.client.Client",
# "2": "someclient.v2.client.Client"}
#
# def Client(version, *args, **kwargs):
# cls = importutils.import_class(version_map[version])
# return cls(*args, **kwargs)
#
# That is why type of version so important and we should ensure that
# version is a string object.
# For those clients which doesn't accept string value(for example
# zaqarclient), this method should be overridden.
version = (version
or self.credential.api_info.get(self.get_name(), {}).get(
"version") or self._meta_get("default_version"))
if version is not None:
version = str(version)
return version
@classmethod
def get_supported_versions(cls):
return cls._meta_get("supported_versions")
@classmethod
def validate_version(cls, version):
supported_versions = cls.get_supported_versions()
if supported_versions:
if str(version) not in supported_versions:
raise exceptions.ValidationError(
"'%(vers)s' is not supported. Should be one of "
"'%(supported)s'"
% {"vers": version, "supported": supported_versions})
else:
raise exceptions.RallyException("Setting version is not supported")
try:
float(version)
except ValueError:
raise exceptions.ValidationError(
"'%s' is invalid. Should be numeric value." % version
) from None
def choose_service_type(self, service_type=None):
"""Return service_type string.
Choose service type between transmitted(preferable value if present),
service type from api_info(configured from a context) and default.
"""
return (service_type
or self.credential.api_info.get(self.get_name(), {}).get(
"service_type") or self._meta_get("default_service_type"))
@classmethod
def is_service_type_configurable(cls):
"""Just checks that client supports setting service type."""
if cls._meta_get("default_service_type") is None:
raise exceptions.RallyException(
"Setting service type is not supported.")
@property
def keystone(self):
return OSClient.get("keystone")(self.credential, self.cache)
def _get_endpoint(self, service_type=None):
kw = {"service_type": self.choose_service_type(service_type),
"region_name": self.credential.region_name}
if self.credential.endpoint_type:
kw["interface"] = self.credential.endpoint_type
api_url = self.keystone.service_catalog.url_for(**kw)
return api_url
def _get_auth_info(self, user_key="username",
password_key="password",
auth_url_key="auth_url",
project_name_key="project_id",
domain_name_key="domain_name",
user_domain_name_key="user_domain_name",
project_domain_name_key="project_domain_name",
cacert_key="cacert",
endpoint_type="endpoint_type",
):
kw = {
user_key: self.credential.username,
password_key: self.credential.password,
auth_url_key: self.credential.auth_url,
cacert_key: self.credential.https_cacert,
}
if project_name_key:
kw.update({project_name_key: self.credential.tenant_name})
if "v2.0" not in self.credential.auth_url:
kw.update({
domain_name_key: self.credential.domain_name})
kw.update({
user_domain_name_key:
self.credential.user_domain_name or "Default"})
kw.update({
project_domain_name_key:
self.credential.project_domain_name or "Default"})
if self.credential.endpoint_type:
kw[endpoint_type] = self.credential.endpoint_type
return kw
@abc.abstractmethod
def create_client(self, *args, **kwargs):
"""Create new instance of client."""
def __call__(self, *args, **kwargs):
"""Return initialized client instance."""
key = "{0}{1}{2}".format(self.get_name(),
str(args) if args else "",
str(kwargs) if kwargs else "")
if key not in self.cache:
self.cache[key] = self.create_client(*args, **kwargs)
return self.cache[key]
@classmethod
def get(cls, name, **kwargs):
# NOTE(boris-42): Remove this after we finish rename refactoring.
kwargs.pop("platform", None)
kwargs.pop("namespace", None)
return super(OSClient, cls).get(name, platform="openstack", **kwargs)
@configure("keystone", supported_versions=("2", "3"))
class Keystone(OSClient):
"""Wrapper for KeystoneClient which hides OpenStack auth details."""
@property
def keystone(self):
raise exceptions.RallyException(
"Method 'keystone' is restricted for keystoneclient. :)")
@property
def service_catalog(self):
return self.auth_ref.service_catalog
@property
def auth_ref(self):
try:
if "keystone_auth_ref" not in self.cache:
sess, plugin = self.get_session()
self.cache["keystone_auth_ref"] = plugin.get_access(sess)
except Exception as original_e:
e = AuthenticationFailed(
error=original_e,
username=self.credential.username,
project=self.credential.tenant_name,
url=self.credential.auth_url
)
if logging.is_debug() and e.is_trace_helpful():
LOG.exception("Unable to authenticate for user"
" %(username)s in project"
" %(tenant_name)s" %
{"username": self.credential.username,
"tenant_name": self.credential.tenant_name})
raise e from None
return self.cache["keystone_auth_ref"]
def get_session(self, version=None):
key = "keystone_session_and_plugin_%s" % version
if key not in self.cache:
from keystoneauth1 import discover
from keystoneauth1 import identity
from keystoneauth1 import session
version = self.choose_version(version)
auth_url = self.credential.auth_url
if version is not None:
auth_url = self._remove_url_version()
password_args = {
"auth_url": auth_url,
"username": self.credential.username,
"password": self.credential.password,
"tenant_name": self.credential.tenant_name
}
if version is None:
# NOTE(rvasilets): If version not specified than we discover
# available version with the smallest number. To be able to
# discover versions we need session
temp_session = session.Session(
verify=(self.credential.https_cacert
or not self.credential.https_insecure),
cert=self.credential.https_cert,
timeout=CONF.openstack_client_http_timeout)
version = str(discover.Discover(
temp_session,
password_args["auth_url"]).version_data()[0]["version"][0])
temp_session.session.close()
if "v2.0" not in password_args["auth_url"] and version != "2":
password_args.update({
"user_domain_name": self.credential.user_domain_name,
"domain_name": self.credential.domain_name,
"project_domain_name": self.credential.project_domain_name
})
identity_plugin = identity.Password(**password_args)
sess = session.Session(
auth=identity_plugin,
verify=(self.credential.https_cacert
or not self.credential.https_insecure),
cert=self.credential.https_cert,
timeout=CONF.openstack_client_http_timeout)
self.cache[key] = (sess, identity_plugin)
return self.cache[key]
def _remove_url_version(self):
"""Remove any version from the auth_url.
The keystone Client code requires that auth_url be the root url
if a version override is used.
"""
url = urlparse(self.credential.auth_url)
path = url.path.rstrip("/")
if path.endswith("v2.0") or path.endswith("v3"):
path = os.path.join(*os.path.split(path)[:-1])
parts = (url.scheme, url.netloc, path, url.params, url.query,
url.fragment)
return urlunparse(parts)
return self.credential.auth_url
def create_client(self, version=None):
"""Return a keystone client.
:param version: Keystone API version, can be one of:
("2", "3")
If this object was constructed with a version in the api_info
then that will be used unless the version parameter is passed.
"""
import keystoneclient
from keystoneclient import client
# Use the version in the api_info if provided, otherwise fall
# back to the passed version (which may be None, in which case
# keystoneclient chooses).
version = self.choose_version(version)
sess, auth_plugin = self.get_session(version=version)
kw = {"version": version, "session": sess,
"timeout": CONF.openstack_client_http_timeout}
# check for keystone version
if auth_plugin._user_domain_name and self.credential.region_name:
kw["region_name"] = self.credential.region_name
if keystoneclient.__version__[0] == "1":
# NOTE(andreykurilin): let's leave this hack for envs which uses
# old(<2.0.0) keystoneclient version. Upstream fix:
# https://github.com/openstack/python-keystoneclient/commit/d9031c252848d89270a543b67109a46f9c505c86
from keystoneauth1 import plugin
kw["auth_url"] = sess.get_endpoint(interface=plugin.AUTH_INTERFACE)
if self.credential.endpoint_type:
kw["interface"] = self.credential.endpoint_type
# NOTE(amyge):
# In auth_ref(), plugin.get_access(sess) only returns a auth_ref object
# and won't check the authentication access until it is actually being
# called. To catch the authentication failure in auth_ref(), we will
# have to call self.auth_ref.auth_token here to actually use auth_ref.
self.auth_ref # noqa
return client.Client(**kw)
@configure("nova", default_version="2", default_service_type="compute")
class Nova(OSClient):
"""Wrapper for NovaClient which returns a authenticated native client."""
@classmethod
def validate_version(cls, version):
from novaclient import api_versions
from novaclient import exceptions as nova_exc
try:
api_versions.get_api_version(version)
except nova_exc.UnsupportedVersion:
raise exceptions.RallyException(
"Version string '%s' is unsupported." % version) from None
def create_client(self, version=None, service_type=None):
"""Return nova client."""
from novaclient import client as nova
client = nova.Client(
session=self.keystone.get_session()[0],
version=self.choose_version(version),
endpoint_override=self._get_endpoint(service_type))
return client
@configure("neutron", default_version="2.0", default_service_type="network",
supported_versions=["2.0"])
class Neutron(OSClient):
"""Wrapper for NeutronClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return neutron client."""
from neutronclient.neutron import client as neutron
kw_args = {}
if self.credential.endpoint_type:
kw_args["endpoint_type"] = self.credential.endpoint_type
client = neutron.Client(
self.choose_version(version),
session=self.keystone.get_session()[0],
endpoint_override=self._get_endpoint(service_type),
**kw_args)
return client
@configure("octavia", default_version="2",
default_service_type="load-balancer", supported_versions=["2"])
class Octavia(OSClient):
"""Wrapper for OctaviaClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return octavia client."""
from octaviaclient.api.v2 import octavia
kw_args = {}
if self.credential.endpoint_type:
kw_args["endpoint_type"] = self.credential.endpoint_type
client = octavia.OctaviaAPI(
endpoint=self._get_endpoint(service_type),
session=self.keystone.get_session()[0],
**kw_args)
return client
@configure("glance", default_version="2", default_service_type="image",
supported_versions=["1", "2"])
class Glance(OSClient):
"""Wrapper for GlanceClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return glance client."""
import glanceclient as glance
session = self.keystone.get_session()[0]
client = glance.Client(
version=self.choose_version(version),
endpoint_override=self._get_endpoint(service_type),
session=session)
return client
@configure("heat", default_version="1", default_service_type="orchestration",
supported_versions=["1"])
class Heat(OSClient):
"""Wrapper for HeatClient which returns an authenticated native client."""
def create_client(self, version=None, service_type=None):
"""Return heat client."""
from heatclient import client as heat
# ToDo: Remove explicit endpoint_type or interface initialization
# when heatclient no longer uses it.
kw_args = {}
if self.credential.endpoint_type:
kw_args["interface"] = self.credential.endpoint_type
client = heat.Client(
self.choose_version(version),
session=self.keystone.get_session()[0],
endpoint_override=self._get_endpoint(service_type),
**kw_args)
return client
@configure("cinder", default_version="3", default_service_type="block-storage",
supported_versions=["1", "2", "3"])
class Cinder(OSClient):
"""Wrapper for CinderClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return cinder client."""
from cinderclient import client as cinder
client = cinder.Client(
self.choose_version(version),
session=self.keystone.get_session()[0],
endpoint_override=self._get_endpoint(service_type))
return client
@configure("manila", default_version="1", default_service_type="share")
class Manila(OSClient):
"""Wrapper for ManilaClient which returns an authenticated native client.
"""
@classmethod
def validate_version(cls, version):
from manilaclient import api_versions
from manilaclient import exceptions as manila_exc
try:
api_versions.get_api_version(version)
except manila_exc.UnsupportedVersion:
raise exceptions.RallyException(
"Version string '%s' is unsupported." % version) from None
def create_client(self, version=None, service_type=None):
"""Return manila client."""
from manilaclient import client as manila
manila_client = manila.Client(
self.choose_version(version),
insecure=self.credential.https_insecure,
session=self.keystone.get_session()[0],
service_catalog_url=self._get_endpoint(service_type))
return manila_client
@configure("gnocchi", default_service_type="metric", default_version="1",
supported_versions=["1"])
class Gnocchi(OSClient):
"""Wrapper for GnocchiClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return gnocchi client."""
# NOTE(sumantmurke): gnocchiclient requires keystoneauth1 for
# authenticating and creating a session.
from gnocchiclient import client as gnocchi
service_type = self.choose_service_type(service_type)
sess = self.keystone.get_session()[0]
gclient = gnocchi.Client(
version=self.choose_version(version), session=sess,
adapter_options={"service_type": service_type,
"interface": self.credential.endpoint_type})
return gclient
@configure("ironic", default_version="1", default_service_type="baremetal",
supported_versions=["1"])
class Ironic(OSClient):
"""Wrapper for IronicClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return Ironic client."""
from ironicclient import client as ironic
client = ironic.get_client(
self.choose_version(version),
session=self.keystone.get_session()[0],
endpoint=self._get_endpoint(service_type))
return client
@configure("sahara", default_version="1.1", supported_versions=["1.0", "1.1"],
default_service_type="data-processing")
class Sahara(OSClient):
"""Wrapper for SaharaClient which returns an authenticated native client.
"""
# NOTE(andreykurilin): saharaclient supports "1.0" version and doesn't
# support "1". `choose_version` and `validate_version` methods are written
# as a hack to covert 1 -> 1.0, which can simplify setting saharaclient
# for end-users.
def choose_version(self, version=None):
return float(super(Sahara, self).choose_version(version))
@classmethod
def validate_version(cls, version):
super(Sahara, cls).validate_version(float(version))
def create_client(self, version=None, service_type=None):
"""Return Sahara client."""
from saharaclient import client as sahara
client = sahara.Client(
self.choose_version(version),
session=self.keystone.get_session()[0],
sahara_url=self._get_endpoint(service_type))
return client
@configure("zaqar", default_version="1.1", default_service_type="messaging",
supported_versions=["1", "1.1"])
class Zaqar(OSClient):
"""Wrapper for ZaqarClient which returns an authenticated native client.
"""
def choose_version(self, version=None):
# zaqarclient accepts only int or float obj as version
return float(super(Zaqar, self).choose_version(version))
def create_client(self, version=None, service_type=None):
"""Return Zaqar client."""
from zaqarclient.queues import client as zaqar
client = zaqar.Client(url=self._get_endpoint(),
version=self.choose_version(version),
session=self.keystone.get_session()[0])
return client
@configure("murano", default_version="1",
default_service_type="application-catalog",
supported_versions=["1"])
class Murano(OSClient):
"""Wrapper for MuranoClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return Murano client."""
from muranoclient import client as murano
client = murano.Client(self.choose_version(version),
endpoint=self._get_endpoint(service_type),
token=self.keystone.auth_ref.auth_token)
return client
@configure("designate", default_version="2", default_service_type="dns",
supported_versions=["2"])
class Designate(OSClient):
"""Wrapper for DesignateClient which returns authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return designate client."""
from designateclient import client
version = self.choose_version(version)
api_url = self._get_endpoint(service_type)
api_url += "/v%s" % version
session = self.keystone.get_session()[0]
return client.Client(version, session=session,
endpoint_override=api_url)
@configure("trove", default_version="1.0", supported_versions=["1.0"],
default_service_type="database")
class Trove(OSClient):
"""Wrapper for TroveClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Returns trove client."""
from troveclient import client as trove
client = trove.Client(self.choose_version(version),
session=self.keystone.get_session()[0],
endpoint=self._get_endpoint(service_type))
return client
@configure("mistral", default_service_type="workflowv2")
class Mistral(OSClient):
"""Wrapper for MistralClient which returns an authenticated native client.
"""
def create_client(self, service_type=None):
"""Return Mistral client."""
from mistralclient.api import client as mistral
client = mistral.client(
mistral_url=self._get_endpoint(service_type),
service_type=self.choose_service_type(service_type),
auth_token=self.keystone.auth_ref.auth_token)
return client
@configure("swift", default_service_type="object-store")
class Swift(OSClient):
"""Wrapper for SwiftClient which returns an authenticated native client.
"""
def create_client(self, service_type=None):
"""Return swift client."""
from swiftclient import client as swift
auth_token = self.keystone.auth_ref.auth_token
client = swift.Connection(retries=1,
preauthurl=self._get_endpoint(service_type),
preauthtoken=auth_token,
insecure=self.credential.https_insecure,
cacert=self.credential.https_cacert,
user=self.credential.username,
tenant_name=self.credential.tenant_name,
)
return client
@configure("monasca", default_version="2_0",
default_service_type="monitoring", supported_versions=["2_0"])
class Monasca(OSClient):
"""Wrapper for MonascaClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return monasca client."""
from monascaclient import client as monasca
# Change this to use session once it's supported by monascaclient
client = monasca.Client(
self.choose_version(version),
self._get_endpoint(service_type),
token=self.keystone.auth_ref.auth_token,
timeout=CONF.openstack_client_http_timeout,
insecure=self.credential.https_insecure,
**self._get_auth_info(project_name_key="tenant_name"))
return client
@configure("senlin", default_version="1", default_service_type="clustering",
supported_versions=["1"])
class Senlin(OSClient):
"""Wrapper for SenlinClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return senlin client."""
from senlinclient import client as senlin
return senlin.Client(
self.choose_version(version),
**self._get_auth_info(project_name_key="project_name",
cacert_key="cert",
endpoint_type="interface"))
@configure("magnum", default_version="1", supported_versions=["1"],
default_service_type="container-infra",)
class Magnum(OSClient):
"""Wrapper for MagnumClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return magnum client."""
from magnumclient import client as magnum
api_url = self._get_endpoint(service_type)
session = self.keystone.get_session()[0]
return magnum.Client(
session=session,
interface=self.credential.endpoint_type,
magnum_url=api_url)
@configure("watcher", default_version="1", default_service_type="infra-optim",
supported_versions=["1"])
class Watcher(OSClient):
"""Wrapper for WatcherClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return watcher client."""
from watcherclient import client as watcher_client
watcher_api_url = self._get_endpoint(
self.choose_service_type(service_type))
client = watcher_client.Client(
self.choose_version(version),
endpoint=watcher_api_url,
session=self.keystone.get_session()[0])
return client
@configure("barbican", default_version="1", default_service_type="key-manager")
class Barbican(OSClient):
"""Wrapper for BarbicanClient which returns an authenticated native client.
"""
def create_client(self, version=None, service_type=None):
"""Return Barbican client."""
from barbicanclient import client as barbican_client
version = "v%s" % self.choose_version(version)
client = barbican_client.Client(
version=self.choose_version(version),
session=self.keystone.get_session()[0])
return client
class Clients(object):
"""This class simplify and unify work with OpenStack python clients."""
def __init__(self, credential, cache=None):
self.credential = credential
self.cache = cache or {}
def __getattr__(self, client_name):
"""Lazy load of clients."""
return OSClient.get(client_name)(self.credential, self.cache)
@classmethod
def create_from_env(cls):
from rally_openstack.common import credential
from rally_openstack.environment.platforms import existing
spec = existing.OpenStack.create_spec_from_sys_environ(os.environ)
if not spec["available"]:
raise ValueError(spec["message"]) from None
creds = spec["spec"]
oscred = credential.OpenStackCredential(
auth_url=creds["auth_url"],
username=creds["admin"]["username"],
password=creds["admin"]["password"],
tenant_name=creds["admin"].get(
"tenant_name", creds["admin"].get("project_name")),
endpoint_type=creds["endpoint_type"],
user_domain_name=creds["admin"].get("user_domain_name"),
project_domain_name=creds["admin"].get("project_domain_name"),
region_name=creds["region_name"],
https_cacert=creds["https_cacert"],
https_insecure=creds["https_insecure"])
return cls(oscred)
def clear(self):
"""Remove all cached client handles."""
self.cache = {}
def verified_keystone(self):
"""Ensure keystone endpoints are valid and then authenticate
:returns: Keystone Client
"""
# Ensure that user is admin
if "admin" not in [role.lower() for role in
self.keystone.auth_ref.role_names]:
raise exceptions.InvalidAdminException(
username=self.credential.username)
return self.keystone()
def services(self):
"""Return available services names and types.
:returns: dict, {"service_type": "service_name", ...}
"""
if "services_data" not in self.cache:
services_data = {}
available_services = self.keystone.service_catalog.get_endpoints()
for stype in available_services.keys():
if stype in consts.ServiceType:
services_data[stype] = consts.ServiceType[stype]
else:
services_data[stype] = "__unknown__"
self.cache["services_data"] = services_data
return self.cache["services_data"]
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,870
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/ui/charts/osprofilerchart.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import os
from rally.common import cfg
from rally.common import logging
from rally.common import opts
from rally.common.plugin import plugin
from rally.task.processing import charts
OPTS = {
"openstack": [
cfg.StrOpt(
"osprofiler_chart_mode",
default=None,
help="Mode of embedding OSProfiler's chart. Can be 'text' "
"(embed only trace id), 'raw' (embed raw osprofiler's native "
"report) or a path to directory (raw osprofiler's native "
"reports for each iteration will be saved separately there "
"to decrease the size of rally report itself)")
]
}
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
def _datetime_json_serialize(obj):
if hasattr(obj, "isoformat"):
return obj.isoformat()
else:
return obj
@plugin.configure(name="OSProfiler")
class OSProfilerChart(charts.OutputEmbeddedChart,
charts.OutputEmbeddedExternalChart,
charts.OutputTextArea):
"""Chart for embedding OSProfiler data."""
@classmethod
def _fetch_osprofiler_data(cls, connection_str, trace_id):
from osprofiler.drivers import base
from osprofiler import opts as osprofiler_opts
opts.register_opts(osprofiler_opts.list_opts()) # noqa
try: # noqa
engine = base.get_driver(connection_str)
except Exception:
msg = "Error while fetching OSProfiler results."
if logging.is_debug():
LOG.exception(msg)
else:
LOG.error(msg)
return None
return engine.get_report(trace_id)
@classmethod
def _generate_osprofiler_report(cls, osp_data):
from osprofiler import cmd
path = "%s/template.html" % os.path.dirname(cmd.__file__)
with open(path) as f:
html_obj = f.read()
osp_data = json.dumps(osp_data,
indent=4,
separators=(",", ": "),
default=_datetime_json_serialize)
return html_obj.replace("$DATA", osp_data).replace("$LOCAL", "false")
@classmethod
def _return_raw_response_for_complete_data(cls, data):
return charts.OutputTextArea.render_complete_data({
"title": data["title"],
"widget": "TextArea",
"data": [data["data"]["trace_id"]]
})
@classmethod
def render_complete_data(cls, data):
mode = CONF.openstack.osprofiler_chart_mode
if isinstance(data["data"]["trace_id"], list):
# NOTE(andreykurilin): it is an adoption for the format that we
# used before rally-openstack 1.5.0 .
data["data"]["trace_id"] = data["data"]["trace_id"][0]
if data["data"].get("conn_str") and mode != "text":
osp_data = cls._fetch_osprofiler_data(
data["data"]["conn_str"],
trace_id=data["data"]["trace_id"]
)
if not osp_data:
# for some reasons we failed to fetch data from OSProfiler's
# backend. in this case we can display just trace ID
return cls._return_raw_response_for_complete_data(data)
osp_report = cls._generate_osprofiler_report(osp_data)
title = "{0} : {1}".format(data["title"],
data["data"]["trace_id"])
if (mode and mode != "raw") and "workload_uuid" in data["data"]:
# NOTE(andreykurilin): we need to rework our charts plugin
# mechanism so it is available out of box
workload_uuid = data["data"]["workload_uuid"]
iteration = data["data"]["iteration"]
file_name = "w_%s-%s.html" % (workload_uuid, iteration)
path = os.path.join(mode, file_name)
with open(path, "w") as f:
f.write(osp_report)
return charts.OutputEmbeddedExternalChart.render_complete_data(
{
"title": title,
"widget": "EmbeddedChart",
"data": path
}
)
else:
return charts.OutputEmbeddedChart.render_complete_data(
{"title": title,
"widget": "EmbeddedChart",
"data": osp_report}
)
return cls._return_raw_response_for_complete_data(data)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,871
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/sahara/test_jobs.py
|
# Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally.common import cfg
from rally_openstack.task.scenarios.sahara import jobs
from tests.unit import test
CONF = cfg.CONF
BASE = "rally_openstack.task.scenarios.sahara.jobs"
class SaharaJobTestCase(test.ScenarioTestCase):
def setUp(self):
super(SaharaJobTestCase, self).setUp()
self.context = test.get_test_context()
CONF.set_override("sahara_cluster_check_interval", 0, "openstack")
CONF.set_override("sahara_job_check_interval", 0, "openstack")
@mock.patch("%s.CreateLaunchJob._run_job_execution" % BASE)
def test_create_launch_job_java(self, mock_run_job):
self.clients("sahara").jobs.create.return_value = mock.MagicMock(
id="42")
self.context.update({
"tenant": {
"sahara": {
"image": "test_image",
"mains": ["main_42"],
"libs": ["lib_42"],
"cluster": "cl_42",
"input": "in_42"
}
}
})
scenario = jobs.CreateLaunchJob(self.context)
scenario.generate_random_name = mock.Mock(
return_value="job_42")
scenario.run(job_type="java",
configs={"conf_key": "conf_val"},
job_idx=0)
self.clients("sahara").jobs.create.assert_called_once_with(
name="job_42",
type="java",
description="",
mains=["main_42"],
libs=["lib_42"]
)
mock_run_job.assert_called_once_with(
job_id="42",
cluster_id="cl_42",
input_id=None,
output_id=None,
configs={"conf_key": "conf_val"},
job_idx=0
)
@mock.patch("%s.CreateLaunchJob._run_job_execution" % BASE)
@mock.patch("%s.CreateLaunchJob._create_output_ds" % BASE,
return_value=mock.MagicMock(id="out_42"))
def test_create_launch_job_pig(self,
mock_create_output,
mock_run_job):
self.clients("sahara").jobs.create.return_value = mock.MagicMock(
id="42")
self.context.update({
"tenant": {
"sahara": {
"image": "test_image",
"mains": ["main_42"],
"libs": ["lib_42"],
"cluster": "cl_42",
"input": "in_42"
}
}
})
scenario = jobs.CreateLaunchJob(self.context)
scenario.generate_random_name = mock.Mock(return_value="job_42")
scenario.run(job_type="pig",
configs={"conf_key": "conf_val"},
job_idx=0)
self.clients("sahara").jobs.create.assert_called_once_with(
name="job_42",
type="pig",
description="",
mains=["main_42"],
libs=["lib_42"]
)
mock_run_job.assert_called_once_with(
job_id="42",
cluster_id="cl_42",
input_id="in_42",
output_id="out_42",
configs={"conf_key": "conf_val"},
job_idx=0
)
@mock.patch("%s.CreateLaunchJob._run_job_execution" % BASE)
@mock.patch("%s.CreateLaunchJob.generate_random_name" % BASE,
return_value="job_42")
def test_create_launch_job_sequence(self,
mock__random_name,
mock_run_job):
self.clients("sahara").jobs.create.return_value = mock.MagicMock(
id="42")
self.context.update({
"tenant": {
"sahara": {
"image": "test_image",
"mains": ["main_42"],
"libs": ["lib_42"],
"cluster": "cl_42",
"input": "in_42"
}
}
})
scenario = jobs.CreateLaunchJobSequence(self.context)
scenario.run(
jobs=[
{
"job_type": "java",
"configs": {"conf_key": "conf_val"}
}, {
"job_type": "java",
"configs": {"conf_key2": "conf_val2"}
}])
jobs_create_call = mock.call(name="job_42",
type="java",
description="",
mains=["main_42"],
libs=["lib_42"])
self.clients("sahara").jobs.create.assert_has_calls(
[jobs_create_call, jobs_create_call])
mock_run_job.assert_has_calls([
mock.call(job_id="42",
cluster_id="cl_42",
input_id=None,
output_id=None,
configs={"conf_key": "conf_val"},
job_idx=0),
mock.call(job_id="42",
cluster_id="cl_42",
input_id=None,
output_id=None,
configs={"conf_key2": "conf_val2"},
job_idx=1)
])
@mock.patch("%s.CreateLaunchJob.generate_random_name" % BASE,
return_value="job_42")
@mock.patch("%s.CreateLaunchJobSequenceWithScaling"
"._scale_cluster" % BASE)
@mock.patch("%s.CreateLaunchJob._run_job_execution" % BASE)
def test_create_launch_job_sequence_with_scaling(
self,
mock_run_job,
mock_create_launch_job_sequence_with_scaling__scale_cluster,
mock_create_launch_job_generate_random_name
):
self.clients("sahara").jobs.create.return_value = mock.MagicMock(
id="42")
self.clients("sahara").clusters.get.return_value = mock.MagicMock(
id="cl_42", status="active")
self.context.update({
"tenant": {
"sahara": {
"image": "test_image",
"mains": ["main_42"],
"libs": ["lib_42"],
"cluster": "cl_42",
"input": "in_42"
}
}
})
scenario = jobs.CreateLaunchJobSequenceWithScaling(self.context)
scenario.run(
jobs=[
{
"job_type": "java",
"configs": {"conf_key": "conf_val"}
}, {
"job_type": "java",
"configs": {"conf_key2": "conf_val2"}
}],
deltas=[1, -1])
jobs_create_call = mock.call(name="job_42",
type="java",
description="",
mains=["main_42"],
libs=["lib_42"])
self.clients("sahara").jobs.create.assert_has_calls(
[jobs_create_call, jobs_create_call])
je_0 = mock.call(job_id="42", cluster_id="cl_42", input_id=None,
output_id=None, configs={"conf_key": "conf_val"},
job_idx=0)
je_1 = mock.call(job_id="42", cluster_id="cl_42", input_id=None,
output_id=None,
configs={"conf_key2": "conf_val2"}, job_idx=1)
mock_run_job.assert_has_calls([je_0, je_1, je_0, je_1, je_0, je_1])
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,872
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/scenarios/designate/basic.py
|
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Endre Karlson <endre.karlson@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import random
from rally.task import validation
from rally_openstack.common import consts
from rally_openstack.task import scenario
from rally_openstack.task.scenarios.designate import utils
"""Basic scenarios for Designate."""
@validation.add("required_services",
services=[consts.Service.DESIGNATE])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(context={"cleanup@openstack": ["designate"]},
name="DesignateBasic.create_and_list_zones",
platform="openstack")
class CreateAndListZones(utils.DesignateScenario):
def run(self):
"""Create a zone and list all zones.
Measure the "openstack zone list" command performance.
If you have only 1 user in your context, you will
add 1 zone on every iteration. So you will have more
and more zone and will be able to measure the
performance of the "openstack zone list" command depending on
the number of zones owned by users.
"""
zone = self._create_zone()
self.assertTrue(zone)
list_zones = self._list_zones()
self.assertIn(zone, list_zones)
@validation.add("required_services",
services=[consts.Service.DESIGNATE])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(name="DesignateBasic.list_zones", platform="openstack")
class ListZones(utils.DesignateScenario):
def run(self):
"""List Designate zones.
This simple scenario tests the openstack zone list command by listing
all the zones.
"""
self._list_zones()
@validation.add("required_services",
services=[consts.Service.DESIGNATE])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(context={"cleanup@openstack": ["designate"]},
name="DesignateBasic.create_and_delete_zone",
platform="openstack")
class CreateAndDeleteZone(utils.DesignateScenario):
def run(self):
"""Create and then delete a zone.
Measure the performance of creating and deleting zones
with different level of load.
"""
zone = self._create_zone()
self._delete_zone(zone["id"])
@validation.add("required_services",
services=[consts.Service.DESIGNATE])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(name="DesignateBasic.list_recordsets",
platform="openstack")
class ListRecordsets(utils.DesignateScenario):
def run(self, zone_id):
"""List Designate recordsets.
This simple scenario tests the openstack recordset list command by
listing all the recordsets in a zone.
:param zone_id: Zone ID
"""
self._list_recordsets(zone_id)
@validation.add("required_services",
services=[consts.Service.DESIGNATE])
@validation.add("required_platform", platform="openstack", users=True)
@validation.add("required_contexts", contexts=("zones"))
@scenario.configure(context={"cleanup@openstack": ["designate"]},
name="DesignateBasic.create_and_delete_recordsets",
platform="openstack")
class CreateAndDeleteRecordsets(utils.DesignateScenario):
def run(self, recordsets_per_zone=5):
"""Create and then delete recordsets.
Measure the performance of creating and deleting recordsets
with different level of load.
:param recordsets_per_zone: recordsets to create pr zone.
"""
zone = random.choice(self.context["tenant"]["zones"])
recordsets = []
for i in range(recordsets_per_zone):
recordset = self._create_recordset(zone)
recordsets.append(recordset)
for recordset in recordsets:
self._delete_recordset(
zone["id"], recordset["id"])
@validation.add("required_services",
services=[consts.Service.DESIGNATE])
@validation.add("required_platform", platform="openstack", users=True)
@validation.add("required_contexts", contexts=("zones"))
@scenario.configure(context={"cleanup@openstack": ["designate"]},
name="DesignateBasic.create_and_list_recordsets",
platform="openstack")
class CreateAndListRecordsets(utils.DesignateScenario):
def run(self, recordsets_per_zone=5):
"""Create and then list recordsets.
If you have only 1 user in your context, you will
add 1 recordset on every iteration. So you will have more
and more recordsets and will be able to measure the
performance of the "openstack recordset list" command depending on
the number of zones/recordsets owned by users.
:param recordsets_per_zone: recordsets to create pr zone.
"""
zone = random.choice(self.context["tenant"]["zones"])
for i in range(recordsets_per_zone):
self._create_recordset(zone)
self._list_recordsets(zone["id"])
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,873
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/common/cfg/tempest.py
|
# Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.common import cfg
OPTS = {"openstack": [
cfg.StrOpt("img_url",
default="http://download.cirros-cloud.net/"
"0.5.2/cirros-0.5.2-x86_64-disk.img",
deprecated_group="tempest",
help="image URL"),
cfg.StrOpt("img_disk_format",
default="qcow2",
deprecated_group="tempest",
help="Image disk format to use when creating the image"),
cfg.StrOpt("img_container_format",
default="bare",
deprecated_group="tempest",
help="Image container format to use when creating the image"),
cfg.StrOpt("img_name_regex",
default="^.*(cirros|testvm).*$",
deprecated_group="tempest",
help="Regular expression for name of a public image to "
"discover it in the cloud and use it for the tests. "
"Note that when Rally is searching for the image, case "
"insensitive matching is performed. Specify nothing "
"('img_name_regex =') if you want to disable discovering. "
"In this case Rally will create needed resources by "
"itself if the values for the corresponding config "
"options are not specified in the Tempest config file"),
cfg.StrOpt("swift_operator_role",
default="member",
deprecated_group="tempest",
help="Role required for users "
"to be able to create Swift containers"),
cfg.StrOpt("swift_reseller_admin_role",
default="ResellerAdmin",
deprecated_group="tempest",
help="User role that has reseller admin"),
cfg.StrOpt("heat_stack_owner_role",
default="heat_stack_owner",
deprecated_group="tempest",
help="Role required for users "
"to be able to manage Heat stacks"),
cfg.StrOpt("heat_stack_user_role",
default="heat_stack_user",
deprecated_group="tempest",
help="Role for Heat template-defined users"),
cfg.IntOpt("flavor_ref_ram",
default="128",
deprecated_group="tempest",
help="Primary flavor RAM size used by most of the test cases"),
cfg.IntOpt("flavor_ref_alt_ram",
default="192",
deprecated_group="tempest",
help="Alternate reference flavor RAM size used by test that "
"need two flavors, like those that resize an instance"),
cfg.IntOpt("flavor_ref_disk",
default="5",
help="Primary flavor disk size in GiB used by most of the test "
"cases"),
cfg.IntOpt("flavor_ref_alt_disk",
default="5",
help="Alternate reference flavor disk size in GiB used by "
"tests that need two flavors, like those that resize an "
"instance"),
cfg.IntOpt("heat_instance_type_ram",
default="128",
deprecated_group="tempest",
help="RAM size flavor used for orchestration test cases"),
cfg.IntOpt("heat_instance_type_disk",
default="5",
deprecated_group="tempest",
help="Disk size requirement in GiB flavor used for "
"orchestration test cases"),
]}
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,874
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/designate/test_utils.py
|
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Endre Karlson <endre.karlson@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
import ddt
from rally_openstack.task.scenarios.designate import utils
from tests.unit import test
DESIGNATE_UTILS = "rally_openstack.task.scenarios.designate.utils."
@ddt.ddt
class DesignateScenarioTestCase(test.ScenarioTestCase):
def setUp(self):
super(DesignateScenarioTestCase, self).setUp()
self.domain = mock.Mock()
self.zone = mock.Mock()
self.server = mock.Mock()
self.client = self.clients("designate", version="2")
@ddt.data(
{},
{"email": "root@zone.name"})
@ddt.data(
{},
{"data": "127.0.0.1"})
# NOTE: API V2
@ddt.data(
{},
{"email": "root@zone.name"},
{"name": "example.name."},
{
"email": "root@zone.name",
"name": "example.name."
})
def test_create_zone(self, zone_data):
scenario = utils.DesignateScenario()
random_name = "foo"
scenario = utils.DesignateScenario(context=self.context)
scenario.generate_random_name = mock.Mock(return_value=random_name)
self.client.zones.create.return_value = self.zone
expected = {
"email": "root@random.name",
"name": "%s.name." % random_name,
"type_": "PRIMARY"
}
expected.update(zone_data)
# Check that the defaults / randoms are used if nothing is specified
zone = scenario._create_zone(**zone_data)
self.client.zones.create.assert_called_once_with(
description=None,
ttl=None,
**expected)
self.assertEqual(self.zone, zone)
self._test_atomic_action_timer(scenario.atomic_actions(),
"designate.create_zone")
def test_list_zones(self):
scenario = utils.DesignateScenario(context=self.context)
return_zones_list = scenario._list_zones()
self.assertEqual(self.client.zones.list.return_value,
return_zones_list)
self._test_atomic_action_timer(scenario.atomic_actions(),
"designate.list_zones")
def test_delete_zone(self):
scenario = utils.DesignateScenario(context=self.context)
zone = scenario._create_zone()
scenario._delete_zone(zone["id"])
self._test_atomic_action_timer(scenario.atomic_actions(),
"designate.delete_zone")
def test_list_recordsets(self):
scenario = utils.DesignateScenario(context=self.context)
return_recordsets_list = scenario._list_recordsets("123")
self.assertEqual(
self.client.recordsets.list.return_value,
return_recordsets_list)
self._test_atomic_action_timer(scenario.atomic_actions(),
"designate.list_recordsets")
@ddt.data(
{},
{"data": "127.0.0.1"})
def test_create_recordset(self, recordset_data):
scenario = utils.DesignateScenario()
random_name = "foo"
zone_name = "zone.name."
random_recordset_name = "%s.%s" % (random_name, zone_name)
scenario = utils.DesignateScenario(context=self.context)
scenario.generate_random_name = mock.Mock(return_value=random_name)
zone = {"name": zone_name, "id": "123"}
# Create with randoms (name and type)
scenario._create_recordset(zone)
self.client.recordsets.create.assert_called_once_with(
zone["id"],
name=random_recordset_name,
type_="A",
records=["10.0.0.1"])
self._test_atomic_action_timer(scenario.atomic_actions(),
"designate.create_recordset")
self.client.recordsets.create.reset_mock()
# Specify name
recordset = {"name": "www.zone.name.", "type_": "ASD"}
scenario._create_recordset(zone, recordset)
self.client.recordsets.create.assert_called_once_with(
zone["id"],
name="www.zone.name.",
type_="ASD",
records=["10.0.0.1"])
self.client.recordsets.create.reset_mock()
# Specify type without underscore
scenario._create_recordset(zone, {"type": "A"})
self.client.recordsets.create.assert_called_once_with(
zone["id"],
name="foo.zone.name.",
type_="A",
records=["10.0.0.1"])
def test_delete_recordset(self):
scenario = utils.DesignateScenario(context=self.context)
zone_id = mock.Mock()
recordset_id = mock.Mock()
scenario._delete_recordset(zone_id, recordset_id)
self.client.recordsets.delete.assert_called_once_with(
zone_id, recordset_id)
self._test_atomic_action_timer(scenario.atomic_actions(),
"designate.delete_recordset")
self.client.recordsets.delete.reset_mock()
scenario._delete_recordset(zone_id, recordset_id)
self.client.recordsets.delete.assert_called_once_with(
zone_id, recordset_id)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,875
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/gnocchi/test_resource.py
|
# Copyright 2017 Red Hat, Inc. <http://www.redhat.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally_openstack.task.scenarios.gnocchi import resource
from tests.unit import test
class GnocchiResourceTestCase(test.ScenarioTestCase):
def get_test_context(self):
context = super(GnocchiResourceTestCase, self).get_test_context()
context.update({
"admin": {
"user_id": "fake",
"credential": mock.MagicMock()
},
"user": {
"user_id": "fake",
"credential": mock.MagicMock()
},
"tenant": {"id": "fake"}
})
return context
def setUp(self):
super(GnocchiResourceTestCase, self).setUp()
patch = mock.patch(
"rally_openstack.common.services.gnocchi.metric.GnocchiService")
self.addCleanup(patch.stop)
self.mock_metric = patch.start()
def test_create_resource(self):
resource_service = self.mock_metric.return_value
scenario = resource.CreateResource(self.context)
scenario.generate_random_name = mock.MagicMock(return_value="name")
scenario.run(resource_type="foo")
resource_service.create_resource.assert_called_once_with(
"name", resource_type="foo")
def test_create_delete_resource(self):
resource_service = self.mock_metric.return_value
scenario = resource.CreateDeleteResource(self.context)
scenario.generate_random_name = mock.MagicMock(return_value="name")
scenario.run(resource_type="foo")
resource_service.create_resource.assert_called_once_with(
"name", resource_type="foo")
self.assertEqual(1, resource_service.delete_resource.call_count)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,876
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/contexts/nova/flavors.py
|
# Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.common import logging
from rally.common import utils as rutils
from rally.common import validation
from rally_openstack.common import consts
from rally_openstack.common import osclients
from rally_openstack.task.cleanup import manager as resource_manager
from rally_openstack.task import context
LOG = logging.getLogger(__name__)
@validation.add("required_platform", platform="openstack", admin=True)
@context.configure(name="flavors", platform="openstack", order=340)
class FlavorsGenerator(context.OpenStackContext):
"""Context creates a list of flavors."""
CONFIG_SCHEMA = {
"type": "array",
"$schema": consts.JSON_SCHEMA,
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
},
"ram": {
"type": "integer",
"minimum": 1
},
"vcpus": {
"type": "integer",
"minimum": 1
},
"disk": {
"type": "integer",
"minimum": 0
},
"swap": {
"type": "integer",
"minimum": 0
},
"ephemeral": {
"type": "integer",
"minimum": 0
},
"extra_specs": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"additionalProperties": False,
"required": ["name", "ram"]
}
}
def setup(self):
"""Create list of flavors."""
from novaclient import exceptions as nova_exceptions
self.context["flavors"] = {}
clients = osclients.Clients(self.context["admin"]["credential"])
for flavor_config in self.config:
extra_specs = flavor_config.get("extra_specs")
flavor_config = FlavorConfig(**flavor_config)
try:
flavor = clients.nova().flavors.create(**flavor_config)
except nova_exceptions.Conflict:
msg = "Using existing flavor %s" % flavor_config["name"]
if logging.is_debug():
LOG.exception(msg)
else:
LOG.warning(msg)
continue
if extra_specs:
flavor.set_keys(extra_specs)
self.context["flavors"][flavor_config["name"]] = flavor.to_dict()
LOG.debug("Created flavor with id '%s'" % flavor.id)
def cleanup(self):
"""Delete created flavors."""
mather = rutils.make_name_matcher(*[f["name"] for f in self.config])
resource_manager.cleanup(
names=["nova.flavors"],
admin=self.context["admin"],
superclass=mather,
task_id=self.get_owner_id())
class FlavorConfig(dict):
def __init__(self, name, ram, vcpus=1, disk=0, swap=0, ephemeral=0,
extra_specs=None):
"""Flavor configuration for context and flavor & image validation code.
Context code uses this code to provide default values for flavor
creation. Validation code uses this class as a Flavor instance to
check image validity against a flavor that is to be created by
the context.
:param name: name of the newly created flavor
:param ram: RAM amount for the flavor (MBs)
:param vcpus: VCPUs amount for the flavor
:param disk: disk amount for the flavor (GBs)
:param swap: swap amount for the flavor (MBs)
:param ephemeral: ephemeral disk amount for the flavor (GBs)
:param extra_specs: is ignored
"""
super(FlavorConfig, self).__init__(
name=name, ram=ram, vcpus=vcpus, disk=disk,
swap=swap, ephemeral=ephemeral)
self.__dict__.update(self)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,877
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/contexts/sahara/sahara_cluster.py
|
# Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.common import cfg
from rally.common import validation
from rally import exceptions
from rally.task import utils as bench_utils
from rally_openstack.common import consts
from rally_openstack.task.cleanup import manager as resource_manager
from rally_openstack.task import context
from rally_openstack.task.scenarios.sahara import utils
CONF = cfg.CONF
@validation.add("required_platform", platform="openstack", users=True)
@context.configure(name="sahara_cluster", platform="openstack", order=441)
class SaharaCluster(context.OpenStackContext):
"""Context class for setting up the Cluster an EDP job."""
CONFIG_SCHEMA = {
"type": "object",
"$schema": consts.JSON_SCHEMA,
"properties": {
"plugin_name": {
"type": "string"
},
"hadoop_version": {
"type": "string",
},
"workers_count": {
"type": "integer",
"minimum": 1
},
"flavor_id": {
"type": "string",
},
"master_flavor_id": {
"type": "string",
},
"worker_flavor_id": {
"type": "string",
},
"floating_ip_pool": {
"type": "string",
},
"volumes_per_node": {
"type": "integer",
"minimum": 1
},
"volumes_size": {
"type": "integer",
"minimum": 1
},
"auto_security_group": {
"type": "boolean",
},
"security_groups": {
"type": "array",
"items": {
"type": "string"
}
},
"node_configs": {
"type": "object",
"additionalProperties": True
},
"cluster_configs": {
"type": "object",
"additionalProperties": True
},
"enable_anti_affinity": {
"type": "boolean"
},
"enable_proxy": {
"type": "boolean"
},
"use_autoconfig": {
"type": "boolean"
},
},
"additionalProperties": False,
"required": ["plugin_name", "hadoop_version", "workers_count",
"master_flavor_id", "worker_flavor_id"]
}
def setup(self):
utils.init_sahara_context(self)
self.context["sahara"]["clusters"] = {}
wait_dict = {}
for user, tenant_id in self._iterate_per_tenants():
image_id = self.context["tenants"][tenant_id]["sahara"]["image"]
floating_ip_pool = self.config.get("floating_ip_pool")
temporary_context = {
"user": user,
"tenant": self.context["tenants"][tenant_id],
"task": self.context["task"],
"owner_id": self.context["owner_id"]
}
scenario = utils.SaharaScenario(context=temporary_context)
cluster = scenario._launch_cluster(
plugin_name=self.config["plugin_name"],
hadoop_version=self.config["hadoop_version"],
flavor_id=self.config.get("flavor_id"),
master_flavor_id=self.config["master_flavor_id"],
worker_flavor_id=self.config["worker_flavor_id"],
workers_count=self.config["workers_count"],
image_id=image_id,
floating_ip_pool=floating_ip_pool,
volumes_per_node=self.config.get("volumes_per_node"),
volumes_size=self.config.get("volumes_size", 1),
auto_security_group=self.config.get("auto_security_group",
True),
security_groups=self.config.get("security_groups"),
node_configs=self.config.get("node_configs"),
cluster_configs=self.config.get("cluster_configs"),
enable_anti_affinity=self.config.get("enable_anti_affinity",
False),
enable_proxy=self.config.get("enable_proxy", False),
wait_active=False,
use_autoconfig=self.config.get("use_autoconfig", True)
)
self.context["tenants"][tenant_id]["sahara"]["cluster"] = (
cluster.id)
# Need to save the client instance to poll for active status
wait_dict[cluster] = scenario.clients("sahara")
bench_utils.wait_for(
resource=wait_dict,
update_resource=self.update_clusters_dict,
is_ready=self.all_clusters_active,
timeout=CONF.openstack.sahara_cluster_create_timeout,
check_interval=CONF.openstack.sahara_cluster_check_interval)
def update_clusters_dict(self, dct):
new_dct = {}
for cluster, client in dct.items():
new_cl = client.clusters.get(cluster.id)
new_dct[new_cl] = client
return new_dct
def all_clusters_active(self, dct):
for cluster, client in dct.items():
cluster_status = cluster.status.lower()
if cluster_status == "error":
msg = ("Sahara cluster %(name)s has failed to"
" %(action)s. Reason: '%(reason)s'"
% {"name": cluster.name, "action": "start",
"reason": cluster.status_description})
raise exceptions.ContextSetupFailure(ctx_name=self.get_name(),
msg=msg)
elif cluster_status != "active":
return False
return True
def cleanup(self):
resource_manager.cleanup(names=["sahara.clusters"],
users=self.context.get("users", []),
superclass=utils.SaharaScenario,
task_id=self.get_owner_id())
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,878
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/common/credential.py
|
# Copyright 2017: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.common import logging
LOG = logging.getLogger(__file__)
class OpenStackCredential(dict):
"""Credential for OpenStack."""
def __init__(self, auth_url, username, password, tenant_name=None,
project_name=None,
permission=None,
region_name=None, endpoint_type=None,
domain_name=None, endpoint=None, user_domain_name=None,
project_domain_name=None,
https_insecure=False, https_cacert=None,
https_cert=None, https_key=None,
profiler_hmac_key=None, profiler_conn_str=None,
api_info=None, **kwargs):
if kwargs:
raise TypeError("%s" % kwargs)
# TODO(andreykurilin): deprecate permission and endpoint
if https_cert and https_key:
https_cert = (https_cert, https_key)
super(OpenStackCredential, self).__init__([
("auth_url", auth_url),
("username", username),
("password", password),
("tenant_name", (tenant_name or project_name)),
("permission", permission),
("endpoint", endpoint),
("region_name", region_name),
("endpoint_type", endpoint_type),
("domain_name", domain_name),
("user_domain_name", user_domain_name),
("project_domain_name", project_domain_name),
("https_insecure", https_insecure),
("https_cacert", https_cacert),
("https_cert", https_cert),
("profiler_hmac_key", profiler_hmac_key),
("profiler_conn_str", profiler_conn_str),
("api_info", api_info or {})
])
self._clients_cache = {}
def __getattr__(self, attr, default=None):
# TODO(andreykurilin): print warning to force everyone to use this
# object as raw dict as soon as we clean over code.
return self.get(attr, default)
def to_dict(self):
return dict(self)
def __deepcopy__(self, memodict=None):
import copy
return self.__class__(**copy.deepcopy(self.to_dict()))
# this method is mostly used by validation step. let's refactor it and
# deprecated this
def clients(self):
from rally_openstack.common import osclients
return osclients.Clients(self, cache=self._clients_cache)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,879
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/contexts/murano/murano_packages.py
|
# Copyright 2015: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import io
import os
import zipfile
from rally.common import validation
from rally import exceptions
from rally_openstack.common import consts
from rally_openstack.common import osclients
from rally_openstack.task.cleanup import manager as resource_manager
from rally_openstack.task import context
from rally_openstack.task.scenarios.murano import utils as mutils
@validation.add("required_platform", platform="openstack", users=True)
@context.configure(name="murano_packages", platform="openstack", order=401)
class PackageGenerator(context.OpenStackContext):
"""Context class for uploading applications for murano."""
CONFIG_SCHEMA = {
"type": "object",
"$schema": consts.JSON_SCHEMA,
"properties": {
"app_package": {
"type": "string",
}
},
"required": ["app_package"],
"additionalProperties": False
}
def setup(self):
is_config_app_dir = False
pckg_path = os.path.expanduser(self.config["app_package"])
if zipfile.is_zipfile(pckg_path):
zip_name = pckg_path
elif os.path.isdir(pckg_path):
is_config_app_dir = True
zip_name = mutils.pack_dir(pckg_path)
else:
msg = "There is no zip archive or directory by this path: %s"
raise exceptions.ContextSetupFailure(msg=msg % pckg_path,
ctx_name=self.get_name())
for user, tenant_id in self._iterate_per_tenants():
clients = osclients.Clients(user["credential"])
self.context["tenants"][tenant_id]["packages"] = []
if is_config_app_dir:
self.context["tenants"][tenant_id]["murano_ctx"] = zip_name
# TODO(astudenov): use self.generate_random_name()
with open(zip_name, "rb") as f:
file = io.BytesIO(f.read())
package = clients.murano().packages.create(
{"categories": ["Web"], "tags": ["tag"]},
{"file": file})
self.context["tenants"][tenant_id]["packages"].append(package)
def cleanup(self):
resource_manager.cleanup(names=["murano.packages"],
users=self.context.get("users", []),
superclass=self.__class__,
task_id=self.get_owner_id())
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,880
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/test_scenario.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
import ddt
import fixtures
from rally_openstack.common.credential import OpenStackCredential
from rally_openstack.task import scenario as base_scenario
from tests.unit import test
CREDENTIAL_WITHOUT_HMAC = OpenStackCredential(
"auth_url",
"username",
"password")
CREDENTIAL_WITH_HMAC = OpenStackCredential(
"auth_url",
"username",
"password",
profiler_hmac_key="test_profiler_hmac_key")
@ddt.ddt
class OpenStackScenarioTestCase(test.TestCase):
def setUp(self):
super(OpenStackScenarioTestCase, self).setUp()
self.osclients = fixtures.MockPatch(
"rally_openstack.common.osclients.Clients")
self.useFixture(self.osclients)
self.context = test.get_test_context()
self.context.update({"foo": "bar"})
def test_init(self):
scenario = base_scenario.OpenStackScenario(self.context)
self.assertEqual(self.context, scenario.context)
def test_init_admin_context(self):
self.context["admin"] = {"credential": mock.Mock()}
scenario = base_scenario.OpenStackScenario(self.context)
self.assertEqual(self.context, scenario.context)
self.osclients.mock.assert_called_once_with(
self.context["admin"]["credential"])
def test_init_admin_clients(self):
scenario = base_scenario.OpenStackScenario(
self.context, admin_clients="foobar")
self.assertEqual(self.context, scenario.context)
self.assertEqual("foobar", scenario._admin_clients)
def test_init_user_context(self):
user = {"credential": mock.Mock(), "tenant_id": "foo"}
self.context["users"] = [user]
self.context["tenants"] = {"foo": {"name": "bar"}}
self.context["user_choice_method"] = "random"
scenario = base_scenario.OpenStackScenario(self.context)
self.assertEqual(user, scenario.context["user"])
self.assertEqual(self.context["tenants"]["foo"],
scenario.context["tenant"])
self.osclients.mock.assert_called_once_with(user["credential"])
def test_init_clients(self):
scenario = base_scenario.OpenStackScenario(self.context,
admin_clients="spam",
clients="ham")
self.assertEqual("spam", scenario._admin_clients)
self.assertEqual("ham", scenario._clients)
def test_init_user_clients(self):
scenario = base_scenario.OpenStackScenario(
self.context, clients="foobar")
self.assertEqual(self.context, scenario.context)
self.assertEqual("foobar", scenario._clients)
@ddt.data(([], 0),
([("admin", CREDENTIAL_WITHOUT_HMAC)], 0),
([("user", CREDENTIAL_WITHOUT_HMAC)], 0),
([("admin", CREDENTIAL_WITH_HMAC)], 1),
([("user", CREDENTIAL_WITH_HMAC)], 1),
([("admin", CREDENTIAL_WITH_HMAC),
("user", CREDENTIAL_WITH_HMAC)], 1),
([("admin", CREDENTIAL_WITHOUT_HMAC),
("user", CREDENTIAL_WITH_HMAC)], 1),
([("admin", CREDENTIAL_WITH_HMAC),
("user", CREDENTIAL_WITHOUT_HMAC)], 1),
([("admin", CREDENTIAL_WITHOUT_HMAC),
("user", CREDENTIAL_WITHOUT_HMAC)], 0))
@ddt.unpack
@mock.patch("rally_openstack.task.scenario.profiler.init")
@mock.patch("rally_openstack.task.scenario.profiler.get")
def test_profiler_init(self, users_credentials,
expected_call_count,
mock_profiler_get,
mock_profiler_init):
for user, credential in users_credentials:
self.context.update({user: {"credential": credential},
"iteration": 0})
base_scenario.OpenStackScenario(self.context)
if expected_call_count:
mock_profiler_init.assert_called_once_with(
CREDENTIAL_WITH_HMAC["profiler_hmac_key"])
mock_profiler_get.assert_called_once_with()
else:
self.assertFalse(mock_profiler_init.called)
self.assertFalse(mock_profiler_get.called)
def test__choose_user_random(self):
users = [{"credential": mock.Mock(), "tenant_id": "foo"}
for _ in range(5)]
self.context["users"] = users
self.context["tenants"] = {"foo": {"name": "bar"},
"baz": {"name": "spam"}}
self.context["user_choice_method"] = "random"
scenario = base_scenario.OpenStackScenario()
scenario._choose_user(self.context)
self.assertIn("user", self.context)
self.assertIn(self.context["user"], self.context["users"])
self.assertIn("tenant", self.context)
tenant_id = self.context["user"]["tenant_id"]
self.assertEqual(self.context["tenants"][tenant_id],
self.context["tenant"])
@ddt.data((1, "0", "bar"),
(2, "0", "foo"),
(3, "1", "bar"),
(4, "1", "foo"),
(5, "0", "bar"),
(6, "0", "foo"),
(7, "1", "bar"),
(8, "1", "foo"))
@ddt.unpack
def test__choose_user_round_robin(self, iteration,
expected_user_id, expected_tenant_id):
self.context["iteration"] = iteration
self.context["user_choice_method"] = "round_robin"
self.context["users"] = []
self.context["tenants"] = {}
for tid in ("foo", "bar"):
users = [{"id": str(i), "tenant_id": tid} for i in range(2)]
self.context["users"] += users
self.context["tenants"][tid] = {"name": tid, "users": users}
scenario = base_scenario.OpenStackScenario()
scenario._choose_user(self.context)
self.assertIn("user", self.context)
self.assertIn(self.context["user"], self.context["users"])
self.assertEqual(expected_user_id, self.context["user"]["id"])
self.assertIn("tenant", self.context)
tenant_id = self.context["user"]["tenant_id"]
self.assertEqual(self.context["tenants"][tenant_id],
self.context["tenant"])
self.assertEqual(expected_tenant_id, tenant_id)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,881
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/scenarios/watcher/utils.py
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.common import cfg
from rally.task import atomic
from rally.task import utils
from rally_openstack.task import scenario
CONF = cfg.CONF
class WatcherScenario(scenario.OpenStackScenario):
"""Base class for Watcher scenarios with basic atomic actions."""
@atomic.action_timer("watcher.create_audit_template")
def _create_audit_template(self, goal_id, strategy_id):
"""Create Audit Template in DB
:param goal_id: UUID Goal
:param strategy_id: UUID Strategy
:return: Audit Template object
"""
return self.admin_clients("watcher").audit_template.create(
goal=goal_id,
strategy=strategy_id,
name=self.generate_random_name())
@atomic.action_timer("watcher.delete_audit_template")
def _delete_audit_template(self, audit_template):
"""Delete Audit Template from DB
:param audit_template: Audit Template object
"""
self.admin_clients("watcher").audit_template.delete(audit_template)
@atomic.action_timer("watcher.list_audit_templates")
def _list_audit_templates(self, name=None, goal=None, strategy=None,
limit=None, sort_key=None, sort_dir=None,
detail=False):
return self.admin_clients("watcher").audit_template.list(
name=name, goal=goal, strategy=strategy, limit=limit,
sort_key=sort_key, sort_dir=sort_dir, detail=detail)
@atomic.action_timer("watcher.create_audit")
def _create_audit(self, audit_template_uuid):
audit = self.admin_clients("watcher").audit.create(
audit_template_uuid=audit_template_uuid,
audit_type="ONESHOT")
utils.wait_for_status(
audit,
ready_statuses=["SUCCEEDED"],
failure_statuses=["FAILED"],
status_attr="state",
update_resource=utils.get_from_manager(),
timeout=CONF.openstack.watcher_audit_launch_timeout,
check_interval=CONF.openstack.watcher_audit_launch_poll_interval,
id_attr="uuid"
)
return audit
@atomic.action_timer("watcher.delete_audit")
def _delete_audit(self, audit):
self.admin_clients("watcher").audit.delete(audit.uuid)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,882
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/types.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
import operator
import re
from rally.common import logging
from rally.common.plugin import plugin
from rally import exceptions
from rally.task import types
from rally_openstack.common import osclients
from rally_openstack.common.services.image import image
from rally_openstack.common.services.storage import block
LOG = logging.getLogger(__name__)
configure = plugin.configure
class OpenStackResourceType(types.ResourceType):
"""A base class for OpenStack ResourceTypes plugins with help-methods"""
def __init__(self, context=None, cache=None):
super(OpenStackResourceType, self).__init__(context, cache)
self._clients = None
if self._context.get("admin"):
self._clients = osclients.Clients(
self._context["admin"]["credential"])
elif self._context.get("users"):
self._clients = osclients.Clients(
self._context["users"][0]["credential"])
def _find_resource(self, resource_spec, resources):
"""Return the resource whose name matches the pattern.
.. note:: This method is a modified version of
`rally.task.types.obj_from_name`. The difference is supporting the
case of returning the latest version of resource in case of
`accurate=False` option.
:param resource_spec: resource specification to find.
Expected keys:
* name - The exact name of resource to search. If no exact match
and value of *accurate* key is False (default behaviour), name
will be interpreted as a regexp
* regexp - a regexp of resource name to match. If several resources
match and value of *accurate* key is False (default behaviour),
the latest resource will be returned.
:param resources: iterable containing all resources
:raises InvalidScenarioArgument: if the pattern does
not match anything.
:returns: resource object mapped to `name` or `regex`
"""
if "name" in resource_spec:
# In a case of pattern string exactly matches resource name
matching_exact = [resource for resource in resources
if resource.name == resource_spec["name"]]
if len(matching_exact) == 1:
return matching_exact[0]
elif len(matching_exact) > 1:
raise exceptions.InvalidScenarioArgument(
"%(typename)s with name '%(pattern)s' "
"is ambiguous, possible matches "
"by id: %(ids)s" % {
"typename": self.get_name().title(),
"pattern": resource_spec["name"],
"ids": ", ".join(map(operator.attrgetter("id"),
matching_exact))})
if resource_spec.get("accurate", False):
raise exceptions.InvalidScenarioArgument(
"%(typename)s with name '%(name)s' not found" % {
"typename": self.get_name().title(),
"name": resource_spec["name"]})
# Else look up as regex
patternstr = resource_spec["name"]
elif "regex" in resource_spec:
patternstr = resource_spec["regex"]
else:
raise exceptions.InvalidScenarioArgument(
"%(typename)s 'id', 'name', or 'regex' not found "
"in '%(resource_spec)s' " % {
"typename": self.get_name().title(),
"resource_spec": resource_spec})
pattern = re.compile(patternstr)
matching = [resource for resource in resources
if re.search(pattern, resource.name or "")]
if not matching:
raise exceptions.InvalidScenarioArgument(
"%(typename)s with pattern '%(pattern)s' not found" % {
"typename": self.get_name().title(),
"pattern": pattern.pattern})
elif len(matching) > 1:
if not resource_spec.get("accurate", False):
return sorted(matching, key=lambda o: o.name or "")[-1]
raise exceptions.InvalidScenarioArgument(
"%(typename)s with name '%(pattern)s' is ambiguous, possible "
"matches by id: %(ids)s" % {
"typename": self.get_name().title(),
"pattern": pattern.pattern,
"ids": ", ".join(map(operator.attrgetter("id"),
matching))})
return matching[0]
@plugin.configure(name="nova_flavor")
class Flavor(OpenStackResourceType):
"""Find Nova's flavor ID by name or regexp."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
if not resource_id:
novaclient = self._clients.nova()
resource_id = types._id_from_name(
resource_config=resource_spec,
resources=novaclient.flavors.list(),
typename="flavor")
return resource_id
@plugin.configure(name="glance_image")
class GlanceImage(OpenStackResourceType):
"""Find Glance's image ID by name or regexp."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
list_kwargs = resource_spec.get("list_kwargs", {})
if not resource_id:
cache_id = hash(frozenset(list_kwargs.items()))
if cache_id not in self._cache:
glance = image.Image(self._clients)
self._cache[cache_id] = glance.list_images(**list_kwargs)
images = self._cache[cache_id]
resource = self._find_resource(resource_spec, images)
return resource.id
return resource_id
@plugin.configure(name="glance_image_args")
class GlanceImageArguments(OpenStackResourceType):
"""Process Glance image create options to look similar in case of V1/V2."""
def pre_process(self, resource_spec, config):
resource_spec = copy.deepcopy(resource_spec)
if "is_public" in resource_spec:
if "visibility" in resource_spec:
resource_spec.pop("is_public")
else:
visibility = ("public" if resource_spec.pop("is_public")
else "private")
resource_spec["visibility"] = visibility
return resource_spec
@plugin.configure(name="ec2_image")
class EC2Image(OpenStackResourceType):
"""Find EC2 image ID."""
def pre_process(self, resource_spec, config):
if "name" not in resource_spec and "regex" not in resource_spec:
# NOTE(wtakase): gets resource name from OpenStack id
glanceclient = self._clients.glance()
resource_name = types._name_from_id(
resource_config=resource_spec,
resources=list(glanceclient.images.list()),
typename="image")
resource_spec["name"] = resource_name
# NOTE(wtakase): gets EC2 resource id from name or regex
ec2client = self._clients.ec2()
resource_ec2_id = types._id_from_name(
resource_config=resource_spec,
resources=list(ec2client.get_all_images()),
typename="ec2_image")
return resource_ec2_id
@plugin.configure(name="cinder_volume_type")
class VolumeType(OpenStackResourceType):
"""Find Cinder volume type ID by name or regexp."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
if not resource_id:
cinder = block.BlockStorage(self._clients)
resource_id = types._id_from_name(
resource_config=resource_spec,
resources=cinder.list_types(),
typename="volume_type")
return resource_id
@plugin.configure(name="neutron_network")
class NeutronNetwork(OpenStackResourceType):
"""Find Neutron network ID by it's name."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
if resource_id:
return resource_id
else:
neutronclient = self._clients.neutron()
for net in neutronclient.list_networks()["networks"]:
if net["name"] == resource_spec.get("name"):
return net["id"]
raise exceptions.InvalidScenarioArgument(
"Neutron network with name '{name}' not found".format(
name=resource_spec.get("name")))
@plugin.configure(name="watcher_strategy")
class WatcherStrategy(OpenStackResourceType):
"""Find Watcher strategy ID by it's name."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
if not resource_id:
watcherclient = self._clients.watcher()
resource_id = types._id_from_name(
resource_config=resource_spec,
resources=[watcherclient.strategy.get(
resource_spec.get("name"))],
typename="strategy",
id_attr="uuid")
return resource_id
@plugin.configure(name="watcher_goal")
class WatcherGoal(OpenStackResourceType):
"""Find Watcher goal ID by it's name."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
if not resource_id:
watcherclient = self._clients.watcher()
resource_id = types._id_from_name(
resource_config=resource_spec,
resources=[watcherclient.goal.get(resource_spec.get("name"))],
typename="goal",
id_attr="uuid")
return resource_id
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,883
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/cinder/test_volume_backups.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally_openstack.task.scenarios.cinder import volume_backups
from tests.unit import test
class CinderBackupTestCase(test.ScenarioTestCase):
def setUp(self):
super(CinderBackupTestCase, self).setUp()
patch = mock.patch(
"rally_openstack.common.services.storage.block.BlockStorage")
self.addCleanup(patch.stop)
self.mock_cinder = patch.start()
def _get_context(self):
context = test.get_test_context()
context.update({
"admin": {
"id": "fake_user_id",
"credential": mock.MagicMock()
},
"user": {"id": "fake_user_id",
"credential": mock.MagicMock()},
"tenant": {"id": "fake", "name": "fake"}})
return context
def test_create_incremental_volume_backup(self):
mock_service = self.mock_cinder.return_value
scenario = volume_backups.CreateIncrementalVolumeBackup(
self._get_context())
volume_kwargs = {"some_var": "zaq"}
backup_kwargs = {"incremental": True}
scenario.run(1, do_delete=True, create_volume_kwargs=volume_kwargs,
create_backup_kwargs=backup_kwargs)
self.assertEqual(2, mock_service.create_backup.call_count)
mock_service.create_volume.assert_called_once_with(1, **volume_kwargs)
mock_service.delete_backup.assert_has_calls(
mock_service.create_backup.return_value)
mock_service.delete_volume.assert_called_once_with(
mock_service.create_volume.return_value)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,884
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/scenarios/vm/workloads/siege.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import re
import subprocess
import sys
import tempfile
SIEGE_RE = re.compile(r"^(Throughput|Transaction rate):\s+(\d+\.\d+)\s+.*")
def get_instances():
outputs = json.load(sys.stdin)
for output in outputs:
if output["output_key"] == "wp_nodes":
for node in output["output_value"].values():
yield node["wordpress-network"][0]
def generate_urls_list(instances):
urls = tempfile.NamedTemporaryFile(delete=False)
with urls:
for inst in instances:
for i in range(1, 1000):
urls.write("http://%s/wordpress/index.php/%d/\n" % (inst, i))
return urls.name
def run():
instances = list(get_instances())
urls = generate_urls_list(instances)
out = subprocess.check_output(
["siege", "-q", "-t", "60S", "-b", "-f", urls],
stderr=subprocess.STDOUT)
for line in out.splitlines():
m = SIEGE_RE.match(line)
if m:
sys.stdout.write("%s:%s\n" % m.groups())
if __name__ == "__main__":
sys.exit(run())
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,885
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/contexts/vm/image_command_customizer.py
|
# Copyright 2015: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
from rally.common import validation
from rally import exceptions
from rally_openstack.task import context
from rally_openstack.task.contexts.vm import custom_image
from rally_openstack.task.scenarios.vm import utils as vm_utils
@validation.add("required_platform", platform="openstack", users=True)
@context.configure(name="image_command_customizer", platform="openstack",
order=501)
class ImageCommandCustomizerContext(custom_image.BaseCustomImageGenerator):
"""Context class for generating image customized by a command execution.
Run a command specified by configuration to prepare image.
Use this script e.g. to download and install something.
"""
CONFIG_SCHEMA = copy.deepcopy(
custom_image.BaseCustomImageGenerator.CONFIG_SCHEMA)
CONFIG_SCHEMA["definitions"] = {
"stringOrStringList": {
"anyOf": [
{"type": "string", "description": "just a string"},
{
"type": "array", "description": "just a list of strings",
"items": {"type": "string"}
}
]
},
"scriptFile": {
"type": "object",
"properties": {
"script_file": {"$ref": "#/definitions/stringOrStringList"},
"interpreter": {"$ref": "#/definitions/stringOrStringList"},
"command_args": {"$ref": "#/definitions/stringOrStringList"}
},
"required": ["script_file", "interpreter"],
"additionalProperties": False,
},
"scriptInline": {
"type": "object",
"properties": {
"script_inline": {"type": "string"},
"interpreter": {"$ref": "#/definitions/stringOrStringList"},
"command_args": {"$ref": "#/definitions/stringOrStringList"}
},
"required": ["script_inline", "interpreter"],
"additionalProperties": False,
},
"commandPath": {
"type": "object",
"properties": {
"remote_path": {"$ref": "#/definitions/stringOrStringList"},
"local_path": {"type": "string"},
"command_args": {"$ref": "#/definitions/stringOrStringList"}
},
"required": ["remote_path"],
"additionalProperties": False,
},
"commandDict": {
"oneOf": [
{"$ref": "#/definitions/scriptFile"},
{"$ref": "#/definitions/scriptInline"},
{"$ref": "#/definitions/commandPath"},
],
}
}
CONFIG_SCHEMA["properties"]["command"] = {
"$ref": "#/definitions/commandDict"
}
def _customize_image(self, server, fip, user):
code, out, err = vm_utils.VMScenario(self.context)._run_command(
fip["ip"], self.config["port"],
self.config["username"], self.config.get("password"),
command=self.config["command"],
pkey=user["keypair"]["private"])
if code:
raise exceptions.ScriptError(
message="Command `%(command)s' execution failed,"
" code %(code)d:\n"
"STDOUT:\n============================\n"
"%(out)s\n"
"STDERR:\n============================\n"
"%(err)s\n"
"============================\n"
% {"command": self.config["command"], "code": code,
"out": out, "err": err})
return code, out, err
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,886
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/contexts/cinder/test_volume_types.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally_openstack.task.contexts.cinder import volume_types
from tests.unit import test
CTX = "rally_openstack.task.contexts.cinder.volume_types"
SERVICE = "rally_openstack.common.services.storage"
class VolumeTypeGeneratorTestCase(test.ContextTestCase):
def setUp(self):
super(VolumeTypeGeneratorTestCase, self).setUp()
self.context.update({"admin": {"credential": "admin_creds"}})
@mock.patch("%s.block.BlockStorage" % SERVICE)
def test_setup(self, mock_block_storage):
self.context.update({"config": {"volume_types": ["foo", "bar"]}})
mock_service = mock_block_storage.return_value
mock_service.create_volume_type.side_effect = (
mock.Mock(id="foo-id"), mock.Mock(id="bar-id"))
vtype_ctx = volume_types.VolumeTypeGenerator(self.context)
vtype_ctx.setup()
mock_service.create_volume_type.assert_has_calls(
[mock.call("foo"), mock.call("bar")])
self.assertEqual(self.context["volume_types"],
[{"id": "foo-id", "name": "foo"},
{"id": "bar-id", "name": "bar"}])
@mock.patch("%s.utils.make_name_matcher" % CTX)
@mock.patch("%s.resource_manager.cleanup" % CTX)
def test_cleanup(self, mock_cleanup, mock_make_name_matcher):
self.context.update({
"config": {"volume_types": ["foo", "bar"]}})
vtype_ctx = volume_types.VolumeTypeGenerator(self.context)
vtype_ctx.cleanup()
mock_cleanup.assert_called_once_with(
names=["cinder.volume_types"],
admin=self.context["admin"],
superclass=mock_make_name_matcher.return_value,
task_id=vtype_ctx.get_owner_id())
mock_make_name_matcher.assert_called_once_with("foo", "bar")
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,887
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/scenario.py
|
# Copyright 2015: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import functools
import random
from osprofiler import profiler
from rally.common import cfg
from rally.common.plugin import plugin
from rally.task import context
from rally.task import scenario
from rally_openstack.common import osclients
configure = functools.partial(scenario.configure, platform="openstack")
CONF = cfg.CONF
@context.add_default_context("users@openstack", {})
@plugin.default_meta(inherit=True)
class OpenStackScenario(scenario.Scenario):
"""Base class for all OpenStack scenarios."""
def __init__(self, context=None, admin_clients=None, clients=None):
super(OpenStackScenario, self).__init__(context)
if context:
if admin_clients is None and "admin" in context:
self._admin_clients = osclients.Clients(
context["admin"]["credential"])
if clients is None:
if "users" in context and "user" not in context:
self._choose_user(context)
if "user" in context:
self._clients = osclients.Clients(
context["user"]["credential"])
if admin_clients:
self._admin_clients = admin_clients
if clients:
self._clients = clients
self._init_profiler(context)
def _choose_user(self, context):
"""Choose one user from users context
We are choosing on each iteration one user
"""
if context["user_choice_method"] == "random":
user = random.choice(context["users"])
tenant = context["tenants"][user["tenant_id"]]
else:
# Second and last case - 'round_robin'.
tenants_amount = len(context["tenants"])
# NOTE(amaretskiy): iteration is subtracted by `1' because it
# starts from `1' but we count from `0'
iteration = context["iteration"] - 1
tenant_index = int(iteration % tenants_amount)
tenant_id = sorted(context["tenants"].keys())[tenant_index]
tenant = context["tenants"][tenant_id]
users = context["tenants"][tenant_id]["users"]
user_index = int((iteration / tenants_amount) % len(users))
user = users[user_index]
context["user"], context["tenant"] = user, tenant
def clients(self, client_type, version=None):
"""Returns a python openstack client of the requested type.
Only one non-admin user is used per every run of scenario.
:param client_type: Client type ("nova"/"glance" etc.)
:param version: client version ("1"/"2" etc.)
:returns: Standard python OpenStack client instance
"""
client = getattr(self._clients, client_type)
return client(version) if version is not None else client()
def admin_clients(self, client_type, version=None):
"""Returns a python admin openstack client of the requested type.
:param client_type: Client type ("nova"/"glance" etc.)
:param version: client version ("1"/"2" etc.)
:returns: Python openstack client object
"""
client = getattr(self._admin_clients, client_type)
return client(version) if version is not None else client()
def _init_profiler(self, context):
"""Inits the profiler."""
if not CONF.openstack.enable_profiler:
return
# False statement here means that Scenario class is used outside the
# runner as some kind of utils
if context is not None and "iteration" in context:
profiler_hmac_key = None
profiler_conn_str = None
if context.get("admin"):
cred = context["admin"]["credential"]
if cred.profiler_hmac_key is not None:
profiler_hmac_key = cred.profiler_hmac_key
profiler_conn_str = cred.profiler_conn_str
if context.get("user"):
cred = context["user"]["credential"]
if cred.profiler_hmac_key is not None:
profiler_hmac_key = cred.profiler_hmac_key
profiler_conn_str = cred.profiler_conn_str
if profiler_hmac_key is None:
return
profiler.init(profiler_hmac_key)
trace_id = profiler.get().get_base_id()
complete_data = {"title": "OSProfiler Trace-ID",
"chart_plugin": "OSProfiler",
"data": {"trace_id": trace_id,
"conn_str": profiler_conn_str,
"taskID": context["task"]["uuid"],
"workload_uuid": context["owner_id"],
"iteration": context["iteration"]}}
self.add_output(complete=complete_data)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,888
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/common/test_validators.py
|
# Copyright 2017: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
import ddt
from unittest import mock
from glanceclient import exc as glance_exc
from novaclient import exceptions as nova_exc
from rally import exceptions
from rally_openstack.common import consts
from rally_openstack.common import validators
from tests.unit import test
PATH = "rally_openstack.common.validators"
context = {
"admin": mock.MagicMock(),
"users": [mock.MagicMock()],
}
config = dict(args={"image": {"id": "fake_id",
"min_ram": 10,
"size": 1024 ** 3,
"min_disk": 10.0 * (1024 ** 3),
"image_name": "foo_image"},
"flavor": {"id": "fake_flavor_id",
"name": "test"},
"foo_image": {"id": "fake_image_id"}
},
context={"images": {"image_name": "foo_image"},
"api_versions@openstack": mock.MagicMock(),
"zones": {"set_zone_in_network": True}}
)
@mock.patch("rally_openstack.task.contexts.keystone.roles.RoleGenerator")
def test_with_roles_ctx(mock_role_generator):
@validators.with_roles_ctx()
def func(config, context):
pass
config = {"contexts": {}}
context = {"admin": {"credential": mock.MagicMock()},
"task": mock.MagicMock()}
func(config, context)
mock_role_generator().setup.assert_not_called()
config = {"contexts": {"roles": "admin"}}
func(config, context)
mock_role_generator().setup.assert_called_once_with()
class RequiredOpenStackValidatorTestCase(test.TestCase):
def validate(self):
validator = validators.RequiredOpenStackValidator(admin=True)
validator.validate(
{"platforms": {"openstack": {"admin": "foo"}}}, {}, None, None)
validator = validators.RequiredOpenStackValidator(users=True)
validator.validate(
{"platforms": {"openstack": {"admin": "foo"}}}, {}, None, None)
validator = validators.RequiredOpenStackValidator(users=True)
validator.validate(
{"platforms": {"openstack": {"users": ["foo"]}}}, {}, None, None)
def test_validate_failed(self):
# case #1: wrong configuration of validator
validator = validators.RequiredOpenStackValidator()
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, {}, {}, None, None)
self.assertEqual(
"You should specify admin=True or users=True or both.",
e.message)
# case #2: admin is not present
validator = validators.RequiredOpenStackValidator(admin=True)
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate,
{"platforms": {"openstack": {}}}, {}, None, None)
self.assertEqual("No admin credentials for openstack",
e.message)
# case #3: users are not present
validator = validators.RequiredOpenStackValidator(users=True)
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate,
{"platforms": {"openstack": {}}}, {}, None, None)
self.assertEqual("No user credentials for openstack",
e.message)
@ddt.ddt
class ImageExistsValidatorTestCase(test.TestCase):
def setUp(self):
super(ImageExistsValidatorTestCase, self).setUp()
self.validator = validators.ImageExistsValidator("image", True)
self.config = copy.deepcopy(config)
self.context = copy.deepcopy(context)
@ddt.unpack
@ddt.data(
{"param_name": "fake_param", "nullable": True, "err_msg": None},
{"param_name": "fake_param", "nullable": False,
"err_msg": "Parameter fake_param is not specified."},
{"param_name": "image", "nullable": True, "err_msg": None},
)
def test_validator(self, param_name, nullable, err_msg, ex=False):
validator = validators.ImageExistsValidator(param_name,
nullable)
clients = self.context["users"][0].clients.return_value
clients.glance().images.get = mock.Mock()
if ex:
clients.glance().images.get.side_effect = ex
if err_msg:
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, self.config, None, None)
self.assertEqual(err_msg, e.message)
else:
result = validator.validate(self.config, self.context, None,
None)
self.assertIsNone(result)
def test_validator_image_from_context(self):
config = {
"args": {"image": {"regex": r"^foo$"}},
"contexts": {"images": {"image_name": "foo"}}}
self.validator.validate(self.context, config, None, None)
@mock.patch("%s.openstack_types.GlanceImage" % PATH)
def test_validator_image_not_in_context(self, mock_glance_image):
mock_glance_image.return_value.pre_process.return_value = "image_id"
config = {
"args": {"image": "fake_image"},
"contexts": {
"images": {"fake_image_name": "foo"}}}
clients = self.context[
"users"][0]["credential"].clients.return_value
clients.glance().images.get = mock.Mock()
result = self.validator.validate(self.context, config, None, None)
self.assertIsNone(result)
mock_glance_image.assert_called_once_with(
context={"admin": {
"credential": self.context["users"][0]["credential"]}})
mock_glance_image.return_value.pre_process.assert_called_once_with(
config["args"]["image"], config={})
clients.glance().images.get.assert_called_with("image_id")
exs = [exceptions.InvalidScenarioArgument(),
glance_exc.HTTPNotFound()]
for ex in exs:
clients.glance().images.get.side_effect = ex
e = self.assertRaises(
validators.validation.ValidationError,
self.validator.validate, self.context, config, None, None)
self.assertEqual("Image 'fake_image' not found", e.message)
@ddt.ddt
class ExternalNetworkExistsValidatorTestCase(test.TestCase):
def setUp(self):
super(ExternalNetworkExistsValidatorTestCase, self).setUp()
self.validator = validators.ExternalNetworkExistsValidator("net")
self.config = copy.deepcopy(config)
self.context = copy.deepcopy(context)
@ddt.unpack
@ddt.data(
{"foo_conf": {}},
{"foo_conf": {"args": {"net": "custom"}}},
{"foo_conf": {"args": {"net": "non_exist"}},
"err_msg": "External (floating) network with name non_exist"
" not found by user {}. Available networks:"
" [{}, {}]"},
{"foo_conf": {"args": {"net": "custom"}},
"net1_name": {"name": {"net": "public"}},
"net2_name": {"name": {"net": "custom"}},
"err_msg": "External (floating) network with name custom"
" not found by user {}. Available networks:"
" [{}, {}]"}
)
def test_validator(self, foo_conf, net1_name="public", net2_name="custom",
err_msg=""):
user = self.context["users"][0]
net1 = {"name": net1_name, "router:external": True}
net2 = {"name": net2_name, "router:external": True}
user["credential"].clients().neutron().list_networks.return_value = {
"networks": [net1, net2]}
if err_msg:
e = self.assertRaises(
validators.validation.ValidationError,
self.validator.validate, self.context, foo_conf,
None, None)
self.assertEqual(
err_msg.format(user["credential"].username, net1, net2),
e.message)
else:
result = self.validator.validate(self.context, foo_conf,
None, None)
self.assertIsNone(result, "Unexpected result '%s'" % result)
@ddt.ddt
class RequiredNeutronExtensionsValidatorTestCase(test.TestCase):
def setUp(self):
super(RequiredNeutronExtensionsValidatorTestCase, self).setUp()
self.config = copy.deepcopy(config)
self.context = copy.deepcopy(context)
def test_validator(self):
validator = validators.RequiredNeutronExtensionsValidator(
"existing_extension")
clients = self.context["users"][0]["credential"].clients()
clients.neutron().list_extensions.return_value = {
"extensions": [{"alias": "existing_extension"}]}
validator.validate(self.context, {}, None, None)
def test_validator_failed(self):
err_msg = "Neutron extension absent_extension is not configured"
validator = validators.RequiredNeutronExtensionsValidator(
"absent_extension")
clients = self.context["users"][0]["credential"].clients()
clients.neutron().list_extensions.return_value = {
"extensions": [{"alias": "existing_extension"}]}
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, {}, None, None)
self.assertEqual(err_msg, e.message)
class FlavorExistsValidatorTestCase(test.TestCase):
def setUp(self):
super(FlavorExistsValidatorTestCase, self).setUp()
self.validator = validators.FlavorExistsValidator(
param_name="foo_flavor")
self.config = copy.deepcopy(config)
self.context = copy.deepcopy(context)
def test__get_validated_flavor_wrong_value_in_config(self):
e = self.assertRaises(
validators.validation.ValidationError,
self.validator._get_validated_flavor, self.config,
mock.MagicMock(), "foo_flavor")
self.assertEqual("Parameter foo_flavor is not specified.",
e.message)
@mock.patch("%s.openstack_types.Flavor" % PATH)
def test__get_validated_flavor(self, mock_flavor):
mock_flavor.return_value.pre_process.return_value = "flavor_id"
clients = mock.Mock()
clients.nova().flavors.get.return_value = "flavor"
result = self.validator._get_validated_flavor(self.config,
clients,
"flavor")
self.assertEqual("flavor", result)
mock_flavor.assert_called_once_with(
context={"admin": {"credential": clients.credential}}
)
mock_flavor_obj = mock_flavor.return_value
mock_flavor_obj.pre_process.assert_called_once_with(
self.config["args"]["flavor"], config={})
clients.nova().flavors.get.assert_called_once_with(flavor="flavor_id")
mock_flavor_obj.pre_process.reset_mock()
clients.side_effect = exceptions.InvalidScenarioArgument("")
result = self.validator._get_validated_flavor(
self.config, clients, "flavor")
self.assertEqual("flavor", result)
mock_flavor_obj.pre_process.assert_called_once_with(
self.config["args"]["flavor"], config={})
clients.nova().flavors.get.assert_called_with(flavor="flavor_id")
@mock.patch("%s.openstack_types.Flavor" % PATH)
def test__get_validated_flavor_not_found(self, mock_flavor):
mock_flavor.return_value.pre_process.return_value = "flavor_id"
clients = mock.MagicMock()
clients.nova().flavors.get.side_effect = nova_exc.NotFound("")
e = self.assertRaises(
validators.validation.ValidationError,
self.validator._get_validated_flavor,
self.config, clients, "flavor")
self.assertEqual("Flavor '%s' not found" %
self.config["args"]["flavor"],
e.message)
mock_flavor_obj = mock_flavor.return_value
mock_flavor_obj.pre_process.assert_called_once_with(
self.config["args"]["flavor"], config={})
@mock.patch("%s.types.obj_from_name" % PATH)
@mock.patch("%s.flavors_ctx.FlavorConfig" % PATH)
def test__get_flavor_from_context(self, mock_flavor_config,
mock_obj_from_name):
config = {
"contexts": {"images": {"fake_parameter_name": "foo_image"}}}
e = self.assertRaises(
validators.validation.ValidationError,
self.validator._get_flavor_from_context,
config, "foo_flavor")
self.assertEqual("No flavors context", e.message)
config = {"contexts": {"images": {"fake_parameter_name": "foo_image"},
"flavors": [{"flavor1": "fake_flavor1"}]}}
result = self.validator._get_flavor_from_context(config, "foo_flavor")
self.assertEqual("<context flavor: %s>" % result.name, result.id)
def test_validate(self):
expected_e = validators.validation.ValidationError("fpp")
self.validator._get_validated_flavor = mock.Mock(
side_effect=expected_e)
config = {}
ctx = mock.MagicMock()
actual_e = self.assertRaises(
validators.validation.ValidationError,
self.validator.validate, ctx, config, None, None)
self.assertEqual(expected_e, actual_e)
self.validator._get_validated_flavor.assert_called_once_with(
config=config,
clients=ctx["users"][0]["credential"].clients(),
param_name=self.validator.param_name)
@ddt.ddt
class ImageValidOnFlavorValidatorTestCase(test.TestCase):
def setUp(self):
super(ImageValidOnFlavorValidatorTestCase, self).setUp()
self.validator = validators.ImageValidOnFlavorValidator("foo_flavor",
"image")
self.config = copy.deepcopy(config)
self.context = copy.deepcopy(context)
@ddt.data(
{"validate_disk": True, "flavor_disk": True},
{"validate_disk": False, "flavor_disk": True},
{"validate_disk": False, "flavor_disk": False}
)
@ddt.unpack
def test_validate(self, validate_disk, flavor_disk):
validator = validators.ImageValidOnFlavorValidator(
flavor_param="foo_flavor",
image_param="image",
fail_on_404_image=False,
validate_disk=validate_disk)
min_ram = 2048
disk = 10
fake_image = {"min_ram": min_ram,
"size": disk * (1024 ** 3),
"min_disk": disk}
fake_flavor = mock.Mock(disk=None, ram=min_ram * 2)
if flavor_disk:
fake_flavor.disk = disk * 2
validator._get_validated_flavor = mock.Mock(
return_value=fake_flavor)
# case 1: no image, but it is ok, since fail_on_404_image is False
validator._get_validated_image = mock.Mock(
side_effect=validators.validation.ValidationError("!!!"))
validator.validate(self.context, {}, None, None)
# case 2: there is an image
validator._get_validated_image = mock.Mock(
return_value=fake_image)
validator.validate(self.context, {}, None, None)
# case 3: check caching of the flavor
self.context["users"].append(self.context["users"][0])
validator._get_validated_image.reset_mock()
validator._get_validated_flavor.reset_mock()
validator.validate(self.context, {}, None, None)
self.assertEqual(1, validator._get_validated_flavor.call_count)
self.assertEqual(2, validator._get_validated_image.call_count)
def test_validate_failed(self):
validator = validators.ImageValidOnFlavorValidator(
flavor_param="foo_flavor",
image_param="image",
fail_on_404_image=True,
validate_disk=True)
min_ram = 2048
disk = 10
fake_flavor = mock.Mock(disk=disk, ram=min_ram)
fake_flavor.id = "flavor_id"
validator._get_validated_flavor = mock.Mock(
return_value=fake_flavor)
# case 1: there is no image and fail_on_404_image flag is True
expected_e = validators.validation.ValidationError("!!!")
validator._get_validated_image = mock.Mock(
side_effect=expected_e)
actual_e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, {}, None, None
)
self.assertEqual(expected_e, actual_e)
# case 2: there is no right flavor
expected_e = KeyError("Ooops")
validator._get_validated_flavor.side_effect = expected_e
actual_e = self.assertRaises(
KeyError,
validator.validate, self.context, {}, None, None
)
self.assertEqual(expected_e, actual_e)
# case 3: ram of a flavor is less than min_ram of an image
validator._get_validated_flavor = mock.Mock(
return_value=fake_flavor)
fake_image = {"min_ram": min_ram * 2, "id": "image_id"}
validator._get_validated_image = mock.Mock(
return_value=fake_image)
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, {}, None, None
)
self.assertEqual(
"The memory size for flavor 'flavor_id' is too small for "
"requested image 'image_id'.", e.message)
# case 4: disk of a flavor is less than size of an image
fake_image = {"min_ram": min_ram / 2.0,
"size": disk * (1024 ** 3) * 3,
"id": "image_id"}
validator._get_validated_image = mock.Mock(
return_value=fake_image)
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, {}, None, None
)
self.assertEqual(
"The disk size for flavor 'flavor_id' is too small for "
"requested image 'image_id'.", e.message)
# case 5: disk of a flavor is less than size of an image
fake_image = {"min_ram": min_ram,
"size": disk * (1024 ** 3),
"min_disk": disk * 2,
"id": "image_id"}
validator._get_validated_image = mock.Mock(
return_value=fake_image)
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, {}, None, None
)
self.assertEqual(
"The minimal disk size for flavor 'flavor_id' is too small for "
"requested image 'image_id'.", e.message)
# case 6: _get_validated_image raises an unexpected error,
# fail_on_404_image=False should not work in this case
expected_e = KeyError("Foo!")
validator = validators.ImageValidOnFlavorValidator(
flavor_param="foo_flavor",
image_param="image",
fail_on_404_image=False,
validate_disk=True)
validator._get_validated_image = mock.Mock(
side_effect=expected_e)
validator._get_validated_flavor = mock.Mock()
actual_e = self.assertRaises(
KeyError,
validator.validate, self.context, {}, None, None
)
self.assertEqual(expected_e, actual_e)
@mock.patch("%s.openstack_types.GlanceImage" % PATH)
def test__get_validated_image(self, mock_glance_image):
mock_glance_image.return_value.pre_process.return_value = "image_id"
image = {
"size": 0,
"min_ram": 0,
"min_disk": 0
}
# Get image name from context
result = self.validator._get_validated_image({
"args": {
"image": {"regex": r"^foo$"}},
"contexts": {
"images": {"image_name": "foo"}}},
mock.Mock(), "image")
self.assertEqual(image, result)
clients = mock.Mock()
clients.glance().images.get().to_dict.return_value = {
"image": "image_id"}
image["image"] = "image_id"
result = self.validator._get_validated_image(self.config,
clients,
"image")
self.assertEqual(image, result)
mock_glance_image.assert_called_once_with(
context={"admin": {"credential": clients.credential}})
mock_glance_image.return_value.pre_process.assert_called_once_with(
config["args"]["image"], config={})
clients.glance().images.get.assert_called_with("image_id")
@mock.patch("%s.openstack_types.GlanceImage" % PATH)
def test__get_validated_image_incorrect_param(self, mock_glance_image):
mock_glance_image.return_value.pre_process.return_value = "image_id"
# Wrong 'param_name'
e = self.assertRaises(
validators.validation.ValidationError,
self.validator._get_validated_image, self.config,
mock.Mock(), "fake_param")
self.assertEqual("Parameter fake_param is not specified.",
e.message)
# 'image_name' is not in 'image_context'
image = {"id": "image_id", "size": 1024,
"min_ram": 256, "min_disk": 512}
clients = mock.Mock()
clients.glance().images.get().to_dict.return_value = image
config = {"args": {"image": "foo_image",
"context": {"images": {
"fake_parameter_name": "foo_image"}
}}
}
result = self.validator._get_validated_image(config, clients, "image")
self.assertEqual(image, result)
mock_glance_image.assert_called_once_with(
context={"admin": {"credential": clients.credential}})
mock_glance_image.return_value.pre_process.assert_called_once_with(
config["args"]["image"], config={})
clients.glance().images.get.assert_called_with("image_id")
@mock.patch("%s.openstack_types.GlanceImage" % PATH)
def test__get_validated_image_exceptions(self, mock_glance_image):
mock_glance_image.return_value.pre_process.return_value = "image_id"
clients = mock.Mock()
clients.glance().images.get.side_effect = glance_exc.HTTPNotFound("")
e = self.assertRaises(
validators.validation.ValidationError,
self.validator._get_validated_image,
config, clients, "image")
self.assertEqual("Image '%s' not found" % config["args"]["image"],
e.message)
mock_glance_image.assert_called_once_with(
context={"admin": {"credential": clients.credential}})
mock_glance_image.return_value.pre_process.assert_called_once_with(
config["args"]["image"], config={})
clients.glance().images.get.assert_called_with("image_id")
mock_glance_image.return_value.pre_process.reset_mock()
clients.side_effect = exceptions.InvalidScenarioArgument("")
e = self.assertRaises(
validators.validation.ValidationError,
self.validator._get_validated_image, config, clients, "image")
self.assertEqual("Image '%s' not found" % config["args"]["image"],
e.message)
mock_glance_image.return_value.pre_process.assert_called_once_with(
config["args"]["image"], config={})
clients.glance().images.get.assert_called_with("image_id")
class RequiredServicesValidatorTestCase(test.TestCase):
def setUp(self):
super(RequiredServicesValidatorTestCase, self).setUp()
self.validator = validators.RequiredServicesValidator([
consts.Service.KEYSTONE,
consts.Service.NOVA])
self.config = config
self.context = context
def test_validator(self):
self.config["context"]["api_versions@openstack"].get = mock.Mock(
return_value={consts.Service.KEYSTONE: "service_type"})
clients = self.context["admin"].get("credential").clients()
clients.services().values.return_value = [
consts.Service.KEYSTONE, consts.Service.NOVA,
consts.Service.NOVA_NET]
fake_service = mock.Mock(binary="nova-network", status="enabled")
clients.nova.services.list.return_value = [fake_service]
result = self.validator.validate(self.context, self.config,
None, None)
self.assertIsNone(result)
fake_service = mock.Mock(binary="keystone", status="enabled")
clients.nova.services.list.return_value = [fake_service]
result = self.validator.validate(self.context, self.config,
None, None)
self.assertIsNone(result)
fake_service = mock.Mock(binary="nova-network", status="disabled")
clients.nova.services.list.return_value = [fake_service]
result = self.validator.validate(self.context, self.config,
None, None)
self.assertIsNone(result)
def test_validator_wrong_service(self):
self.config["context"]["api_versions@openstack"].get = mock.Mock(
return_value={consts.Service.KEYSTONE: "service_type",
consts.Service.NOVA: "service_name"})
clients = self.context["admin"].get("credential").clients()
clients.services().values.return_value = [
consts.Service.KEYSTONE, consts.Service.NOVA]
validator = validators.RequiredServicesValidator([
consts.Service.KEYSTONE,
consts.Service.NOVA, "lol"])
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, {}, None, None)
expected_msg = ("'{0}' service is not available. Hint: If '{0}'"
" service has non-default service_type, try to setup"
" it via 'api_versions@openstack' context."
).format("lol")
self.assertEqual(expected_msg, e.message)
@ddt.ddt
class ValidateHeatTemplateValidatorTestCase(test.TestCase):
def setUp(self):
super(ValidateHeatTemplateValidatorTestCase, self).setUp()
self.validator = validators.ValidateHeatTemplateValidator(
"template_path1", "template_path2")
self.config = copy.deepcopy(config)
self.context = copy.deepcopy(context)
@ddt.data(
{"exception_msg": "Heat template validation failed on fake_path1. "
"Original error message: fake_msg."},
{"exception_msg": None}
)
@ddt.unpack
@mock.patch("%s.os.path.exists" % PATH,
return_value=True)
@mock.patch("rally_openstack.common.validators.open",
side_effect=mock.mock_open(), create=True)
def test_validate(self, mock_open, mock_exists, exception_msg):
clients = self.context["users"][0]["credential"].clients()
mock_open().__enter__().read.side_effect = ["fake_template1",
"fake_template2"]
heat_validator = mock.MagicMock()
if exception_msg:
heat_validator.side_effect = Exception("fake_msg")
clients.heat().stacks.validate = heat_validator
context = {"args": {"template_path1": "fake_path1",
"template_path2": "fake_path2"}}
if not exception_msg:
result = self.validator.validate(self.context, context, None, None)
heat_validator.assert_has_calls([
mock.call(template="fake_template1"),
mock.call(template="fake_template2")
])
mock_open.assert_has_calls([
mock.call("fake_path1", "r"),
mock.call("fake_path2", "r")
], any_order=True)
self.assertIsNone(result)
else:
e = self.assertRaises(
validators.validation.ValidationError,
self.validator.validate, self.context, context, None, None)
heat_validator.assert_called_once_with(
template="fake_template1")
self.assertEqual(
"Heat template validation failed on fake_path1."
" Original error message: fake_msg.", e.message)
def test_validate_missed_params(self):
validator = validators.ValidateHeatTemplateValidator(
params="fake_param")
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, self.config, None, None)
expected_msg = ("Path to heat template is not specified. Its needed "
"for heat template validation. Please check the "
"content of `fake_param` scenario argument.")
self.assertEqual(expected_msg, e.message)
@mock.patch("%s.os.path.exists" % PATH,
return_value=False)
def test_validate_file_not_found(self, mock_exists):
config = {"args": {"template_path1": "fake_path1",
"template_path2": "fake_path2"}}
e = self.assertRaises(
validators.validation.ValidationError,
self.validator.validate, self.context, config, None, None)
expected_msg = "No file found by the given path fake_path1"
self.assertEqual(expected_msg, e.message)
class RequiredCinderServicesValidatorTestCase(test.TestCase):
def setUp(self):
super(RequiredCinderServicesValidatorTestCase, self).setUp()
self.context = copy.deepcopy(context)
self.config = copy.deepcopy(config)
def test_validate(self):
validator = validators.RequiredCinderServicesValidator(
"cinder_service")
fake_service = mock.Mock(binary="cinder_service", state="up")
clients = self.context["admin"]["credential"].clients()
clients.cinder().services.list.return_value = [fake_service]
result = validator.validate(self.context, self.config, None, None)
self.assertIsNone(result)
fake_service.state = "down"
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, self.config, None, None)
self.assertEqual("cinder_service service is not available",
e.message)
@ddt.ddt
class RequiredAPIVersionsValidatorTestCase(test.TestCase):
def setUp(self):
super(RequiredAPIVersionsValidatorTestCase, self).setUp()
self.config = copy.deepcopy(config)
self.context = copy.deepcopy(context)
def _get_keystone_v2_mock_client(self):
keystone = mock.Mock()
del keystone.projects
keystone.tenants = mock.Mock()
return keystone
def _get_keystone_v3_mock_client(self):
keystone = mock.Mock()
del keystone.tenants
keystone.projects = mock.Mock()
return keystone
def test_validate(self):
validator = validators.RequiredAPIVersionsValidator("keystone",
[2.0, 3])
clients = self.context["users"][0]["credential"].clients()
clients.keystone.return_value = self._get_keystone_v3_mock_client()
validator.validate(self.context, self.config, None, None)
clients.keystone.return_value = self._get_keystone_v2_mock_client()
validator.validate(self.context, self.config, None, None)
def test_validate_with_keystone_v2(self):
validator = validators.RequiredAPIVersionsValidator("keystone",
[2.0])
clients = self.context["users"][0]["credential"].clients()
clients.keystone.return_value = self._get_keystone_v2_mock_client()
validator.validate(self.context, self.config, None, None)
clients.keystone.return_value = self._get_keystone_v3_mock_client()
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, self.config, None, None)
self.assertEqual("Task was designed to be used with keystone V2.0, "
"but V3 is selected.", e.message)
def test_validate_with_keystone_v3(self):
validator = validators.RequiredAPIVersionsValidator("keystone",
[3])
clients = self.context["users"][0]["credential"].clients()
clients.keystone.return_value = self._get_keystone_v3_mock_client()
validator.validate(self.context, self.config, None, None)
clients.keystone.return_value = self._get_keystone_v2_mock_client()
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, self.config, None, None)
self.assertEqual("Task was designed to be used with keystone V3, "
"but V2.0 is selected.", e.message)
@ddt.unpack
@ddt.data(
{"nova": 2, "versions": [2], "err_msg": None},
{"nova": 3, "versions": [2],
"err_msg": "Task was designed to be used with nova V2, "
"but V3 is selected."},
{"nova": None, "versions": [2],
"err_msg": "Unable to determine the API version."},
{"nova": 2, "versions": [2, 3], "err_msg": None},
{"nova": 4, "versions": [2, 3],
"err_msg": "Task was designed to be used with nova V2, 3, "
"but V4 is selected."}
)
def test_validate_nova(self, nova, versions, err_msg):
validator = validators.RequiredAPIVersionsValidator("nova",
versions)
clients = self.context["users"][0]["credential"].clients()
clients.nova.choose_version.return_value = nova
config = {"contexts": {"api_versions@openstack": {}}}
if err_msg:
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, config, None, None)
self.assertEqual(err_msg, e.message)
else:
result = validator.validate(self.context, config, None, None)
self.assertIsNone(result)
@ddt.unpack
@ddt.data({"version": 2, "err_msg": None},
{"version": 3, "err_msg": "Task was designed to be used with "
"nova V3, but V2 is selected."})
def test_validate_context(self, version, err_msg):
validator = validators.RequiredAPIVersionsValidator("nova",
[version])
config = {
"contexts": {"api_versions@openstack": {"nova": {"version": 2}}}}
if err_msg:
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, config, None, None)
self.assertEqual(err_msg, e.message)
else:
result = validator.validate(self.context, config, None, None)
self.assertIsNone(result)
class VolumeTypeExistsValidatorTestCase(test.TestCase):
def setUp(self):
super(VolumeTypeExistsValidatorTestCase, self).setUp()
self.validator = validators.VolumeTypeExistsValidator("volume_type",
True)
self.config = copy.deepcopy(config)
self.context = copy.deepcopy(context)
def test_validator_without_ctx(self):
validator = validators.VolumeTypeExistsValidator("fake_param",
nullable=True)
clients = self.context["users"][0]["credential"].clients()
clients.cinder().volume_types.list.return_value = [mock.MagicMock()]
result = validator.validate(self.context, self.config, None, None)
self.assertIsNone(result, "Unexpected result")
def test_validator_without_ctx_failed(self):
validator = validators.VolumeTypeExistsValidator("fake_param",
nullable=False)
clients = self.context["users"][0]["credential"].clients()
clients.cinder().volume_types.list.return_value = [mock.MagicMock()]
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, self.context, self.config, None, None)
self.assertEqual(
"The parameter 'fake_param' is required and should not be empty.",
e.message)
def test_validate_with_ctx(self):
clients = self.context["users"][0]["credential"].clients()
clients.cinder().volume_types.list.return_value = []
ctx = {"args": {"volume_type": "fake_type"},
"contexts": {"volume_types": ["fake_type"]}}
result = self.validator.validate(self.context, ctx, None, None)
self.assertIsNone(result)
def test_validate_with_ctx_failed(self):
clients = self.context["users"][0]["credential"].clients()
clients.cinder().volume_types.list.return_value = []
config = {"args": {"volume_type": "fake_type"},
"contexts": {"volume_types": ["fake_type_2"]}}
e = self.assertRaises(
validators.validation.ValidationError,
self.validator.validate, self.context, config, None, None)
err_msg = ("Specified volume type fake_type not found for user {}. "
"List of available types: ['fake_type_2']")
fake_user = self.context["users"][0]
self.assertEqual(err_msg.format(fake_user), e.message)
@ddt.ddt
class WorkbookContainsWorkflowValidatorTestCase(test.TestCase):
@mock.patch("%s.yaml.safe_load" % PATH)
@mock.patch("%s.os.access" % PATH)
@mock.patch("%s.open" % PATH)
def test_validator(self, mock_open, mock_access, mock_safe_load):
mock_safe_load.return_value = {
"version": "2.0",
"name": "wb",
"workflows": {
"wf1": {
"type": "direct",
"tasks": {
"t1": {
"action": "std.noop"
}
}
}
}
}
validator = validators.WorkbookContainsWorkflowValidator(
workbook_param="definition", workflow_param="workflow_name")
config = {
"args": {
"definition": "fake_path1",
"workflow_name": "wf1"
}
}
result = validator.validate(None, config, None, None)
self.assertIsNone(result)
self.assertEqual(1, mock_open.called)
self.assertEqual(1, mock_access.called)
self.assertEqual(1, mock_safe_load.called)
@ddt.ddt
class RequiredContextConfigValidatorTestCase(test.TestCase):
def test_validator(self):
validator = validators.RequiredContextConfigValidator(
context_name="zones",
context_config={"set_zone_in_network": True})
cfg = {
"contexts": {
"users": {
"tenants": 1, "users_per_tenant": 1
},
"network": {
"dns_nameservers": ["8.8.8.8", "192.168.210.45"]
},
"zones": {"set_zone_in_network": True}
},
}
validator.validate({}, cfg, None, None)
def test_validator_context_not_in_contexts(self):
validator = validators.RequiredContextConfigValidator(
context_name="zones",
context_config={"set_zone_in_network": True})
cfg = {
"contexts": {
"users": {
"tenants": 1, "users_per_tenant": 1
},
"network": {
"dns_nameservers": ["8.8.8.8", "192.168.210.45"]
},
},
}
validator.validate({}, cfg, None, None)
def test_validator_failed(self):
validator = validators.RequiredContextConfigValidator(
context_name="zones",
context_config={"set_zone_in_network": True})
cfg = {
"contexts": {
"users": {
"tenants": 1, "users_per_tenant": 1
},
"network": {
"dns_nameservers": ["8.8.8.8", "192.168.210.45"]
},
"zones": {"set_zone_in_network": False}
},
}
e = self.assertRaises(
validators.validation.ValidationError,
validator.validate, {}, cfg, None, None)
self.assertEqual(
"The 'zones' context expects '{'set_zone_in_network': True}'",
e.message)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,889
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/functional/test_cli_deployment.py
|
# Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import re
import testtools
from tests.functional import utils
TEST_ENV = {
"OS_USERNAME": "admin",
"OS_PASSWORD": "admin",
"OS_TENANT_NAME": "admin",
"OS_AUTH_URL": "http://fake/",
}
class DeploymentTestCase(testtools.TestCase):
def test_create_fromenv_list_show(self):
# NOTE(andreykurilin): `rally deployment create --fromenv` is
# hardcoded to OpenStack. Should be fixed as soon as the platforms
# will be introduced.
rally = utils.Rally()
rally.env.update(TEST_ENV)
rally("deployment create --name t_create_env --fromenv")
self.assertIn("t_create_env", rally("deployment list"))
self.assertIn(TEST_ENV["OS_AUTH_URL"],
rally("deployment show"))
def test_create_fromfile(self):
rally = utils.Rally()
rally.env.update(TEST_ENV)
rally("deployment create --name t_create_env --fromenv")
existing_conf = rally("deployment config", getjson=True)
with open("/tmp/.tmp.deployment", "w") as f:
f.write(json.dumps(existing_conf))
rally("deployment create --name t_create_file "
"--filename /tmp/.tmp.deployment")
self.assertIn("t_create_file", rally("deployment list"))
def test_destroy(self):
rally = utils.Rally()
rally.env.update(TEST_ENV)
rally("deployment create --name t_create_env --fromenv")
self.assertIn("t_create_env", rally("deployment list"))
rally("deployment destroy")
self.assertNotIn("t_create_env", rally("deployment list"))
def test_check_success(self):
rally = utils.Rally()
rally("deployment check")
def test_check_fail(self):
rally = utils.Rally()
rally.env.update(TEST_ENV)
rally("deployment create --name t_create_env --fromenv")
self.assertRaises(utils.RallyCliError, rally, "deployment check")
def test_check_debug(self):
rally = utils.Rally()
rally.env.update(TEST_ENV)
rally("deployment create --name t_create_env --fromenv")
config = rally("deployment config", getjson=True)
config["openstack"]["admin"]["password"] = "fakepassword"
file = utils.JsonTempFile(config)
rally("deployment create --name t_create_file_debug "
"--filename %s" % file.filename)
self.assertIn("t_create_file_debug", rally("deployment list"))
self.assertEqual(config, rally("deployment config", getjson=True))
e = self.assertRaises(utils.RallyCliError, rally,
"--debug deployment check")
self.assertIn(
"AuthenticationFailed: Could not find versioned identity "
"endpoints when attempting to authenticate.",
e.output)
def test_use(self):
rally = utils.Rally()
rally.env.update(TEST_ENV)
output = rally(
"deployment create --name t_create_env1 --fromenv")
uuid = re.search(r"Using deployment: (?P<uuid>[0-9a-f\-]{36})",
output).group("uuid")
rally("deployment create --name t_create_env2 --fromenv")
rally("deployment use --deployment %s" % uuid)
current_deployment = utils.get_global("RALLY_DEPLOYMENT",
rally.env)
self.assertEqual(uuid, current_deployment)
def test_create_from_env_openstack_deployment(self):
rally = utils.Rally()
rally.env.update(TEST_ENV)
rally("deployment create --name t_create_env --fromenv")
config = rally("deployment config", getjson=True)
self.assertIn("openstack", config)
self.assertEqual(TEST_ENV["OS_USERNAME"],
config["openstack"]["admin"]["username"])
self.assertEqual(TEST_ENV["OS_PASSWORD"],
config["openstack"]["admin"]["password"])
if "project_name" in config["openstack"]["admin"]:
# keystone v3
self.assertEqual(TEST_ENV["OS_TENANT_NAME"],
config["openstack"]["admin"]["project_name"])
else:
# keystone v2
self.assertEqual(TEST_ENV["OS_TENANT_NAME"],
config["openstack"]["admin"]["tenant_name"])
self.assertEqual(TEST_ENV["OS_AUTH_URL"],
config["openstack"]["auth_url"])
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,890
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/ci/playbooks/roles/prepare-for-rally-task/library/make_env_spec_with_existing_users.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
import json
import uuid
from ansible.module_utils.basic import AnsibleModule
from rally import api
from rally.env import env_mgr
from rally import plugins
from rally_openstack.common import consts
from rally_openstack.common import credential
def fetch_parent_env_and_admin_creds(env_name):
"""Fetch parent environment spec and openstack admin creds from it."""
env_data = env_mgr.EnvManager.get(env_name).data
openstack_platform = env_data["platforms"]["openstack"]
admin_creds = credential.OpenStackCredential(
permission=consts.EndpointPermission.ADMIN,
**openstack_platform["platform_data"]["admin"])
return env_data["spec"], admin_creds
def create_projects_and_users(admin_creds, projects_count, users_per_project):
"""Create new projects and users via 'users@openstack' context.
:param admin_creds: admin credentials to use for creating new entities
:param projects_count: The number of keystone projects to create.
:param users_per_project: The number of keystone users to create per one
keystone project.
"""
# it should be imported after calling rally.api.API that setups oslo_config
from rally_openstack.task.contexts.keystone import users as users_ctx
ctx = {
"env": {
"platforms": {
"openstack": {
"admin": admin_creds.to_dict(),
"users": []
}
}
},
"task": {
"uuid": str(uuid.uuid4())
},
"config": {
"users@openstack": {
"tenants": projects_count,
"users_per_tenant": users_per_project
}
}
}
users_ctx.UserGenerator(ctx).setup()
users = []
for user in ctx["users"]:
users.append({
"username": user["credential"]["username"],
"password": user["credential"]["password"],
"project_name": user["credential"]["tenant_name"]
})
for optional in ("domain_name",
"user_domain_name",
"project_domain_name"):
if user["credential"][optional]:
users[-1][optional] = user["credential"][optional]
return users
def store_a_new_spec(original_spec, users, path_for_new_spec):
new_spec = copy.deepcopy(original_spec)
del new_spec["existing@openstack"]["admin"]
new_spec["existing@openstack"]["users"] = users
with open(path_for_new_spec, "w") as f:
f.write(json.dumps(new_spec, indent=4))
@plugins.ensure_plugins_are_loaded
def ansible_main():
module = AnsibleModule(argument_spec=dict(
projects_count=dict(
type="int",
default=1,
required=False
),
users_per_project=dict(
type="int",
default=1,
required=False
),
parent_env_name=dict(
type="str",
required=True
),
path_for_new_spec=dict(
type="str",
required=True
)
))
# init Rally API as it makes all work for logging and config initialization
api.API()
original_spec, admin_creds = fetch_parent_env_and_admin_creds(
module.params["parent_env_name"]
)
users = create_projects_and_users(
admin_creds,
projects_count=module.params["projects_count"],
users_per_project=module.params["users_per_project"]
)
store_a_new_spec(original_spec, users, module.params["path_for_new_spec"])
module.exit_json(changed=True)
if __name__ == "__main__":
ansible_main()
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,891
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/environment/platforms/test_existing.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
from unittest import mock
import jsonschema
from rally.env import env_mgr
from rally.env import platform
from rally import exceptions
from rally_openstack.environment.platforms import existing
from tests.unit import test
class PlatformBaseTestCase(test.TestCase):
def _check_schema(self, schema, obj):
jsonschema.validate(obj, schema)
def _check_health_schema(self, obj):
self._check_schema(env_mgr.EnvManager._HEALTH_FORMAT, obj)
def _check_cleanup_schema(self, obj):
self._check_schema(env_mgr.EnvManager._CLEANUP_FORMAT, obj)
def _check_info_schema(self, obj):
self._check_schema(env_mgr.EnvManager._INFO_FORMAT, obj)
class ExistingPlatformTestCase(PlatformBaseTestCase):
def test_validate_spec_schema(self):
spec = {
"existing@openstack": {
"auth_url": "url",
"admin": {
"username": "admin",
"password": "password123",
"tenant_name": "admin"
},
"users": [{
"username": "admin",
"password": "password123",
"tenant_name": "admin"
}]
}
}
result = platform.Platform.validate("existing@openstack", {},
spec, spec["existing@openstack"])
self.assertEqual([], result)
def test_validate_invalid_spec(self):
spec = {
"existing@openstack": {
"something_wrong": {
"username": "not_an_admin",
"password": "password123",
"project_name": "not_an_admin"
}
}
}
result = platform.Platform.validate("existing@openstack", {},
spec, spec["existing@openstack"])
self.assertNotEqual([], result)
def test_validate_spec_schema_with_api_info(self):
spec = {
"existing@openstack": {
"auth_url": "url",
"admin": {
"username": "admin",
"password": "password123",
"tenant_name": "admin"
},
"api_info": {
"nova": {"version": 1},
"cinder": {"version": 2, "service_type": "volumev2"}
}
}
}
result = platform.Platform.validate("existing@openstack", {},
spec, spec["existing@openstack"])
self.assertEqual([], result)
def test_create_users_only(self):
spec = {
"auth_url": "https://best",
"endpoint": "check_that_its_poped",
"users": [
{"project_name": "a", "username": "a", "password": "a"},
{"project_name": "b", "username": "b", "password": "b"}
]
}
self.assertEqual(
({
"admin": None,
"users": [
{
"auth_url": "https://best", "endpoint_type": None,
"region_name": None,
"domain_name": None,
"user_domain_name": "default",
"project_domain_name": "default",
"https_insecure": False, "https_cacert": None,
"tenant_name": "a", "username": "a", "password": "a"
},
{
"auth_url": "https://best", "endpoint_type": None,
"region_name": None,
"domain_name": None,
"user_domain_name": "default",
"project_domain_name": "default",
"https_insecure": False, "https_cacert": None,
"tenant_name": "b", "username": "b", "password": "b"
}
]
}, {}),
existing.OpenStack(spec).create())
def test_create_admin_only(self):
spec = {
"auth_url": "https://best",
"endpoint_type": "public",
"https_insecure": True,
"https_cacert": "/my.ca",
"profiler_hmac_key": "key",
"profiler_conn_str": "http://prof",
"admin": {
"domain_name": "d", "user_domain_name": "d",
"project_domain_name": "d", "project_name": "d",
"username": "d", "password": "d"
}
}
self.assertEqual(
(
{
"admin": {
"auth_url": "https://best",
"endpoint_type": "public",
"https_insecure": True, "https_cacert": "/my.ca",
"profiler_hmac_key": "key",
"profiler_conn_str": "http://prof",
"region_name": None, "domain_name": "d",
"user_domain_name": "d", "project_domain_name": "d",
"tenant_name": "d", "username": "d", "password": "d"
},
"users": []
},
{}
),
existing.OpenStack(spec).create())
def test_create_spec_from_sys_environ(self):
# keystone v2
sys_env = {
"OS_AUTH_URL": "https://example.com",
"OS_USERNAME": "user",
"OS_PASSWORD": "pass",
"OS_TENANT_NAME": "projectX",
"OS_INTERFACE": "publicURL",
"OS_REGION_NAME": "Region1",
"OS_CACERT": "Cacert",
"OS_CERT": "cert",
"OS_KEY": "key",
"OS_INSECURE": True,
"OSPROFILER_HMAC_KEY": "hmackey",
"OSPROFILER_CONN_STR": "https://example2.com",
}
result = existing.OpenStack.create_spec_from_sys_environ(sys_env)
self.assertTrue(result["available"])
self.assertEqual(
{
"admin": {
"username": "user",
"tenant_name": "projectX",
"password": "pass"
},
"auth_url": "https://example.com",
"endpoint_type": "public",
"region_name": "Region1",
"https_cacert": "Cacert",
"https_cert": "cert",
"https_key": "key",
"https_insecure": True,
"profiler_hmac_key": "hmackey",
"profiler_conn_str": "https://example2.com",
"api_info": {
"keystone": {
"version": 2,
"service_type": "identity"
}
}
}, result["spec"])
# keystone v3
sys_env["OS_IDENTITY_API_VERSION"] = "3"
result = existing.OpenStack.create_spec_from_sys_environ(sys_env)
self.assertEqual(
{
"admin": {
"username": "user",
"project_name": "projectX",
"user_domain_name": "Default",
"password": "pass",
"project_domain_name": "Default"
},
"endpoint_type": "public",
"auth_url": "https://example.com",
"region_name": "Region1",
"https_cacert": "Cacert",
"https_cert": "cert",
"https_key": "key",
"https_insecure": True,
"profiler_hmac_key": "hmackey",
"profiler_conn_str": "https://example2.com",
"api_info": {
"keystone": {
"version": 3,
"service_type": "identityv3"
}
}
}, result["spec"])
def test_create_spec_from_sys_environ_fails_with_missing_vars(self):
sys_env = {"OS_AUTH_URL": "https://example.com"}
result = existing.OpenStack.create_spec_from_sys_environ(sys_env)
self.assertFalse(result["available"])
self.assertIn("OS_USERNAME", result["message"])
self.assertIn("OS_PASSWORD", result["message"])
self.assertNotIn("OS_AUTH_URL", result["message"])
sys_env = {"OS_AUTH_URL": "https://example.com",
"OS_USERNAME": "user",
"OS_PASSWORD": "pass"}
result = existing.OpenStack.create_spec_from_sys_environ(sys_env)
self.assertFalse(result["available"])
self.assertIn("OS_PROJECT_NAME or OS_TENANT_NAME", result["message"])
def test_destroy(self):
self.assertIsNone(existing.OpenStack({}).destroy())
def test_cleanup(self):
result1 = existing.OpenStack({}).cleanup()
result2 = existing.OpenStack({}).cleanup(task_uuid="any")
self.assertEqual(result1, result2)
self.assertEqual(
{
"message": "Coming soon!",
"discovered": 0,
"deleted": 0,
"failed": 0,
"resources": {},
"errors": []
},
result1
)
self._check_cleanup_schema(result1)
@mock.patch("rally_openstack.common.osclients.Clients")
def test_check_health(self, mock_clients):
pdata = {
"admin": mock.MagicMock(),
"users": [mock.MagicMock(), mock.MagicMock()]
}
result = existing.OpenStack({}, platform_data=pdata).check_health()
self._check_health_schema(result)
self.assertEqual({"available": True}, result)
mock_clients.assert_has_calls(
[mock.call(pdata["users"][0]), mock.call().keystone(),
mock.call(pdata["users"][1]), mock.call().keystone(),
mock.call(pdata["admin"]), mock.call().verified_keystone()])
@mock.patch("rally_openstack.common.osclients.Clients")
def test_check_failed_with_native_rally_exc(self, mock_clients):
e = exceptions.RallyException("foo")
mock_clients.return_value.keystone.side_effect = e
pdata = {"admin": None,
"users": [{"username": "balbab", "password": "12345"}]}
result = existing.OpenStack({}, platform_data=pdata).check_health()
self._check_health_schema(result)
self.assertEqual(
{
"available": False,
"message": e.format_message(),
"traceback": mock.ANY
},
result)
@mock.patch("rally_openstack.common.osclients.Clients")
def test_check_failed_admin(self, mock_clients):
mock_clients.return_value.verified_keystone.side_effect = Exception
pdata = {"admin": {"username": "balbab", "password": "12345"},
"users": []}
result = existing.OpenStack({}, platform_data=pdata).check_health()
self._check_health_schema(result)
self.assertEqual(
{"available": False,
"message":
"Bad admin creds: \n%s"
% json.dumps({"username": "balbab", "password": "***",
"api_info": {}},
indent=2, sort_keys=True),
"traceback": mock.ANY},
result)
self.assertIn("Traceback (most recent call last)", result["traceback"])
@mock.patch("rally_openstack.common.osclients.Clients")
def test_check_failed_users(self, mock_clients):
mock_clients.return_value.keystone.side_effect = Exception
pdata = {"admin": None,
"users": [{"username": "balbab", "password": "12345"}]}
result = existing.OpenStack({}, platform_data=pdata).check_health()
self._check_health_schema(result)
self.assertEqual(
{"available": False,
"message":
"Bad user creds: \n%s"
% json.dumps({"username": "balbab", "password": "***",
"api_info": {}},
indent=2, sort_keys=True),
"traceback": mock.ANY},
result)
self.assertIn("Traceback (most recent call last)", result["traceback"])
@mock.patch("rally_openstack.common.osclients.Clients")
def test_check_health_with_api_info(self, mock_clients):
pdata = {"admin": mock.MagicMock(),
"users": [],
"api_info": {"fakeclient": "version"}}
result = existing.OpenStack({}, platform_data=pdata).check_health()
self._check_health_schema(result)
self.assertEqual({"available": True}, result)
mock_clients.assert_has_calls(
[mock.call(pdata["admin"]), mock.call().verified_keystone(),
mock.call().fakeclient.choose_version(),
mock.call().fakeclient.validate_version(
mock_clients.return_value.fakeclient.choose_version
.return_value),
mock.call().fakeclient.create_client()])
@mock.patch("rally_openstack.common.osclients.Clients")
def test_check_version_failed_with_api_info(self, mock_clients):
pdata = {"admin": mock.MagicMock(),
"users": [],
"api_info": {"fakeclient": "version"}}
def validate_version(version):
raise exceptions.RallyException("Version is not supported.")
(mock_clients.return_value.fakeclient
.validate_version) = validate_version
result = existing.OpenStack({}, platform_data=pdata).check_health()
self._check_health_schema(result)
self.assertEqual({"available": False,
"message": ("Invalid setting for 'fakeclient':"
" Version is not supported.")},
result)
@mock.patch("rally_openstack.common.osclients.Clients")
def test_check_unexpected_failed_with_api_info(self, mock_clients):
pdata = {"admin": mock.MagicMock(),
"users": [],
"api_info": {"fakeclient": "version"}}
def create_client():
raise Exception("Invalid client.")
(mock_clients.return_value.fakeclient
.choose_version.return_value) = "1.0"
mock_clients.return_value.fakeclient.create_client = create_client
result = existing.OpenStack({}, platform_data=pdata).check_health()
self._check_health_schema(result)
self.assertEqual({"available": False,
"message": ("Can not create 'fakeclient' with"
" 1.0 version."),
"traceback": mock.ANY},
result)
@mock.patch("rally_openstack.common.osclients.Clients")
def test_info(self, mock_clients):
mock_clients.return_value.services.return_value = {
"foo": "bar",
"volumev4": "__unknown__"}
platform_data = {
"admin": None,
"users": [{"username": "u1", "password": "123"}]
}
p = existing.OpenStack({}, platform_data=platform_data)
result = p.info()
mock_clients.assert_called_once_with(platform_data["users"][0])
mock_clients.return_value.services.assert_called_once_with()
self.assertEqual(
{
"info": {
"services": [{"type": "foo", "name": "bar"},
{"type": "volumev4"}]}},
result)
self._check_info_schema(result)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,892
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/contexts/network/test_allow_ssh.py
|
# Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
from unittest import mock
from rally_openstack.task.contexts.network import allow_ssh
from tests.unit import test
CTX = "rally_openstack.task.contexts.network.allow_ssh"
class AllowSSHContextTestCase(test.TestCase):
def setUp(self):
super(AllowSSHContextTestCase, self).setUp()
self.users_count = 3
self.ctx = test.get_test_context()
self.ctx.update(
users=[
{
"tenant_id": f"uuid{i // 3}",
"credential": mock.MagicMock()
}
for i in range(1, self.users_count + 1)
],
admin={
"tenant_id": "uuid2",
"credential": mock.MagicMock()},
tenants={
"uuid1": {"id": "uuid1", "name": "uuid1"},
"uuid2": {"id": "uuid2", "name": "uuid1"}
}
)
def test_setup(self):
for i, user in enumerate(self.ctx["users"]):
clients = user["credential"].clients.return_value
nc = clients.neutron.return_value
nc.list_extensions.return_value = {
"extensions": [{"alias": "security-group"}]
}
nc.create_security_group.return_value = {
"security_group": {
"name": "xxx",
"id": f"security-group-{i}",
"security_group_rules": []
}
}
allow_ssh.AllowSSH(self.ctx).setup()
# admin user should not be used
self.assertFalse(self.ctx["admin"]["credential"].clients.called)
processed_tenants = {}
for i, user in enumerate(self.ctx["users"]):
clients = user["credential"].clients.return_value
nc = clients.neutron.return_value
if i == 0:
nc.list_extensions.assert_called_once_with()
else:
self.assertFalse(nc.list_extensions.called)
if user["tenant_id"] in processed_tenants:
self.assertFalse(nc.create_security_group.called)
self.assertFalse(nc.create_security_group_rule.called)
else:
nc.create_security_group.assert_called_once_with({
"security_group": {
"name": mock.ANY,
"description": mock.ANY
}
})
secgroup = nc.create_security_group.return_value
secgroup = secgroup["security_group"]
rules = copy.deepcopy(allow_ssh._RULES_TO_ADD)
for rule in rules:
rule["security_group_id"] = secgroup["id"]
self.assertEqual(
[mock.call({"security_group_rule": rule})
for rule in rules],
nc.create_security_group_rule.call_args_list
)
processed_tenants[user["tenant_id"]] = secgroup
self.assertEqual(processed_tenants[user["tenant_id"]]["id"],
user["secgroup"]["id"])
def test_setup_no_security_group_extension(self):
clients = self.ctx["users"][0]["credential"].clients.return_value
nc = clients.neutron.return_value
nc.list_extensions.return_value = {"extensions": []}
allow_ssh.AllowSSH(self.ctx).setup()
# admin user should not be used
self.assertFalse(self.ctx["admin"]["credential"].clients.called)
nc.list_extensions.assert_called_once_with()
for i, user in enumerate(self.ctx["users"]):
if i == 0:
continue
self.assertFalse(user["credential"].clients.called)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,893
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/scenarios/monasca/utils.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import random
import time
import uuid
from rally.common import cfg
from rally.task import atomic
from rally_openstack.task import scenario
CONF = cfg.CONF
class MonascaScenario(scenario.OpenStackScenario):
"""Base class for Monasca scenarios with basic atomic actions."""
@atomic.action_timer("monasca.list_metrics")
def _list_metrics(self, **kwargs):
"""Get list of user's metrics.
:param kwargs: optional arguments for list query:
name, dimensions, start_time, etc
:returns list of monasca metrics
"""
return self.clients("monasca").metrics.list(**kwargs)
@atomic.action_timer("monasca.create_metrics")
def _create_metrics(self, **kwargs):
"""Create user metrics.
:param kwargs: attributes for metric creation:
name, dimension, timestamp, value, etc
"""
timestamp = int(time.time() * 1000)
kwargs.update({"name": self.generate_random_name(),
"timestamp": timestamp,
"value": random.random(),
"value_meta": {
"key": str(uuid.uuid4())[:10]}})
self.clients("monasca").metrics.create(**kwargs)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,894
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/nova/test_aggregates.py
|
# Copyright 2016 IBM Corp.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally import exceptions
from rally_openstack.task.scenarios.nova import aggregates
from tests.unit import test
class NovaAggregatesTestCase(test.ScenarioTestCase):
def test_list_aggregates(self):
scenario = aggregates.ListAggregates()
scenario._list_aggregates = mock.Mock()
scenario.run()
scenario._list_aggregates.assert_called_once_with()
def test_create_and_list_aggregates(self):
# Positive case
scenario = aggregates.CreateAndListAggregates()
scenario._create_aggregate = mock.Mock(return_value="agg1")
scenario._list_aggregates = mock.Mock(return_value=("agg1", "agg2"))
scenario.run(availability_zone="nova")
scenario._create_aggregate.assert_called_once_with("nova")
scenario._list_aggregates.assert_called_once_with()
# Negative case 1: aggregate isn't created
scenario._create_aggregate.return_value = None
self.assertRaises(exceptions.RallyAssertionError,
scenario.run, availability_zone="nova")
scenario._create_aggregate.assert_called_with("nova")
# Negative case 2: aggregate was created but not included into list
scenario._create_aggregate.return_value = "agg3"
self.assertRaises(exceptions.RallyAssertionError,
scenario.run, availability_zone="nova")
scenario._create_aggregate.assert_called_with("nova")
scenario._list_aggregates.assert_called_with()
def test_create_and_delete_aggregate(self):
scenario = aggregates.CreateAndDeleteAggregate()
scenario._create_aggregate = mock.Mock()
scenario._delete_aggregate = mock.Mock()
scenario.run(availability_zone="nova")
scenario._create_aggregate.assert_called_once_with("nova")
aggregate = scenario._create_aggregate.return_value
scenario._delete_aggregate.assert_called_once_with(aggregate)
def test_create_and_update_aggregate(self):
scenario = aggregates.CreateAndUpdateAggregate()
scenario._create_aggregate = mock.Mock()
scenario._update_aggregate = mock.Mock()
scenario.run(availability_zone="nova")
scenario._create_aggregate.assert_called_once_with("nova")
aggregate = scenario._create_aggregate.return_value
scenario._update_aggregate.assert_called_once_with(aggregate)
def test_create_aggregate_add_and_remove_host(self):
fake_aggregate = "fake_aggregate"
fake_hosts = [mock.Mock(service={"host": "fake_host_name"})]
scenario = aggregates.CreateAggregateAddAndRemoveHost()
scenario._create_aggregate = mock.MagicMock(
return_value=fake_aggregate)
scenario._list_hypervisors = mock.MagicMock(return_value=fake_hosts)
scenario._aggregate_add_host = mock.MagicMock()
scenario._aggregate_remove_host = mock.MagicMock()
scenario.run(availability_zone="nova")
scenario._create_aggregate.assert_called_once_with(
"nova")
scenario._list_hypervisors.assert_called_once_with()
scenario._aggregate_add_host.assert_called_once_with(
"fake_aggregate", "fake_host_name")
scenario._aggregate_remove_host.assert_called_once_with(
"fake_aggregate", "fake_host_name")
def test_create_and_get_aggregate_details(self):
scenario = aggregates.CreateAndGetAggregateDetails()
scenario._create_aggregate = mock.Mock()
scenario._get_aggregate_details = mock.Mock()
scenario.run(availability_zone="nova")
scenario._create_aggregate.assert_called_once_with("nova")
aggregate = scenario._create_aggregate.return_value
scenario._get_aggregate_details.assert_called_once_with(aggregate)
def test_create_aggregate_add_host_and_boot_server(self):
fake_aggregate = mock.Mock()
fake_hosts = [mock.Mock(service={"host": "fake_host_name"}, state="up",
status="enabled")]
fake_flavor = mock.MagicMock(id="flavor-id-0", ram=512, disk=1,
vcpus=1)
fake_metadata = {"test_metadata": "true"}
fake_server = mock.MagicMock(id="server-id-0")
setattr(fake_server, "OS-EXT-SRV-ATTR:hypervisor_hostname",
"fake_host_name")
fake_aggregate_kwargs = {"fake_arg1": "f"}
scenario = aggregates.CreateAggregateAddHostAndBootServer()
scenario._create_aggregate = mock.MagicMock(
return_value=fake_aggregate)
scenario._list_hypervisors = mock.MagicMock(return_value=fake_hosts)
scenario._aggregate_add_host = mock.MagicMock()
scenario._aggregate_set_metadata = mock.MagicMock()
scenario._create_flavor = mock.MagicMock(return_value=fake_flavor)
scenario._boot_server = mock.MagicMock(return_value=fake_server)
self.admin_clients("nova").servers.get.return_value = fake_server
scenario.run("img", fake_metadata, availability_zone="nova",
boot_server_kwargs=fake_aggregate_kwargs)
scenario._create_aggregate.assert_called_once_with("nova")
scenario._list_hypervisors.assert_called_once_with()
scenario._aggregate_set_metadata.assert_called_once_with(
fake_aggregate, fake_metadata)
scenario._aggregate_add_host(fake_aggregate, "fake_host_name")
scenario._create_flavor.assert_called_once_with(512, 1, 1)
fake_flavor.set_keys.assert_called_once_with(fake_metadata)
scenario._boot_server.assert_called_once_with("img", "flavor-id-0",
**fake_aggregate_kwargs)
self.admin_clients("nova").servers.get.assert_called_once_with(
"server-id-0")
self.assertEqual(getattr(
fake_server, "OS-EXT-SRV-ATTR:hypervisor_hostname"),
"fake_host_name")
def test_create_aggregate_add_host_and_boot_server_failure(self):
fake_aggregate = mock.Mock()
fake_hosts = [mock.Mock(service={"host": "fake_host_name"})]
fake_flavor = mock.MagicMock(id="flavor-id-0", ram=512, disk=1,
vcpus=1)
fake_metadata = {"test_metadata": "true"}
fake_server = mock.MagicMock(id="server-id-0")
setattr(fake_server, "OS-EXT-SRV-ATTR:hypervisor_hostname",
"wrong_host_name")
fake_boot_server_kwargs = {"fake_arg1": "f"}
scenario = aggregates.CreateAggregateAddHostAndBootServer()
scenario._create_aggregate = mock.MagicMock(
return_value=fake_aggregate)
scenario._list_hypervisors = mock.MagicMock(return_value=fake_hosts)
scenario._aggregate_add_host = mock.MagicMock()
scenario._aggregate_set_metadata = mock.MagicMock()
scenario._create_flavor = mock.MagicMock(return_value=fake_flavor)
scenario._boot_server = mock.MagicMock(return_value=fake_server)
self.admin_clients("nova").servers.get.return_value = fake_server
self.assertRaises(exceptions.RallyException, scenario.run, "img",
fake_metadata, "nova", fake_boot_server_kwargs)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,895
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/scenarios/neutron/security_groups.py
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.task import validation
from rally_openstack.common import consts
from rally_openstack.task import scenario
from rally_openstack.task.scenarios.neutron import utils
"""Scenarios for Neutron Security Groups."""
@validation.add("required_services",
services=[consts.Service.NEUTRON])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(
context={"cleanup@openstack": ["neutron"]},
name="NeutronSecurityGroup.create_and_list_security_groups",
platform="openstack")
class CreateAndListSecurityGroups(utils.NeutronScenario):
def run(self, security_group_create_args=None):
"""Create and list Neutron security-groups.
Measure the "neutron security-group-create" and "neutron
security-group-list" command performance.
:param security_group_create_args: dict, POST /v2.0/security-groups
request options
"""
security_group_create_args = security_group_create_args or {}
self._create_security_group(**security_group_create_args)
self._list_security_groups()
@validation.add("required_services",
services=[consts.Service.NEUTRON])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(
context={"cleanup@openstack": ["neutron"]},
name="NeutronSecurityGroup.create_and_show_security_group",
platform="openstack")
class CreateAndShowSecurityGroup(utils.NeutronScenario):
def run(self, security_group_create_args=None):
"""Create and show Neutron security-group.
Measure the "neutron security-group-create" and "neutron
security-group-show" command performance.
:param security_group_create_args: dict, POST /v2.0/security-groups
request options
"""
security_group_create_args = security_group_create_args or {}
security_group = self._create_security_group(
**security_group_create_args)
msg = "security_group isn't created"
self.assertTrue(security_group, err_msg=msg)
self._show_security_group(security_group)
@validation.add("required_services",
services=[consts.Service.NEUTRON])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(
context={"cleanup@openstack": ["neutron"]},
name="NeutronSecurityGroup.create_and_delete_security_groups",
platform="openstack")
class CreateAndDeleteSecurityGroups(utils.NeutronScenario):
def run(self, security_group_create_args=None):
"""Create and delete Neutron security-groups.
Measure the "neutron security-group-create" and "neutron
security-group-delete" command performance.
:param security_group_create_args: dict, POST /v2.0/security-groups
request options
"""
security_group_create_args = security_group_create_args or {}
security_group = self._create_security_group(
**security_group_create_args)
self._delete_security_group(security_group)
@validation.add("required_services",
services=[consts.Service.NEUTRON])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(
context={"cleanup@openstack": ["neutron"]},
name="NeutronSecurityGroup.create_and_update_security_groups",
platform="openstack")
class CreateAndUpdateSecurityGroups(utils.NeutronScenario):
def run(self, security_group_create_args=None,
security_group_update_args=None):
"""Create and update Neutron security-groups.
Measure the "neutron security-group-create" and "neutron
security-group-update" command performance.
:param security_group_create_args: dict, POST /v2.0/security-groups
request options
:param security_group_update_args: dict, PUT /v2.0/security-groups
update options
"""
security_group_create_args = security_group_create_args or {}
security_group_update_args = security_group_update_args or {}
security_group = self._create_security_group(
**security_group_create_args)
self._update_security_group(security_group,
**security_group_update_args)
@validation.add("required_services",
services=[consts.Service.NEUTRON])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(
context={"cleanup@openstack": ["neutron"]},
name="NeutronSecurityGroup.create_and_list_security_group_rules",
platform="openstack")
class CreateAndListSecurityGroupRules(utils.NeutronScenario):
def run(self, security_group_rules_count=1,
security_group_args=None,
security_group_rule_args=None):
"""Create and list Neutron security-group-rules.
Measure the "neutron security-group-rule-create" and "neutron
security-group-rule-list" command performance.
:param security_group_rules_count: int, number of rules per
security group
:param security_group_args: dict, POST /v2.0/security-groups
request options
:param security_group_rule_args: dict,
POST /v2.0/security-group-rules request options
"""
security_group_args = security_group_args or {}
security_group = self._create_security_group(**security_group_args)
msg = "security_group isn't created"
self.assertTrue(security_group, err_msg=msg)
rules = []
for rule in range(security_group_rules_count):
security_group_rule_args = security_group_rule_args or {}
security_group_rule_args["port_range_min"] = rule + 1
security_group_rule_args["port_range_max"] = rule + 1
security_group_rule = self._create_security_group_rule(
security_group["security_group"]["id"],
**security_group_rule_args)
rules.append(security_group_rule)
msg = "security_group_rule isn't created"
self.assertTrue(security_group_rule, err_msg=msg)
security_group_rules = self._list_security_group_rules()
for rule in rules:
self.assertIn(rule["security_group_rule"]["id"],
[sgr["id"] for sgr in security_group_rules[
"security_group_rules"]])
@validation.add("required_services",
services=[consts.Service.NEUTRON])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(
context={"cleanup@openstack": ["neutron"]},
name="NeutronSecurityGroup.create_and_show_security_group_rule",
platform="openstack")
class CreateAndShowSecurityGroupRule(utils.NeutronScenario):
def run(self, security_group_args=None,
security_group_rule_args=None):
"""Create and show Neutron security-group-rule.
Measure the "neutron security-group-rule-create" and "neutron
security-group-rule-show" command performance.
:param security_group_args: dict, POST /v2.0/security-groups
request options
:param security_group_rule_args: dict,
POST /v2.0/security-group-rules request options
"""
security_group_args = security_group_args or {}
security_group_rule_args = security_group_rule_args or {}
security_group = self._create_security_group(**security_group_args)
msg = "security_group isn't created"
self.assertTrue(security_group, err_msg=msg)
security_group_rule = self._create_security_group_rule(
security_group["security_group"]["id"], **security_group_rule_args)
msg = "security_group_rule isn't created"
self.assertTrue(security_group_rule, err_msg=msg)
self._show_security_group_rule(
security_group_rule["security_group_rule"]["id"])
@validation.add("required_services",
services=[consts.Service.NEUTRON])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(
context={"cleanup@openstack": ["neutron"]},
name="NeutronSecurityGroup.create_and_delete_security_group_rule",
platform="openstack")
class CreateAndDeleteSecurityGroupRule(utils.NeutronScenario):
def run(self, security_group_args=None,
security_group_rule_args=None):
"""Create and delete Neutron security-group-rule.
Measure the "neutron security-group-rule-create" and "neutron
security-group-rule-delete" command performance.
:param security_group_args: dict, POST /v2.0/security-groups
request options
:param security_group_rule_args: dict,
POST /v2.0/security-group-rules request options
"""
security_group_args = security_group_args or {}
security_group_rule_args = security_group_rule_args or {}
security_group = self._create_security_group(**security_group_args)
msg = "security_group isn't created"
self.assertTrue(security_group, err_msg=msg)
security_group_rule = self._create_security_group_rule(
security_group["security_group"]["id"], **security_group_rule_args)
msg = "security_group_rule isn't created"
self.assertTrue(security_group_rule, err_msg=msg)
self._delete_security_group_rule(
security_group_rule["security_group_rule"]["id"])
self._delete_security_group(security_group)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,896
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/contexts/quotas/test_designate_quotas.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally_openstack.task.contexts.quotas import designate_quotas
from tests.unit import test
class DesignateQuotasTestCase(test.TestCase):
def test_update(self):
clients = mock.MagicMock()
quotas = designate_quotas.DesignateQuotas(clients)
tenant_id = mock.MagicMock()
quotas_values = {
"api_export_size": 5,
"zones": 5,
"zone_recordsets": 20,
"zone_records": 20,
"recordset_records": 20,
}
quotas.update(tenant_id, **quotas_values)
clients.designate().quotas.update.assert_called_once_with(
tenant_id, quotas_values)
def test_delete(self):
clients = mock.MagicMock()
quotas = designate_quotas.DesignateQuotas(clients)
tenant_id = mock.MagicMock()
quotas.delete(tenant_id)
clients.designate().quotas.reset.assert_called_once_with(tenant_id)
def test_get(self):
tenant_id = "tenant_id"
quotas = {"api_export_size": -1, "zones": -1,
"zone_recordsets": 2, "zone_records": 3,
"recordset_records": 3}
clients = mock.MagicMock()
clients.designate.return_value.quotas.get.return_value = quotas
designate_quo = designate_quotas.DesignateQuotas(clients)
self.assertEqual(quotas, designate_quo.get(tenant_id))
clients.designate().quotas.get.assert_called_once_with(tenant_id)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,897
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/ci/playbooks/roles/list-os-resources/library/osresources.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""List and compare most used OpenStack cloud resources."""
import io
import json
import subprocess
from ansible.module_utils.basic import AnsibleModule
from rally.cli import cliutils
from rally.common.plugin import discover
from rally import plugins
try:
from rally_openstack.common import consts
from rally_openstack.common import credential
except ImportError:
# backward compatibility for stable branches
from rally_openstack import consts
from rally_openstack import credential
def skip_if_service(service):
def wrapper(func):
def inner(self):
if service in self.clients.services().values():
return []
return func(self)
return inner
return wrapper
class ResourceManager(object):
REQUIRED_SERVICE = None
STR_ATTRS = ("id", "name")
def __init__(self, clients):
self.clients = clients
def is_available(self):
if self.REQUIRED_SERVICE:
return self.REQUIRED_SERVICE in self.clients.services().values()
return True
@property
def client(self):
return getattr(self.clients, self.__class__.__name__.lower())()
def get_resources(self):
all_resources = []
cls = self.__class__.__name__.lower()
for prop in dir(self):
if not prop.startswith("list_"):
continue
f = getattr(self, prop)
resources = f() or []
resource_name = prop[5:][:-1]
for raw_res in resources:
res = {"cls": cls, "resource_name": resource_name,
"id": {}, "props": {}}
if not isinstance(raw_res, dict):
raw_res = {k: getattr(raw_res, k) for k in dir(raw_res)
if not k.startswith("_")
if not callable(getattr(raw_res, k))}
for key, value in raw_res.items():
if key.startswith("_"):
continue
if key in self.STR_ATTRS:
res["id"][key] = value
else:
try:
res["props"][key] = json.dumps(value, indent=2)
except TypeError:
res["props"][key] = str(value)
if not res["id"] and not res["props"]:
print("1: %s" % raw_res)
print("2: %s" % cls)
print("3: %s" % resource_name)
raise ValueError("Failed to represent resource %r" %
raw_res)
all_resources.append(res)
return all_resources
class Keystone(ResourceManager):
REQUIRED_SERVICE = consts.Service.KEYSTONE
def list_users(self):
return self.client.users.list()
def list_tenants(self):
if hasattr(self.client, "projects"):
return self.client.projects.list() # V3
return self.client.tenants.list() # V2
def list_roles(self):
return self.client.roles.list()
class Magnum(ResourceManager):
REQUIRED_SERVICE = consts.Service.MAGNUM
def list_cluster_templates(self):
result = []
marker = None
while True:
ct_list = self.client.cluster_templates.list(marker=marker)
if not ct_list:
break
result.extend(ct_list)
marker = ct_list[-1].uuid
return result
def list_clusters(self):
result = []
marker = None
while True:
clusters = self.client.clusters.list(marker=marker)
if not clusters:
break
result.extend(clusters)
marker = clusters[-1].uuid
return result
class Mistral(ResourceManager):
REQUIRED_SERVICE = consts.Service.MISTRAL
def list_workbooks(self):
return self.client.workbooks.list()
def list_workflows(self):
return self.client.workflows.list()
def list_executions(self):
return self.client.executions.list()
class Nova(ResourceManager):
REQUIRED_SERVICE = consts.Service.NOVA
def list_flavors(self):
return self.client.flavors.list()
def list_aggregates(self):
return self.client.aggregates.list()
def list_hypervisors(self):
return self.client.hypervisors.list()
def list_keypairs(self):
return self.client.keypairs.list()
def list_servers(self):
return self.client.servers.list(
search_opts={"all_tenants": True})
def list_server_groups(self):
return self.client.server_groups.list(all_projects=True)
def list_services(self):
return self.client.services.list()
def list_availability_zones(self):
return self.client.availability_zones.list()
class Neutron(ResourceManager):
REQUIRED_SERVICE = consts.Service.NEUTRON
def has_extension(self, name):
extensions = self.client.list_extensions().get("extensions", [])
return any(ext.get("alias") == name for ext in extensions)
def list_networks(self):
return self.client.list_networks()["networks"]
def list_subnets(self):
return self.client.list_subnets()["subnets"]
def list_routers(self):
return self.client.list_routers()["routers"]
def list_ports(self):
return self.client.list_ports()["ports"]
def list_floatingips(self):
return self.client.list_floatingips()["floatingips"]
def list_security_groups(self):
return self.client.list_security_groups()["security_groups"]
def list_trunks(self):
if self.has_extension("trunks"):
return self.client.list_trunks()["trunks"]
def list_health_monitors(self):
if self.has_extension("lbaas"):
return self.client.list_health_monitors()["health_monitors"]
def list_pools(self):
if self.has_extension("lbaas"):
return self.client.list_pools()["pools"]
def list_vips(self):
if self.has_extension("lbaas"):
return self.client.list_vips()["vips"]
def list_bgpvpns(self):
if self.has_extension("bgpvpn"):
return self.client.list_bgpvpns()["bgpvpns"]
class Glance(ResourceManager):
REQUIRED_SERVICE = consts.Service.GLANCE
def list_images(self):
return self.client.images.list()
class Heat(ResourceManager):
REQUIRED_SERVICE = consts.Service.HEAT
def list_resource_types(self):
return self.client.resource_types.list()
def list_stacks(self):
return self.client.stacks.list()
class Cinder(ResourceManager):
REQUIRED_SERVICE = consts.Service.CINDER
def list_availability_zones(self):
return self.client.availability_zones.list()
def list_backups(self):
return self.client.backups.list()
def list_volume_snapshots(self):
return self.client.volume_snapshots.list()
def list_volume_types(self):
return self.client.volume_types.list()
def list_encryption_types(self):
return self.client.volume_encryption_types.list()
def list_transfers(self):
return self.client.transfers.list()
def list_volumes(self):
return self.client.volumes.list(search_opts={"all_tenants": True})
def list_qos(self):
return self.client.qos_specs.list()
class Senlin(ResourceManager):
REQUIRED_SERVICE = consts.Service.SENLIN
def list_clusters(self):
return self.client.clusters()
def list_profiles(self):
return self.client.profiles()
class Manila(ResourceManager):
REQUIRED_SERVICE = consts.Service.MANILA
def list_shares(self):
return self.client.shares.list(detailed=False,
search_opts={"all_tenants": True})
def list_share_networks(self):
return self.client.share_networks.list(
detailed=False, search_opts={"all_tenants": True})
def list_share_servers(self):
return self.client.share_servers.list(
search_opts={"all_tenants": True})
class Gnocchi(ResourceManager):
REQUIRED_SERVICE = consts.Service.GNOCCHI
def list_resources(self):
result = []
marker = None
while True:
resources = self.client.resource.list(marker=marker)
if not resources:
break
result.extend(resources)
marker = resources[-1]["id"]
return result
def list_archive_policy_rules(self):
return self.client.archive_policy_rule.list()
def list_archive_policys(self):
return self.client.archive_policy.list()
def list_resource_types(self):
return self.client.resource_type.list()
def list_metrics(self):
result = []
marker = None
while True:
metrics = self.client.metric.list(marker=marker)
if not metrics:
break
result.extend(metrics)
marker = metrics[-1]["id"]
return result
class Ironic(ResourceManager):
REQUIRED_SERVICE = consts.Service.IRONIC
def list_nodes(self):
return self.client.node.list()
class Sahara(ResourceManager):
REQUIRED_SERVICE = consts.Service.SAHARA
def list_node_group_templates(self):
return self.client.node_group_templates.list()
class Murano(ResourceManager):
REQUIRED_SERVICE = consts.Service.MURANO
def list_environments(self):
return self.client.environments.list()
def list_packages(self):
return self.client.packages.list(include_disabled=True)
class Designate(ResourceManager):
REQUIRED_SERVICE = consts.Service.DESIGNATE
def list_zones(self):
return self.clients.designate("2").zones.list()
def list_recordset(self):
client = self.clients.designate("2")
results = []
results.extend(client.recordsets.list(zone_id)
for zone_id in client.zones.list())
return results
class Trove(ResourceManager):
REQUIRED_SERVICE = consts.Service.TROVE
def list_backups(self):
return self.client.backup.list()
def list_clusters(self):
return self.client.cluster.list()
def list_configurations(self):
return self.client.configuration.list()
def list_databases(self):
return self.client.database.list()
def list_datastore(self):
return self.client.datastore.list()
def list_instances(self):
return self.client.list(include_clustered=True)
def list_modules(self):
return self.client.module.list(datastore="all")
class Monasca(ResourceManager):
REQUIRED_SERVICE = consts.Service.MONASCA
def list_metrics(self):
return self.client.metrics.list()
class Watcher(ResourceManager):
REQUIRED_SERVICE = consts.Service.WATCHER
REPR_KEYS = ("uuid", "name")
def list_audits(self):
return self.client.audit.list()
def list_audit_templates(self):
return self.client.audit_template.list()
def list_goals(self):
return self.client.goal.list()
def list_strategies(self):
return self.client.strategy.list()
def list_action_plans(self):
return self.client.action_plan.list()
class Octavia(ResourceManager):
REQUIRED_SERVICE = consts.Service.OCTAVIA
def list_load_balancers(self):
return self.client.load_balancer_list()["loadbalancers"]
def list_listeners(self):
return self.client.listener_list()["listeners"]
def list_pools(self):
return self.client.pool_list()["pools"]
def list_l7policies(self):
return self.client.l7policy_list()["l7policies"]
def list_health_monitors(self):
return self.client.health_monitor_list()["healthmonitors"]
def list_amphoras(self):
return self.client.amphora_list()["amphorae"]
class CloudResources(object):
"""List and compare cloud resources.
resources = CloudResources(auth_url=..., ...)
saved_list = resources.list()
# Do something with the cloud ...
changes = resources.compare(saved_list)
has_changed = any(changes)
removed, added = changes
"""
def __init__(self, **kwargs):
self.clients = credential.OpenStackCredential(**kwargs).clients()
def list(self):
managers_classes = discover.itersubclasses(ResourceManager)
resources = []
for cls in managers_classes:
manager = cls(self.clients)
if manager.is_available():
resources.extend(manager.get_resources())
return resources
def compare(self, with_list):
def make_uuid(res):
return "%s.%s:%s" % (
res["cls"], res["resource_name"],
";".join(["%s=%s" % (k, v)
for k, v in sorted(res["id"].items())]))
current_resources = dict((make_uuid(r), r) for r in self.list())
saved_resources = dict((make_uuid(r), r) for r in with_list)
removed = set(saved_resources.keys()) - set(current_resources.keys())
removed = [saved_resources[k] for k in sorted(removed)]
added = set(current_resources.keys()) - set(saved_resources.keys())
added = [current_resources[k] for k in sorted(added)]
return removed, added
def _print_tabular_resources(resources, table_label):
def dict_formatter(d):
return "\n".join("%s:%s" % (k, v) for k, v in d.items())
out = io.StringIO()
cliutils.print_list(
objs=[dict(r) for r in resources],
fields=("cls", "resource_name", "id", "fields"),
field_labels=("service", "resource type", "id", "fields"),
table_label=table_label,
formatters={"id": lambda d: dict_formatter(d["id"]),
"fields": lambda d: dict_formatter(d["props"])},
out=out
)
out.write("\n")
print(out.getvalue())
def dump_resources(resources_mgr, json_output):
resources_list = resources_mgr.list()
_print_tabular_resources(resources_list, "Available resources.")
if json_output:
with open(json_output, "w") as f:
f.write(json.dumps(resources_list))
return 0, resources_list
def check_resource(resources_mgs, compare_with, json_output):
with open(compare_with) as f:
compare_to = f.read()
compare_to = json.loads(compare_to)
changes = resources_mgs.compare(with_list=compare_to)
removed, added = changes
# Cinder has a feature - cache images for speeding-up time of creating
# volumes from images. let's put such cache-volumes into expected list
volume_names = [
"image-%s" % i["id"]["id"] for i in compare_to
if i["cls"] == "glance" and i["resource_name"] == "image"]
# filter out expected additions
expected = []
for resource in added:
if (False # <- makes indent of other cases similar
or (resource["cls"] == "keystone"
and resource["resource_name"] == "role"
and resource["id"].get("name") == "_member_")
or (resource["cls"] == "neutron"
and resource["resource_name"] == "security_group"
and resource["id"].get("name") == "default")
or (resource["cls"] == "cinder"
and resource["resource_name"] == "volume"
and resource["id"].get("name") in volume_names)
or resource["cls"] == "murano"
# Glance has issues with uWSGI integration...
# or resource["cls"] == "glance"
or resource["cls"] == "gnocchi"):
expected.append(resource)
for resource in expected:
added.remove(resource)
if removed:
_print_tabular_resources(removed, "Removed resources")
if added:
_print_tabular_resources(added, "Added resources (unexpected)")
if expected:
_print_tabular_resources(expected, "Added resources (expected)")
result = {"removed": removed, "added": added, "expected": expected}
if json_output:
with open(json_output, "w") as f:
f.write(json.dumps(result, indent=4))
rc = 1 if any(changes) else 0
return rc, result
@plugins.ensure_plugins_are_loaded
def do_it(json_output, compare_with):
out = subprocess.check_output(
["rally", "env", "show", "--only-spec", "--env", "devstack"])
config = json.loads(out.decode("utf-8"))
config = config["existing@openstack"]
config.update(config.pop("admin"))
if "users" in config:
del config["users"]
resources = CloudResources(**config)
if compare_with:
return check_resource(resources, compare_with, json_output)
else:
return dump_resources(resources, json_output)
def ansible_main():
module = AnsibleModule(
argument_spec=dict(
json_output=dict(required=False, type="str"),
compare_with=dict(required=False, type="path")
)
)
rc, json_result = do_it(
json_output=module.params.get("json_output"),
compare_with=module.params.get("compare_with")
)
if rc:
module.fail_json(
msg="Unexpected changes of resources are detected.",
rc=1,
resources=json_result
)
module.exit_json(rc=0, changed=True, resources=json_result)
if __name__ == "__main__":
ansible_main()
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,898
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/contexts/magnum/test_ca_certs.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally_openstack.task.contexts.magnum import ca_certs
from tests.unit import test
CTX = "rally_openstack.task.contexts.magnum"
SCN = "rally_openstack.task.scenarios"
class CaCertsGeneratorTestCase(test.ScenarioTestCase):
def _gen_tenants(self, count):
tenants = {}
for id_ in range(count):
tenants[str(id_)] = {"name": str(id_)}
tenants[str(id_)]["cluster"] = "rally_cluster_uuid"
return tenants
def test__generate_csr_and_key(self):
ca_cert_ctx = ca_certs.CaCertGenerator(self.context)
result = ca_cert_ctx._generate_csr_and_key()
assert result["csr"] is not None
assert result["key"] is not None
@mock.patch("%s.magnum.utils.MagnumScenario._create_ca_certificate" % SCN)
@mock.patch("%s.magnum.utils.MagnumScenario._get_ca_certificate" % SCN)
@mock.patch("%s.ca_certs.open" % CTX, side_effect=mock.mock_open(),
create=True)
@mock.patch("%s.ca_certs.CaCertGenerator._generate_csr_and_key"
% CTX)
@mock.patch("%s.magnum.utils.MagnumScenario._get_cluster_template" % SCN)
@mock.patch("%s.magnum.utils.MagnumScenario._get_cluster" % SCN,
return_value=mock.Mock())
def test_setup(self, mock_magnum_scenario__get_cluster,
mock_magnum_scenario__get_cluster_template,
mock_ca_cert_generator__generate_csr_and_key,
mock_open,
mock_magnum_scenario__get_ca_certificate,
mock_magnum_scenario__create_ca_certificate):
tenants_count = 2
users_per_tenant = 5
tenants = self._gen_tenants(tenants_count)
users = []
for ten_id in tenants:
for i in range(users_per_tenant):
users.append({"id": i, "tenant_id": ten_id,
"credential": mock.MagicMock()})
self.context.update({
"config": {
"users": {
"tenants": tenants_count,
"users_per_tenant": users_per_tenant,
"concurrent": 10,
},
"clusters": {
"cluster_template_uuid": "123456789",
"node_count": 2
},
"ca_certs": {
"directory": ""
}
},
"users": users,
"tenants": tenants
})
fake_ct = mock.Mock()
fake_ct.tls_disabled = False
mock_magnum_scenario__get_cluster_template.return_value = fake_ct
fake_tls = {"csr": "fake_csr", "key": "fake_key"}
mock_ca_cert_generator__generate_csr_and_key.return_value = fake_tls
fake_ca_cert = mock.Mock()
fake_ca_cert.pem = "fake_ca_cert"
mock_magnum_scenario__get_ca_certificate.return_value = fake_ca_cert
fake_cert = mock.Mock()
fake_cert.pem = "fake_cert"
mock_magnum_scenario__create_ca_certificate.return_value = fake_cert
ca_cert_ctx = ca_certs.CaCertGenerator(self.context)
ca_cert_ctx.setup()
mock_cluster = mock_magnum_scenario__get_cluster.return_value
mock_calls = [mock.call(mock_cluster.cluster_template_id)
for i in range(tenants_count)]
mock_magnum_scenario__get_cluster_template.assert_has_calls(
mock_calls)
mock_calls = [mock.call("rally_cluster_uuid")
for i in range(tenants_count)]
mock_magnum_scenario__get_cluster.assert_has_calls(mock_calls)
mock_magnum_scenario__get_ca_certificate.assert_has_calls(mock_calls)
fake_csr_req = {"cluster_uuid": "rally_cluster_uuid",
"csr": fake_tls["csr"]}
mock_calls = [mock.call(fake_csr_req)
for i in range(tenants_count)]
mock_magnum_scenario__create_ca_certificate.assert_has_calls(
mock_calls)
@mock.patch("%s.magnum.utils.MagnumScenario._create_ca_certificate" % SCN)
@mock.patch("%s.magnum.utils.MagnumScenario._get_ca_certificate" % SCN)
@mock.patch("%s.magnum.utils.MagnumScenario._get_cluster_template" % SCN)
@mock.patch("%s.magnum.utils.MagnumScenario._get_cluster" % SCN,
return_value=mock.Mock())
def test_tls_disabled_setup(self, mock_magnum_scenario__get_cluster,
mock_magnum_scenario__get_cluster_template,
mock_magnum_scenario__get_ca_certificate,
mock_magnum_scenario__create_ca_certificate):
tenants_count = 2
users_per_tenant = 5
tenants = self._gen_tenants(tenants_count)
users = []
for ten_id in tenants:
for i in range(users_per_tenant):
users.append({"id": i, "tenant_id": ten_id,
"credential": mock.MagicMock()})
self.context.update({
"config": {
"users": {
"tenants": tenants_count,
"users_per_tenant": users_per_tenant,
"concurrent": 10,
},
"clusters": {
"cluster_template_uuid": "123456789",
"node_count": 2
},
"ca_certs": {
"directory": ""
}
},
"users": users,
"tenants": tenants
})
fake_ct = mock.Mock()
fake_ct.tls_disabled = True
mock_magnum_scenario__get_cluster_template.return_value = fake_ct
ca_cert_ctx = ca_certs.CaCertGenerator(self.context)
ca_cert_ctx.setup()
mock_cluster = mock_magnum_scenario__get_cluster.return_value
mock_calls = [mock.call(mock_cluster.cluster_template_id)
for i in range(tenants_count)]
mock_magnum_scenario__get_cluster_template.assert_has_calls(
mock_calls)
mock_calls = [mock.call("rally_cluster_uuid")
for i in range(tenants_count)]
mock_magnum_scenario__get_cluster.assert_has_calls(mock_calls)
mock_magnum_scenario__get_ca_certificate.assert_not_called()
mock_magnum_scenario__create_ca_certificate.assert_not_called()
@mock.patch("os.remove", return_value=mock.Mock())
@mock.patch("os.path.join", return_value=mock.Mock())
@mock.patch("%s.magnum.utils.MagnumScenario._get_cluster_template" % SCN)
@mock.patch("%s.magnum.utils.MagnumScenario._get_cluster" % SCN,
return_value=mock.Mock())
def test_cleanup(self, mock_magnum_scenario__get_cluster,
mock_magnum_scenario__get_cluster_template,
mock_os_path_join, mock_os_remove):
tenants_count = 2
users_per_tenant = 5
tenants = self._gen_tenants(tenants_count)
users = []
for ten_id in tenants:
for i in range(users_per_tenant):
users.append({"id": i, "tenant_id": ten_id,
"credential": mock.MagicMock()})
self.context.update({
"config": {
},
"ca_certs_directory": "",
"users": users,
"tenants": tenants
})
fake_ct = mock.Mock()
fake_ct.tls_disabled = False
mock_magnum_scenario__get_cluster_template.return_value = fake_ct
ca_cert_ctx = ca_certs.CaCertGenerator(self.context)
ca_cert_ctx.cleanup()
cluster_uuid = "rally_cluster_uuid"
dir = self.context["ca_certs_directory"]
mock_os_path_join.assert_has_calls(dir, cluster_uuid.__add__(".key"))
mock_os_path_join.assert_has_calls(
dir, cluster_uuid.__add__("_ca.crt"))
mock_os_path_join.assert_has_calls(dir, cluster_uuid.__add__(".crt"))
@mock.patch("os.remove", return_value=mock.Mock())
@mock.patch("os.path.join", return_value=mock.Mock())
@mock.patch("%s.magnum.utils.MagnumScenario._get_cluster_template" % SCN)
@mock.patch("%s.magnum.utils.MagnumScenario._get_cluster" % SCN,
return_value=mock.Mock())
def test_tls_disabled_cleanup(self, mock_magnum_scenario__get_cluster,
mock_magnum_scenario__get_cluster_template,
mock_os_path_join, mock_os_remove):
tenants_count = 2
users_per_tenant = 5
tenants = self._gen_tenants(tenants_count)
users = []
for ten_id in tenants:
for i in range(users_per_tenant):
users.append({"id": i, "tenant_id": ten_id,
"credential": mock.MagicMock()})
self.context.update({
"config": {
},
"ca_certs_directory": "",
"users": users,
"tenants": tenants
})
fake_ct = mock.Mock()
fake_ct.tls_disabled = True
mock_magnum_scenario__get_cluster_template.return_value = fake_ct
ca_cert_ctx = ca_certs.CaCertGenerator(self.context)
ca_cert_ctx.cleanup()
mock_os_path_join.assert_not_called()
mock_os_remove.assert_not_called()
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,899
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/scenarios/sahara/node_group_templates.py
|
# Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.task import types
from rally.task import validation
from rally_openstack.common import consts
from rally_openstack.task import scenario
from rally_openstack.task.scenarios.sahara import utils
"""Scenarios for Sahara node group templates."""
@types.convert(flavor={"type": "nova_flavor"})
@validation.add("flavor_exists", param_name="flavor")
@validation.add("required_services", services=[consts.Service.SAHARA])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(
context={"cleanup@openstack": ["sahara"]},
name="SaharaNodeGroupTemplates.create_and_list_node_group_templates",
platform="openstack")
class CreateAndListNodeGroupTemplates(utils.SaharaScenario):
def run(self, flavor, plugin_name="vanilla",
hadoop_version="1.2.1", use_autoconfig=True):
"""Create and list Sahara Node Group Templates.
This scenario creates two Node Group Templates with different set of
node processes. The master Node Group Template contains Hadoop's
management processes. The worker Node Group Template contains
Hadoop's worker processes.
By default the templates are created for the vanilla Hadoop
provisioning plugin using the version 1.2.1
After the templates are created the list operation is called.
:param flavor: Nova flavor that will be for nodes in the
created node groups
:param plugin_name: name of a provisioning plugin
:param hadoop_version: version of Hadoop distribution supported by
the specified plugin.
:param use_autoconfig: If True, instances of the node group will be
automatically configured during cluster
creation. If False, the configuration values
should be specify manually
"""
self._create_master_node_group_template(flavor_id=flavor,
plugin_name=plugin_name,
hadoop_version=hadoop_version,
use_autoconfig=use_autoconfig)
self._create_worker_node_group_template(flavor_id=flavor,
plugin_name=plugin_name,
hadoop_version=hadoop_version,
use_autoconfig=use_autoconfig)
self._list_node_group_templates()
@types.convert(flavor={"type": "nova_flavor"})
@validation.add("flavor_exists", param_name="flavor")
@validation.add("required_services", services=[consts.Service.SAHARA])
@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(
context={"cleanup@openstack": ["sahara"]},
name="SaharaNodeGroupTemplates.create_delete_node_group_templates",
platform="openstack")
class CreateDeleteNodeGroupTemplates(utils.SaharaScenario):
def run(self, flavor, plugin_name="vanilla",
hadoop_version="1.2.1", use_autoconfig=True):
"""Create and delete Sahara Node Group Templates.
This scenario creates and deletes two most common types of
Node Group Templates.
By default the templates are created for the vanilla Hadoop
provisioning plugin using the version 1.2.1
:param flavor: Nova flavor that will be for nodes in the
created node groups
:param plugin_name: name of a provisioning plugin
:param hadoop_version: version of Hadoop distribution supported by
the specified plugin.
:param use_autoconfig: If True, instances of the node group will be
automatically configured during cluster
creation. If False, the configuration values
should be specify manually
"""
master_ngt = self._create_master_node_group_template(
flavor_id=flavor,
plugin_name=plugin_name,
hadoop_version=hadoop_version,
use_autoconfig=use_autoconfig)
worker_ngt = self._create_worker_node_group_template(
flavor_id=flavor,
plugin_name=plugin_name,
hadoop_version=hadoop_version,
use_autoconfig=use_autoconfig)
self._delete_node_group_template(master_ngt)
self._delete_node_group_template(worker_ngt)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,900
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/common/services/identity/test_keystone_common.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally_openstack.common import osclients
from rally_openstack.common import service
from rally_openstack.common.services.identity import identity
from rally_openstack.common.services.identity import keystone_common
from tests.unit import test
class FullUnifiedKeystone(keystone_common.UnifiedKeystoneMixin,
service.Service):
"""Implementation of UnifiedKeystoneMixin with Service base class."""
pass
class UnifiedKeystoneMixinTestCase(test.TestCase):
def setUp(self):
super(UnifiedKeystoneMixinTestCase, self).setUp()
self.clients = mock.MagicMock()
self.name_generator = mock.MagicMock()
self.impl = mock.MagicMock()
self.version = "some"
self.service = FullUnifiedKeystone(
clients=self.clients, name_generator=self.name_generator)
self.service._impl = self.impl
self.service.version = self.version
def test__unify_service(self):
class SomeFakeService(object):
id = 123123123123123
name = "asdfasdfasdfasdfadf"
other_var = "asdfasdfasdfasdfasdfasdfasdf"
service = self.service._unify_service(SomeFakeService())
self.assertIsInstance(service, identity.Service)
self.assertEqual(SomeFakeService.id, service.id)
self.assertEqual(SomeFakeService.name, service.name)
def test__unify_role(self):
class SomeFakeRole(object):
id = 123123123123123
name = "asdfasdfasdfasdfadf"
other_var = "asdfasdfasdfasdfasdfasdfasdf"
role = self.service._unify_role(SomeFakeRole())
self.assertIsInstance(role, identity.Role)
self.assertEqual(SomeFakeRole.id, role.id)
self.assertEqual(SomeFakeRole.name, role.name)
def test_delete_user(self):
user_id = "id"
self.service.delete_user(user_id)
self.impl.delete_user.assert_called_once_with(user_id)
def test_get_user(self):
user_id = "id"
self.service._unify_user = mock.MagicMock()
self.assertEqual(self.service._unify_user.return_value,
self.service.get_user(user_id))
self.impl.get_user.assert_called_once_with(user_id)
self.service._unify_user.assert_called_once_with(
self.impl.get_user.return_value)
def test_create_service(self):
self.service._unify_service = mock.MagicMock()
name = "some_Service"
service_type = "computeNextGen"
description = "we will Rock you!"
self.assertEqual(self.service._unify_service.return_value,
self.service.create_service(
name=name, service_type=service_type,
description=description))
self.service._unify_service.assert_called_once_with(
self.service._impl.create_service.return_value)
self.service._impl.create_service.assert_called_once_with(
name=name, service_type=service_type, description=description)
def test_delete_service(self):
service_id = "id"
self.service.delete_service(service_id)
self.impl.delete_service.assert_called_once_with(service_id)
def test_get_service(self):
service_id = "id"
self.service._unify_service = mock.MagicMock()
self.assertEqual(self.service._unify_service.return_value,
self.service.get_service(service_id))
self.impl.get_service.assert_called_once_with(service_id)
self.service._unify_service.assert_called_once_with(
self.impl.get_service.return_value)
def test_get_service_by_name(self):
service_id = "id"
self.service._unify_service = mock.MagicMock()
self.assertEqual(self.service._unify_service.return_value,
self.service.get_service_by_name(service_id))
self.impl.get_service_by_name.assert_called_once_with(service_id)
self.service._unify_service.assert_called_once_with(
self.impl.get_service_by_name.return_value)
def test_delete_role(self):
role_id = "id"
self.service.delete_role(role_id)
self.impl.delete_role.assert_called_once_with(role_id)
def test_get_role(self):
role_id = "id"
self.service._unify_role = mock.MagicMock()
self.assertEqual(self.service._unify_role.return_value,
self.service.get_role(role_id))
self.impl.get_role.assert_called_once_with(role_id)
self.service._unify_role.assert_called_once_with(
self.impl.get_role.return_value)
def test_list_ec2credentials(self):
user_id = "id"
self.assertEqual(self.impl.list_ec2credentials.return_value,
self.service.list_ec2credentials(user_id))
self.impl.list_ec2credentials.assert_called_once_with(user_id)
def test_delete_ec2credential(self):
user_id = "id"
access = mock.MagicMock()
self.assertEqual(self.impl.delete_ec2credential.return_value,
self.service.delete_ec2credential(user_id,
access=access))
self.impl.delete_ec2credential.assert_called_once_with(user_id=user_id,
access=access)
def test_fetch_token(self):
self.assertEqual(self.impl.fetch_token.return_value,
self.service.fetch_token())
self.impl.fetch_token.assert_called_once_with()
def test_validate_token(self):
token = "id"
self.assertEqual(self.impl.validate_token.return_value,
self.service.validate_token(token))
self.impl.validate_token.assert_called_once_with(token)
class FullKeystone(service.Service, keystone_common.KeystoneMixin):
"""Implementation of KeystoneMixin with Service base class."""
pass
class KeystoneMixinTestCase(test.TestCase):
def setUp(self):
super(KeystoneMixinTestCase, self).setUp()
self.clients = mock.MagicMock()
self.kc = self.clients.keystone.return_value
self.name_generator = mock.MagicMock()
self.version = "some"
self.service = FullKeystone(
clients=self.clients, name_generator=self.name_generator)
self.service.version = self.version
def test_list_users(self):
self.assertEqual(self.kc.users.list.return_value,
self.service.list_users())
self.kc.users.list.assert_called_once_with()
def test_delete_user(self):
user_id = "fake_id"
self.service.delete_user(user_id)
self.kc.users.delete.assert_called_once_with(user_id)
def test_get_user(self):
user_id = "fake_id"
self.service.get_user(user_id)
self.kc.users.get.assert_called_once_with(user_id)
def test_delete_service(self):
service_id = "fake_id"
self.service.delete_service(service_id)
self.kc.services.delete.assert_called_once_with(service_id)
def test_list_services(self):
self.assertEqual(self.kc.services.list.return_value,
self.service.list_services())
self.kc.services.list.assert_called_once_with()
def test_get_service(self):
service_id = "fake_id"
self.service.get_service(service_id)
self.kc.services.get.assert_called_once_with(service_id)
def test_get_service_by_name(self):
class FakeService(object):
def __init__(self, name):
self.name = name
service_name = "fake_name"
services = [FakeService(name="foo"), FakeService(name=service_name),
FakeService(name="bar")]
self.service.list_services = mock.MagicMock(return_value=services)
self.assertEqual(services[1],
self.service.get_service_by_name(service_name))
def test_delete_role(self):
role_id = "fake_id"
self.service.delete_role(role_id)
self.kc.roles.delete.assert_called_once_with(role_id)
def test_list_roles(self):
self.assertEqual(self.kc.roles.list.return_value,
self.service.list_roles())
self.kc.roles.list.assert_called_once_with()
def test_get_role(self):
role_id = "fake_id"
self.service.get_role(role_id)
self.kc.roles.get.assert_called_once_with(role_id)
def test_list_ec2credentials(self):
user_id = "fake_id"
self.assertEqual(self.kc.ec2.list.return_value,
self.service.list_ec2credentials(user_id))
self.kc.ec2.list.assert_called_once_with(user_id)
def test_delete_ec2credentials(self):
user_id = "fake_id"
access = mock.MagicMock()
self.service.delete_ec2credential(user_id, access=access)
self.kc.ec2.delete.assert_called_once_with(user_id=user_id,
access=access)
@mock.patch("rally_openstack.common.osclients.Clients",
spec=osclients.Clients)
def test_fetch_token(self, mock_clients):
mock_clients.return_value = mock.Mock(keystone=mock.Mock())
expected_token = mock_clients.return_value.keystone.auth_ref.auth_token
self.assertEqual(expected_token, self.service.fetch_token())
mock_clients.assert_called_once_with(
credential=self.clients.credential)
def test_validate_token(self):
token = "some_token"
self.service.validate_token(token)
self.kc.tokens.validate.assert_called_once_with(token)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,901
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/functional/test_certification_task.py
|
# Copyright 2014: Mirantis Inc.
# Copyright 2014: Catalyst IT Ltd.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import traceback
import unittest
import rally_openstack
from tests.functional import utils
class TestPreCreatedTasks(unittest.TestCase):
def test_task_samples_is_valid(self):
rally = utils.Rally()
full_path = os.path.join(
os.path.dirname(rally_openstack.__file__), os.pardir,
"tasks", "openstack")
task_path = os.path.join(full_path, "task.yaml")
args_path = os.path.join(full_path, "task_arguments.yaml")
try:
rally("task validate --task %s --task-args-file %s" % (task_path,
args_path))
except Exception:
print(traceback.format_exc())
self.fail("Wrong task config %s" % full_path)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,902
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/neutron/test_loadbalancer_v2.py
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
import ddt
from rally_openstack.task.scenarios.neutron import loadbalancer_v2
from tests.unit import test
@ddt.ddt
class NeutronLoadbalancerv2TestCase(test.TestCase):
def _get_context(self):
context = test.get_test_context()
context.update({
"user": {
"id": "fake_user",
"tenant_id": "fake_tenant",
"credential": mock.MagicMock()
},
"tenant": {"id": "fake_tenant",
"networks": [{"id": "fake_net",
"subnets": ["fake_subnet"]}]}})
return context
@ddt.data(
{},
{"lb_create_args": None},
{"lb_create_args": {}},
{"lb_create_args": {"name": "given-name"}},
)
@ddt.unpack
def test_create_and_list_load_balancers(self, lb_create_args=None):
context = self._get_context()
scenario = loadbalancer_v2.CreateAndListLoadbalancers(context)
lb_create_args = lb_create_args or {}
networks = context["tenant"]["networks"]
scenario._create_lbaasv2_loadbalancer = mock.Mock()
scenario._list_lbaasv2_loadbalancers = mock.Mock()
scenario.run(lb_create_args=lb_create_args)
subnets = []
mock_has_calls = []
for network in networks:
subnets.extend(network.get("subnets", []))
for subnet in subnets:
mock_has_calls.append(mock.call(subnet, **lb_create_args))
scenario._create_lbaasv2_loadbalancer.assert_has_calls(mock_has_calls)
scenario._list_lbaasv2_loadbalancers.assert_called_once_with()
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,903
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/contexts/manila/manila_share_networks.py
|
# Copyright 2015 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.common import cfg
from rally.common import logging
from rally.common import validation
from rally import exceptions
from rally_openstack.common import consts as rally_consts
from rally_openstack.task.cleanup import manager as resource_manager
from rally_openstack.task import context
from rally_openstack.task.contexts.manila import consts
from rally_openstack.task.scenarios.manila import utils as manila_utils
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
CONTEXT_NAME = consts.SHARE_NETWORKS_CONTEXT_NAME
SHARE_NETWORKS_ARG_DESCR = """
This context arg will be used only when context arg "use_share_networks" is
set to True.
If context arg 'share_networks' has values then they will be used else share
networks will be autocreated - one for each tenant network. If networks do not
exist then will be created one share network for each tenant without network
data.
Expected value is dict of lists where tenant Name or ID is key and list of
share_network Names or IDs is value. Example:
.. code-block:: json
"context": {
"manila_share_networks": {
"use_share_networks": true,
"share_networks": {
"tenant_1_name_or_id": ["share_network_1_name_or_id",
"share_network_2_name_or_id"],
"tenant_2_name_or_id": ["share_network_3_name_or_id"]}
}
}
Also, make sure that all 'existing users' in appropriate registered deployment
have share networks if its usage is enabled, else Rally will randomly take
users that does not satisfy criteria.
"""
@validation.add("required_platform", platform="openstack", users=True)
@context.configure(name=CONTEXT_NAME, platform="openstack", order=450)
class ShareNetworks(context.OpenStackContext):
"""This context creates share networks for Manila project."""
CONFIG_SCHEMA = {
"type": "object",
"$schema": rally_consts.JSON_SCHEMA,
"properties": {
"use_share_networks": {
"type": "boolean",
"description": "Specifies whether manila should use share "
"networks for share creation or not."},
"share_networks": {
"type": "object",
"description": SHARE_NETWORKS_ARG_DESCR,
"additionalProperties": True
},
},
"additionalProperties": False
}
DEFAULT_CONFIG = {
"use_share_networks": False,
"share_networks": {},
}
def _setup_for_existing_users(self):
if (self.config["use_share_networks"]
and not self.config["share_networks"]):
msg = ("Usage of share networks was enabled but for deployment "
"with existing users share networks also should be "
"specified via arg 'share_networks'")
raise exceptions.ContextSetupFailure(
ctx_name=self.get_name(), msg=msg)
for tenant_name_or_id, share_networks in self.config[
"share_networks"].items():
# Verify project existence
for tenant in self.context["tenants"].values():
if tenant_name_or_id in (tenant["id"], tenant["name"]):
tenant_id = tenant["id"]
existing_user = None
for user in self.context["users"]:
if user["tenant_id"] == tenant_id:
existing_user = user
break
break
else:
msg = ("Provided tenant Name or ID '%s' was not found in "
"existing tenants.") % tenant_name_or_id
raise exceptions.ContextSetupFailure(
ctx_name=self.get_name(), msg=msg)
self.context["tenants"][tenant_id][CONTEXT_NAME] = {}
self.context["tenants"][tenant_id][CONTEXT_NAME][
"share_networks"] = []
manila_scenario = manila_utils.ManilaScenario({
"user": existing_user
})
existing_sns = manila_scenario._list_share_networks(
detailed=False, search_opts={"project_id": tenant_id})
for sn_name_or_id in share_networks:
# Verify share network existence
for sn in existing_sns:
if sn_name_or_id in (sn.id, sn.name):
break
else:
msg = ("Specified share network '%(sn)s' does not "
"exist for tenant '%(tenant_id)s'"
% {"sn": sn_name_or_id, "tenant_id": tenant_id})
raise exceptions.ContextSetupFailure(
ctx_name=self.get_name(), msg=msg)
# Set share network for project
self.context["tenants"][tenant_id][CONTEXT_NAME][
"share_networks"].append(sn.to_dict())
def _setup_for_autocreated_users(self):
# Create share network for each network of tenant
for user, tenant_id in (self._iterate_per_tenants(
self.context.get("users", []))):
networks = self.context["tenants"][tenant_id].get("networks")
manila_scenario = manila_utils.ManilaScenario({
"task": self.task,
"owner_id": self.get_owner_id(),
"user": user
})
manila_scenario.RESOURCE_NAME_FORMAT = self.RESOURCE_NAME_FORMAT
self.context["tenants"][tenant_id][CONTEXT_NAME] = {
"share_networks": []}
data = {}
def _setup_share_network(tenant_id, data):
share_network = manila_scenario._create_share_network(
**data).to_dict()
self.context["tenants"][tenant_id][CONTEXT_NAME][
"share_networks"].append(share_network)
for ss in self.context["tenants"][tenant_id].get(
consts.SECURITY_SERVICES_CONTEXT_NAME, {}).get(
"security_services", []):
manila_scenario._add_security_service_to_share_network(
share_network["id"], ss["id"])
if networks:
for network in networks:
if network.get("cidr"):
data["nova_net_id"] = network["id"]
elif network.get("subnets"):
data["neutron_net_id"] = network["id"]
data["neutron_subnet_id"] = network["subnets"][0]
else:
LOG.warning("Can't determine network service provider."
" Share network will have no data.")
_setup_share_network(tenant_id, data)
else:
_setup_share_network(tenant_id, data)
def setup(self):
self.context[CONTEXT_NAME] = {}
if not self.config["use_share_networks"]:
pass
elif self.context["config"].get("existing_users"):
self._setup_for_existing_users()
else:
self._setup_for_autocreated_users()
def cleanup(self):
if (not self.context["config"].get("existing_users")
or self.config["use_share_networks"]):
resource_manager.cleanup(
names=["manila.share_networks"],
users=self.context.get("users", []),
superclass=self.__class__,
task_id=self.get_owner_id())
else:
# NOTE(vponomaryov): assume that share networks were not created
# by test run.
return
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,904
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/contexts/manila/test_manila_security_services.py
|
# Copyright 2015 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
import ddt
from rally_openstack.task.contexts.manila import consts
from rally_openstack.task.contexts.manila import manila_security_services
from rally_openstack.task.scenarios.manila import utils as manila_utils
from tests.unit import test
CONTEXT_NAME = consts.SECURITY_SERVICES_CONTEXT_NAME
@ddt.ddt
class SecurityServicesTestCase(test.ScenarioTestCase):
TENANTS_AMOUNT = 3
USERS_PER_TENANT = 4
SECURITY_SERVICES = [
{"security_service_type": ss_type,
"dns_ip": "fake_dns_ip_%s" % ss_type,
"server": "fake_server_%s" % ss_type,
"domain": "fake_domain_%s" % ss_type,
"user": "fake_user_%s" % ss_type,
"password": "fake_password_%s" % ss_type}
for ss_type in ("ldap", "kerberos", "active_directory")
]
def _get_context(self, security_services=None, networks_per_tenant=2,
neutron_network_provider=True):
if security_services is None:
security_services = self.SECURITY_SERVICES
tenants = {}
for t_id in range(self.TENANTS_AMOUNT):
tenants[str(t_id)] = {"name": str(t_id)}
tenants[str(t_id)]["networks"] = []
for i in range(networks_per_tenant):
network = {"id": "fake_net_id_%s" % i}
if neutron_network_provider:
network["subnets"] = ["fake_subnet_id_of_net_%s" % i]
else:
network["cidr"] = "101.0.5.0/24"
tenants[str(t_id)]["networks"].append(network)
users = []
for t_id in tenants.keys():
for i in range(self.USERS_PER_TENANT):
users.append({"id": i, "tenant_id": t_id, "endpoint": "fake"})
context = {
"config": {
"users": {
"tenants": self.TENANTS_AMOUNT,
"users_per_tenant": self.USERS_PER_TENANT,
},
CONTEXT_NAME: {
"security_services": security_services,
},
},
"admin": {
"endpoint": mock.MagicMock(),
},
"task": mock.MagicMock(),
"owner_id": "foo_uuid",
"users": users,
"tenants": tenants,
}
return context
def test_init(self):
context = {
"task": mock.MagicMock(),
"config": {
CONTEXT_NAME: {"foo": "bar"},
"not_manila": {"not_manila_key": "not_manila_value"},
}
}
inst = manila_security_services.SecurityServices(context)
self.assertEqual("bar", inst.config.get("foo"))
self.assertFalse(inst.config.get("security_services"))
self.assertEqual(445, inst.get_order())
self.assertEqual(CONTEXT_NAME, inst.get_name())
@mock.patch.object(manila_security_services.manila_utils, "ManilaScenario")
@ddt.data(True, False)
def test_setup_security_services_set(self, neutron_network_provider,
mock_manila_scenario):
ctxt = self._get_context(
neutron_network_provider=neutron_network_provider)
inst = manila_security_services.SecurityServices(ctxt)
inst.setup()
self.assertEqual(
self.TENANTS_AMOUNT, mock_manila_scenario.call_count)
self.assertEqual(
mock_manila_scenario.call_args_list,
[mock.call({
"task": inst.task,
"owner_id": "foo_uuid",
"user": user})
for user in inst.context["users"] if user["id"] == 0]
)
mock_create_security_service = (
mock_manila_scenario.return_value._create_security_service)
expected_calls = []
for ss in self.SECURITY_SERVICES:
expected_calls.extend([mock.call(**ss), mock.call().to_dict()])
mock_create_security_service.assert_has_calls(expected_calls)
self.assertEqual(
self.TENANTS_AMOUNT * len(self.SECURITY_SERVICES),
mock_create_security_service.call_count)
self.assertEqual(
self.TENANTS_AMOUNT,
len(inst.context["config"][CONTEXT_NAME]["security_services"]))
for tenant in inst.context["tenants"]:
self.assertEqual(
self.TENANTS_AMOUNT,
len(inst.context["tenants"][tenant][CONTEXT_NAME][
"security_services"])
)
@mock.patch.object(manila_security_services.manila_utils, "ManilaScenario")
def test_setup_security_services_not_set(self, mock_manila_scenario):
ctxt = self._get_context(security_services=[])
inst = manila_security_services.SecurityServices(ctxt)
inst.setup()
self.assertFalse(mock_manila_scenario.called)
self.assertFalse(
mock_manila_scenario.return_value._create_security_service.called)
self.assertIn(CONTEXT_NAME, inst.context["config"])
self.assertIn(
"security_services", inst.context["config"][CONTEXT_NAME])
self.assertEqual(
0,
len(inst.context["config"][CONTEXT_NAME]["security_services"]))
for tenant in inst.context["tenants"]:
self.assertEqual(
0,
len(inst.context["tenants"][tenant][CONTEXT_NAME][
"security_services"])
)
@mock.patch.object(manila_security_services, "resource_manager")
def test_cleanup_security_services_enabled(self, mock_resource_manager):
ctxt = self._get_context()
inst = manila_security_services.SecurityServices(ctxt)
inst.cleanup()
mock_resource_manager.cleanup.assert_called_once_with(
names=["manila.security_services"],
users=ctxt["users"],
superclass=manila_utils.ManilaScenario,
task_id="foo_uuid")
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,905
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/common/cfg/nova.py
|
# Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.common import cfg
OPTS = {"openstack": [
# prepoll delay, timeout, poll interval
# "start": (0, 300, 1)
cfg.FloatOpt("nova_server_start_prepoll_delay",
default=0.0,
deprecated_group="benchmark",
help="Time to sleep after start before polling for status"),
cfg.FloatOpt("nova_server_start_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server start timeout"),
cfg.FloatOpt("nova_server_start_poll_interval",
deprecated_group="benchmark",
default=1.0,
help="Server start poll interval"),
# "stop": (0, 300, 2)
cfg.FloatOpt("nova_server_stop_prepoll_delay",
default=0.0,
help="Time to sleep after stop before polling for status"),
cfg.FloatOpt("nova_server_stop_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server stop timeout"),
cfg.FloatOpt("nova_server_stop_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server stop poll interval"),
# "boot": (1, 300, 1)
cfg.FloatOpt("nova_server_boot_prepoll_delay",
default=1.0,
deprecated_group="benchmark",
help="Time to sleep after boot before polling for status"),
cfg.FloatOpt("nova_server_boot_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server boot timeout"),
cfg.FloatOpt("nova_server_boot_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server boot poll interval"),
# "delete": (2, 300, 2)
cfg.FloatOpt("nova_server_delete_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time to sleep after delete before polling for status"),
cfg.FloatOpt("nova_server_delete_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server delete timeout"),
cfg.FloatOpt("nova_server_delete_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server delete poll interval"),
# "reboot": (2, 300, 2)
cfg.FloatOpt("nova_server_reboot_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time to sleep after reboot before polling for status"),
cfg.FloatOpt("nova_server_reboot_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server reboot timeout"),
cfg.FloatOpt("nova_server_reboot_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server reboot poll interval"),
# "rebuild": (1, 300, 1)
cfg.FloatOpt("nova_server_rebuild_prepoll_delay",
default=1.0,
deprecated_group="benchmark",
help="Time to sleep after rebuild before polling for status"),
cfg.FloatOpt("nova_server_rebuild_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server rebuild timeout"),
cfg.FloatOpt("nova_server_rebuild_poll_interval",
default=1.0,
deprecated_group="benchmark",
help="Server rebuild poll interval"),
# "rescue": (2, 300, 2)
cfg.FloatOpt("nova_server_rescue_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time to sleep after rescue before polling for status"),
cfg.FloatOpt("nova_server_rescue_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server rescue timeout"),
cfg.FloatOpt("nova_server_rescue_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server rescue poll interval"),
# "unrescue": (2, 300, 2)
cfg.FloatOpt("nova_server_unrescue_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time to sleep after unrescue "
"before polling for status"),
cfg.FloatOpt("nova_server_unrescue_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server unrescue timeout"),
cfg.FloatOpt("nova_server_unrescue_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server unrescue poll interval"),
# "suspend": (2, 300, 2)
cfg.FloatOpt("nova_server_suspend_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time to sleep after suspend before polling for status"),
cfg.FloatOpt("nova_server_suspend_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server suspend timeout"),
cfg.FloatOpt("nova_server_suspend_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server suspend poll interval"),
# "resume": (2, 300, 2)
cfg.FloatOpt("nova_server_resume_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time to sleep after resume before polling for status"),
cfg.FloatOpt("nova_server_resume_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server resume timeout"),
cfg.FloatOpt("nova_server_resume_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server resume poll interval"),
# "pause": (2, 300, 2)
cfg.FloatOpt("nova_server_pause_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time to sleep after pause before polling for status"),
cfg.FloatOpt("nova_server_pause_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server pause timeout"),
cfg.FloatOpt("nova_server_pause_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server pause poll interval"),
# "unpause": (2, 300, 2)
cfg.FloatOpt("nova_server_unpause_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time to sleep after unpause before polling for status"),
cfg.FloatOpt("nova_server_unpause_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server unpause timeout"),
cfg.FloatOpt("nova_server_unpause_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server unpause poll interval"),
# "shelve": (2, 300, 2)
cfg.FloatOpt("nova_server_shelve_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time to sleep after shelve before polling for status"),
cfg.FloatOpt("nova_server_shelve_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server shelve timeout"),
cfg.FloatOpt("nova_server_shelve_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server shelve poll interval"),
# "unshelve": (2, 300, 2)
cfg.FloatOpt("nova_server_unshelve_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time to sleep after unshelve before "
"polling for status"),
cfg.FloatOpt("nova_server_unshelve_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server unshelve timeout"),
cfg.FloatOpt("nova_server_unshelve_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server unshelve poll interval"),
# "image_create": (0, 300, 2)
cfg.FloatOpt("nova_server_image_create_prepoll_delay",
default=0.0,
deprecated_group="benchmark",
help="Time to sleep after image_create before polling"
" for status"),
cfg.FloatOpt("nova_server_image_create_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server image_create timeout"),
cfg.FloatOpt("nova_server_image_create_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server image_create poll interval"),
# "image_delete": (0, 300, 2)
cfg.FloatOpt("nova_server_image_delete_prepoll_delay",
default=0.0,
deprecated_group="benchmark",
help="Time to sleep after image_delete before polling"
" for status"),
cfg.FloatOpt("nova_server_image_delete_timeout",
default=300.0,
deprecated_group="benchmark",
help="Server image_delete timeout"),
cfg.FloatOpt("nova_server_image_delete_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server image_delete poll interval"),
# "resize": (2, 400, 5)
cfg.FloatOpt("nova_server_resize_prepoll_delay",
default=2.0,
deprecated_group="benchmark",
help="Time to sleep after resize before polling for status"),
cfg.FloatOpt("nova_server_resize_timeout",
default=400.0,
deprecated_group="benchmark",
help="Server resize timeout"),
cfg.FloatOpt("nova_server_resize_poll_interval",
default=4.0,
deprecated_group="benchmark",
help="Server resize poll interval"),
# "resize_confirm": (0, 200, 2)
cfg.FloatOpt("nova_server_resize_confirm_prepoll_delay",
default=0.0,
deprecated_group="benchmark",
help="Time to sleep after resize_confirm before polling"
" for status"),
cfg.FloatOpt("nova_server_resize_confirm_timeout",
default=200.0,
deprecated_group="benchmark",
help="Server resize_confirm timeout"),
cfg.FloatOpt("nova_server_resize_confirm_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server resize_confirm poll interval"),
# "resize_revert": (0, 200, 2)
cfg.FloatOpt("nova_server_resize_revert_prepoll_delay",
default=0.0,
deprecated_group="benchmark",
help="Time to sleep after resize_revert before polling"
" for status"),
cfg.FloatOpt("nova_server_resize_revert_timeout",
default=200.0,
deprecated_group="benchmark",
help="Server resize_revert timeout"),
cfg.FloatOpt("nova_server_resize_revert_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server resize_revert poll interval"),
# "live_migrate": (1, 400, 2)
cfg.FloatOpt("nova_server_live_migrate_prepoll_delay",
default=1.0,
deprecated_group="benchmark",
help="Time to sleep after live_migrate before polling"
" for status"),
cfg.FloatOpt("nova_server_live_migrate_timeout",
default=400.0,
deprecated_group="benchmark",
help="Server live_migrate timeout"),
cfg.FloatOpt("nova_server_live_migrate_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server live_migrate poll interval"),
# "migrate": (1, 400, 2)
cfg.FloatOpt("nova_server_migrate_prepoll_delay",
default=1.0,
deprecated_group="benchmark",
help="Time to sleep after migrate before polling for status"),
cfg.FloatOpt("nova_server_migrate_timeout",
default=400.0,
deprecated_group="benchmark",
help="Server migrate timeout"),
cfg.FloatOpt("nova_server_migrate_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Server migrate poll interval"),
# "detach":
cfg.FloatOpt("nova_detach_volume_timeout",
default=200.0,
deprecated_group="benchmark",
help="Nova volume detach timeout"),
cfg.FloatOpt("nova_detach_volume_poll_interval",
default=2.0,
deprecated_group="benchmark",
help="Nova volume detach poll interval")
]}
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,906
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/heat/test_utils.py
|
# Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally import exceptions
from rally_openstack.task.scenarios.heat import utils
from tests.unit import test
HEAT_UTILS = "rally_openstack.task.scenarios.heat.utils"
CONF = utils.CONF
class HeatScenarioTestCase(test.ScenarioTestCase):
def setUp(self):
super(HeatScenarioTestCase, self).setUp()
self.stack = mock.Mock()
self.scenario = utils.HeatScenario(self.context)
self.default_template = "heat_template_version: 2013-05-23"
self.dummy_parameters = {"dummy_param": "dummy_key"}
self.dummy_files = ["dummy_file.yaml"]
self.dummy_environment = {"dummy_env": "dummy_env_value"}
self.default_output_key = "dummy_output_key"
def test_list_stacks(self):
scenario = utils.HeatScenario(self.context)
return_stacks_list = scenario._list_stacks()
self.clients("heat").stacks.list.assert_called_once_with()
self.assertEqual(list(self.clients("heat").stacks.list.return_value),
return_stacks_list)
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.list_stacks")
def test_create_stack(self):
self.clients("heat").stacks.create.return_value = {
"stack": {"id": "test_id"}
}
self.clients("heat").stacks.get.return_value = self.stack
return_stack = self.scenario._create_stack(self.default_template,
self.dummy_parameters,
self.dummy_files,
self.dummy_environment)
args, kwargs = self.clients("heat").stacks.create.call_args
self.assertIn(self.dummy_parameters, kwargs.values())
self.assertIn(self.default_template, kwargs.values())
self.assertIn(self.dummy_files, kwargs.values())
self.assertIn(self.dummy_environment, kwargs.values())
self.mock_wait_for_status.mock.assert_called_once_with(
self.stack,
update_resource=self.mock_get_from_manager.mock.return_value,
ready_statuses=["CREATE_COMPLETE"],
failure_statuses=["CREATE_FAILED", "ERROR"],
check_interval=CONF.openstack.heat_stack_create_poll_interval,
timeout=CONF.openstack.heat_stack_create_timeout)
self.mock_get_from_manager.mock.assert_called_once_with()
self.assertEqual(self.mock_wait_for_status.mock.return_value,
return_stack)
self._test_atomic_action_timer(self.scenario.atomic_actions(),
"heat.create_stack")
def test_update_stack(self):
self.clients("heat").stacks.update.return_value = None
scenario = utils.HeatScenario(self.context)
scenario._update_stack(self.stack, self.default_template,
self.dummy_parameters, self.dummy_files,
self.dummy_environment)
args, kwargs = self.clients("heat").stacks.update.call_args
self.assertIn(self.dummy_parameters, kwargs.values())
self.assertIn(self.default_template, kwargs.values())
self.assertIn(self.dummy_files, kwargs.values())
self.assertIn(self.dummy_environment, kwargs.values())
self.assertIn(self.stack.id, args)
self.mock_wait_for_status.mock.assert_called_once_with(
self.stack,
update_resource=self.mock_get_from_manager.mock.return_value,
ready_statuses=["UPDATE_COMPLETE"],
failure_statuses=["UPDATE_FAILED", "ERROR"],
check_interval=CONF.openstack.heat_stack_update_poll_interval,
timeout=CONF.openstack.heat_stack_update_timeout)
self.mock_get_from_manager.mock.assert_called_once_with()
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.update_stack")
def test_check_stack(self):
scenario = utils.HeatScenario(self.context)
scenario._check_stack(self.stack)
self.clients("heat").actions.check.assert_called_once_with(
self.stack.id)
self.mock_wait_for_status.mock.assert_called_once_with(
self.stack,
update_resource=self.mock_get_from_manager.mock.return_value,
ready_statuses=["CHECK_COMPLETE"],
failure_statuses=["CHECK_FAILED", "ERROR"],
check_interval=CONF.openstack.heat_stack_check_poll_interval,
timeout=CONF.openstack.heat_stack_check_timeout)
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.check_stack")
def test_delete_stack(self):
scenario = utils.HeatScenario(self.context)
scenario._delete_stack(self.stack)
self.stack.delete.assert_called_once_with()
self.mock_wait_for_status.mock.assert_called_once_with(
self.stack,
ready_statuses=["DELETE_COMPLETE"],
failure_statuses=["DELETE_FAILED", "ERROR"],
check_deletion=True,
update_resource=self.mock_get_from_manager.mock.return_value,
check_interval=CONF.openstack.heat_stack_delete_poll_interval,
timeout=CONF.openstack.heat_stack_delete_timeout)
self.mock_get_from_manager.mock.assert_called_once_with()
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.delete_stack")
def test_suspend_stack(self):
scenario = utils.HeatScenario(self.context)
scenario._suspend_stack(self.stack)
self.clients("heat").actions.suspend.assert_called_once_with(
self.stack.id)
self.mock_wait_for_status.mock.assert_called_once_with(
self.stack,
update_resource=self.mock_get_from_manager.mock.return_value,
ready_statuses=["SUSPEND_COMPLETE"],
failure_statuses=["SUSPEND_FAILED", "ERROR"],
check_interval=CONF.openstack.heat_stack_suspend_poll_interval,
timeout=CONF.openstack.heat_stack_suspend_timeout)
self.mock_get_from_manager.mock.assert_called_once_with()
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.suspend_stack")
def test_resume_stack(self):
scenario = utils.HeatScenario(self.context)
scenario._resume_stack(self.stack)
self.clients("heat").actions.resume.assert_called_once_with(
self.stack.id)
self.mock_wait_for_status.mock.assert_called_once_with(
self.stack,
update_resource=self.mock_get_from_manager.mock.return_value,
ready_statuses=["RESUME_COMPLETE"],
failure_statuses=["RESUME_FAILED", "ERROR"],
check_interval=CONF.openstack.heat_stack_resume_poll_interval,
timeout=CONF.openstack.heat_stack_resume_timeout)
self.mock_get_from_manager.mock.assert_called_once_with()
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.resume_stack")
def test_snapshot_stack(self):
scenario = utils.HeatScenario(self.context)
scenario._snapshot_stack(self.stack)
self.clients("heat").stacks.snapshot.assert_called_once_with(
self.stack.id)
self.mock_wait_for_status.mock.assert_called_once_with(
self.stack,
update_resource=self.mock_get_from_manager.mock.return_value,
ready_statuses=["SNAPSHOT_COMPLETE"],
failure_statuses=["SNAPSHOT_FAILED", "ERROR"],
check_interval=CONF.openstack.heat_stack_snapshot_poll_interval,
timeout=CONF.openstack.heat_stack_snapshot_timeout)
self.mock_get_from_manager.mock.assert_called_once_with()
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.snapshot_stack")
def test_restore_stack(self):
scenario = utils.HeatScenario(self.context)
scenario._restore_stack(self.stack, "dummy_id")
self.clients("heat").stacks.restore.assert_called_once_with(
self.stack.id, "dummy_id")
self.mock_wait_for_status.mock.assert_called_once_with(
self.stack,
update_resource=self.mock_get_from_manager.mock.return_value,
ready_statuses=["RESTORE_COMPLETE"],
failure_statuses=["RESTORE_FAILED", "ERROR"],
check_interval=CONF.openstack.heat_stack_restore_poll_interval,
timeout=CONF.openstack.heat_stack_restore_timeout)
self.mock_get_from_manager.mock.assert_called_once_with()
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.restore_stack")
def test__count_instances(self):
self.clients("heat").resources.list.return_value = [
mock.Mock(resource_type="OS::Nova::Server"),
mock.Mock(resource_type="OS::Nova::Server"),
mock.Mock(resource_type="OS::Heat::AutoScalingGroup")]
scenario = utils.HeatScenario(self.context)
self.assertEqual(scenario._count_instances(self.stack), 2)
self.clients("heat").resources.list.assert_called_once_with(
self.stack.id,
nested_depth=1)
def test__scale_stack(self):
scenario = utils.HeatScenario(self.context)
scenario._count_instances = mock.Mock(side_effect=[3, 3, 2])
scenario._stack_webhook = mock.Mock()
scenario._scale_stack(self.stack, "test_output_key", -1)
scenario._stack_webhook.assert_called_once_with(self.stack,
"test_output_key")
self.mock_wait_for.mock.assert_called_once_with(
self.stack,
is_ready=mock.ANY,
failure_statuses=["UPDATE_FAILED", "ERROR"],
update_resource=self.mock_get_from_manager.mock.return_value,
timeout=CONF.openstack.heat_stack_scale_timeout,
check_interval=CONF.openstack.heat_stack_scale_poll_interval)
self.mock_get_from_manager.mock.assert_called_once_with()
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.scale_with_test_output_key")
@mock.patch("requests.post")
def test_stack_webhook(self, mock_post):
env_context = {
"env": {
"spec": {
"existing@openstack": {
"https_cacert": "cacert.crt",
"https_insecure": False
}
}
}
}
env_context.update(self.context)
scenario = utils.HeatScenario(env_context)
stack = mock.Mock(outputs=[
{"output_key": "output1", "output_value": "url1"},
{"output_key": "output2", "output_value": "url2"}])
scenario._stack_webhook(stack, "output1")
mock_post.assert_called_with("url1", verify="cacert.crt")
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.output1_webhook")
@mock.patch("requests.post")
def test_stack_webhook_insecure(self, mock_post):
env_context = {
"env": {
"spec": {
"existing@openstack": {
"https_cacert": "cacert.crt",
"https_insecure": True
}
}
}
}
env_context.update(self.context)
scenario = utils.HeatScenario(env_context)
stack = mock.Mock(outputs=[
{"output_key": "output1", "output_value": "url1"},
{"output_key": "output2", "output_value": "url2"}])
scenario._stack_webhook(stack, "output1")
mock_post.assert_called_with("url1", verify=False)
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.output1_webhook")
@mock.patch("requests.post")
def test_stack_webhook_invalid_output_key(self, mock_post):
scenario = utils.HeatScenario(self.context)
stack = mock.Mock()
stack.outputs = [{"output_key": "output1", "output_value": "url1"},
{"output_key": "output2", "output_value": "url2"}]
self.assertRaises(exceptions.InvalidConfigException,
scenario._stack_webhook, stack, "bogus")
def test_stack_show_output(self):
scenario = utils.HeatScenario(self.context)
scenario._stack_show_output(self.stack, self.default_output_key)
self.clients("heat").stacks.output_show.assert_called_once_with(
self.stack.id, self.default_output_key)
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.show_output")
def test_stack_show_output_via_API(self):
scenario = utils.HeatScenario(self.context)
scenario._stack_show_output_via_API(
self.stack, self.default_output_key)
self.clients("heat").stacks.get.assert_called_once_with(
stack_id=self.stack.id)
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.show_output_via_API")
def test_stack_list_output(self):
scenario = utils.HeatScenario(self.context)
scenario._stack_list_output(self.stack)
self.clients("heat").stacks.output_list.assert_called_once_with(
self.stack.id)
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.list_output")
def test_stack_list_output_via_API(self):
scenario = utils.HeatScenario(self.context)
scenario._stack_list_output_via_API(self.stack)
self.clients("heat").stacks.get.assert_called_once_with(
stack_id=self.stack.id)
self._test_atomic_action_timer(scenario.atomic_actions(),
"heat.list_output_via_API")
class HeatScenarioNegativeTestCase(test.ScenarioTestCase):
patch_task_utils = False
def test_failed_create_stack(self):
self.clients("heat").stacks.create.return_value = {
"stack": {"id": "test_id"}
}
stack = mock.Mock()
resource = mock.Mock()
resource.stack_status = "CREATE_FAILED"
stack.manager.get.return_value = resource
self.clients("heat").stacks.get.return_value = stack
scenario = utils.HeatScenario(context=self.context)
ex = self.assertRaises(exceptions.GetResourceErrorStatus,
scenario._create_stack, "stack_name")
self.assertIn("has CREATE_FAILED status", str(ex))
def test_failed_update_stack(self):
stack = mock.Mock()
resource = mock.Mock()
resource.stack_status = "UPDATE_FAILED"
stack.manager.get.return_value = resource
self.clients("heat").stacks.get.return_value = stack
scenario = utils.HeatScenario(context=self.context)
ex = self.assertRaises(exceptions.GetResourceErrorStatus,
scenario._update_stack, stack,
"heat_template_version: 2013-05-23")
self.assertIn("has UPDATE_FAILED status", str(ex))
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,907
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/common/services/image/glance_common.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally import exceptions
from rally.task import atomic
from rally_openstack.common.services.image import image as image_service
class GlanceMixin(object):
def _get_client(self):
return self._clients.glance(self.version)
def get_image(self, image):
"""Get specified image.
:param image: ID or object with ID of image to obtain.
"""
from glanceclient import exc as glance_exc
image_id = getattr(image, "id", image)
try:
aname = "glance_v%s.get_image" % self.version
with atomic.ActionTimer(self, aname):
return self._get_client().images.get(image_id)
except glance_exc.HTTPNotFound:
raise exceptions.GetResourceNotFound(resource=image)
def delete_image(self, image_id):
"""Delete image."""
aname = "glance_v%s.delete_image" % self.version
with atomic.ActionTimer(self, aname):
self._get_client().images.delete(image_id)
def download_image(self, image_id, do_checksum=True):
"""Retrieve data of an image.
:param image_id: ID of the image to download.
:param do_checksum: Enable/disable checksum validation.
:returns: An iterable body or None
"""
aname = "glance_v%s.download_image" % self.version
with atomic.ActionTimer(self, aname):
return self._get_client().images.data(image_id,
do_checksum=do_checksum)
class UnifiedGlanceMixin(object):
@staticmethod
def _unify_image(image):
if hasattr(image, "visibility"):
return image_service.UnifiedImage(id=image.id, name=image.name,
status=image.status,
visibility=image.visibility)
else:
return image_service.UnifiedImage(
id=image.id, name=image.name,
status=image.status,
visibility=("public" if image.is_public else "private"))
def get_image(self, image):
"""Get specified image.
:param image: ID or object with ID of image to obtain.
"""
image_obj = self._impl.get_image(image=image)
return self._unify_image(image_obj)
def delete_image(self, image_id):
"""Delete image."""
self._impl.delete_image(image_id=image_id)
def download_image(self, image_id, do_checksum=True):
"""Download data for an image.
:param image_id: image id to look up
:param do_checksum: Enable/disable checksum validation
:rtype: iterable containing image data or None
"""
return self._impl.download_image(image_id, do_checksum=do_checksum)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,908
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/contexts/glance/test_images.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
from unittest import mock
import ddt
from rally_openstack.task.contexts.glance import images
from tests.unit import test
CTX = "rally_openstack.task.contexts.glance.images"
SCN = "rally_openstack.task.scenarios.glance"
@ddt.ddt
class ImageGeneratorTestCase(test.ScenarioTestCase):
tenants_num = 1
users_per_tenant = 5
users_num = tenants_num * users_per_tenant
threads = 10
def setUp(self):
super(ImageGeneratorTestCase, self).setUp()
self.context.update({
"config": {
"users": {
"tenants": self.tenants_num,
"users_per_tenant": self.users_per_tenant,
"resource_management_workers": self.threads,
}
},
"admin": {"credential": mock.MagicMock()},
"users": [],
"task": {"uuid": "task_id"}
})
patch = mock.patch(
"rally_openstack.common.services.image.image.Image")
self.addCleanup(patch.stop)
self.mock_image = patch.start()
def _gen_tenants(self, count):
tenants = {}
for id_ in range(count):
tenants[str(id_)] = {"name": str(id_)}
return tenants
@ddt.data(
{},
{"min_disk": 1, "min_ram": 2},
{"image_name": "foo"},
{"tenants": 3, "users_per_tenant": 2, "images_per_tenant": 5})
@ddt.unpack
@mock.patch("rally_openstack.common.osclients.Clients")
def test_setup(self, mock_clients,
container_format="bare", disk_format="qcow2",
image_url="http://example.com/fake/url",
tenants=1, users_per_tenant=1, images_per_tenant=1,
image_name=None, min_ram=None, min_disk=None,
visibility="public"):
image_service = self.mock_image.return_value
tenant_data = self._gen_tenants(tenants)
users = []
for tenant_id in tenant_data:
for i in range(users_per_tenant):
users.append({"id": i, "tenant_id": tenant_id,
"credential": mock.MagicMock()})
self.context.update({
"config": {
"users": {
"tenants": tenants,
"users_per_tenant": users_per_tenant,
"concurrent": 10,
},
"images": {
"image_url": image_url,
"disk_format": disk_format,
"container_format": container_format,
"images_per_tenant": images_per_tenant,
"visibility": visibility,
}
},
"admin": {
"credential": mock.MagicMock()
},
"users": users,
"tenants": tenant_data
})
expected_image_args = {}
if image_name is not None:
self.context["config"]["images"]["image_name"] = image_name
if min_ram is not None:
self.context["config"]["images"]["min_ram"] = min_ram
expected_image_args["min_ram"] = min_ram
if min_disk is not None:
self.context["config"]["images"]["min_disk"] = min_disk
expected_image_args["min_disk"] = min_disk
new_context = copy.deepcopy(self.context)
for tenant_id in new_context["tenants"].keys():
new_context["tenants"][tenant_id]["images"] = [
image_service.create_image.return_value.id
] * images_per_tenant
images_ctx = images.ImageGenerator(self.context)
images_ctx.setup()
self.assertEqual(new_context, self.context)
wrapper_calls = []
wrapper_calls.extend([mock.call(mock_clients.return_value.glance,
images_ctx)] * tenants)
wrapper_calls.extend(
[mock.call().create_image(
container_format, image_url, disk_format,
name=mock.ANY, **expected_image_args)]
* tenants * images_per_tenant)
mock_clients.assert_has_calls([mock.call(mock.ANY)] * tenants)
@mock.patch("%s.image.Image" % CTX)
@mock.patch("%s.LOG" % CTX)
def test_setup_with_deprecated_args(self, mock_log, mock_image):
image_type = "itype"
image_container = "icontainer"
is_public = True
d_min_ram = mock.Mock()
d_min_disk = mock.Mock()
self.context.update({
"config": {
"images": {"image_type": image_type,
"image_container": image_container,
"image_args": {"is_public": is_public,
"min_ram": d_min_ram,
"min_disk": d_min_disk}}
},
"users": [{"tenant_id": "foo-tenant",
"credential": mock.MagicMock()}],
"tenants": {"foo-tenant": {}}
})
images_ctx = images.ImageGenerator(self.context)
images_ctx.setup()
mock_image.return_value.create_image.assert_called_once_with(
image_name=None,
container_format=image_container,
image_location=None,
disk_format=image_type,
visibility="public",
min_disk=d_min_disk,
min_ram=d_min_ram
)
expected_warns = [
mock.call("The 'image_type' argument is deprecated since "
"Rally 0.10.0, use disk_format argument instead"),
mock.call("The 'image_container' argument is deprecated since "
"Rally 0.10.0; use container_format argument instead"),
mock.call("The 'image_args' argument is deprecated since "
"Rally 0.10.0; specify arguments in a root "
"section of context instead")]
self.assertEqual(expected_warns, mock_log.warning.call_args_list)
mock_image.return_value.create_image.reset_mock()
mock_log.warning.reset_mock()
min_ram = mock.Mock()
min_disk = mock.Mock()
visibility = "foo"
disk_format = "dformat"
container_format = "cformat"
self.context["config"]["images"].update({
"min_ram": min_ram,
"min_disk": min_disk,
"visibility": visibility,
"disk_format": disk_format,
"container_format": container_format
})
images_ctx = images.ImageGenerator(self.context)
images_ctx.setup()
# check that deprecated arguments are not used
mock_image.return_value.create_image.assert_called_once_with(
image_name=None,
container_format=container_format,
image_location=None,
disk_format=disk_format,
visibility=visibility,
min_disk=min_disk,
min_ram=min_ram
)
# No matter will be deprecated arguments used or not, if they are
# specified, warning message should be printed.
self.assertEqual(expected_warns, mock_log.warning.call_args_list)
@ddt.data({"admin": True})
@ddt.unpack
@mock.patch("%s.resource_manager.cleanup" % CTX)
def test_cleanup(self, mock_cleanup, admin=None):
images_per_tenant = 5
tenants = self._gen_tenants(self.tenants_num)
users = []
created_images = []
for tenant_id in tenants:
for i in range(self.users_per_tenant):
users.append({"id": i, "tenant_id": tenant_id,
"credential": mock.MagicMock()})
tenants[tenant_id].setdefault("images", [])
for j in range(images_per_tenant):
image = mock.Mock()
created_images.append(image)
tenants[tenant_id]["images"].append(image)
self.context.update({
"config": {
"users": {
"tenants": self.tenants_num,
"users_per_tenant": self.users_per_tenant,
"concurrent": 10,
},
"images": {}
},
"users": mock.Mock()
})
if admin:
self.context["admin"] = {"credential": mock.MagicMock()}
else:
# ensure that there is no admin
self.context.pop("admin")
images_ctx = images.ImageGenerator(self.context)
images_ctx.cleanup()
mock_cleanup.assert_called_once_with(
names=["glance.images", "cinder.image_volumes_cache"],
admin=self.context.get("admin"),
admin_required=None if admin else False,
users=self.context["users"],
superclass=images_ctx.__class__,
task_id=self.context["owner_id"])
@mock.patch("%s.rutils.make_name_matcher" % CTX)
@mock.patch("%s.resource_manager.cleanup" % CTX)
def test_cleanup_for_predefined_name(self, mock_cleanup,
mock_make_name_matcher):
self.context.update({
"config": {
"images": {"image_name": "foo"}
},
"users": mock.Mock()
})
images_ctx = images.ImageGenerator(self.context)
images_ctx.cleanup()
mock_cleanup.assert_called_once_with(
names=["glance.images", "cinder.image_volumes_cache"],
admin=self.context.get("admin"),
admin_required=None,
users=self.context["users"],
superclass=mock_make_name_matcher.return_value,
task_id=self.context["owner_id"])
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,909
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/contexts/sahara/test_sahara_cluster.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from rally.common import cfg
from rally import exceptions
from rally_openstack.task.contexts.sahara import sahara_cluster
from rally_openstack.task.scenarios.sahara import utils as sahara_utils
from tests.unit import test
CONF = cfg.CONF
CTX = "rally_openstack.task.contexts.sahara"
class SaharaClusterTestCase(test.ScenarioTestCase):
patch_task_utils = False
def setUp(self):
super(SaharaClusterTestCase, self).setUp()
self.tenants_num = 2
self.users_per_tenant = 2
self.users = self.tenants_num * self.users_per_tenant
self.tenants = {}
self.users_key = []
for i in range(self.tenants_num):
self.tenants[str(i)] = {"id": str(i), "name": str(i),
"sahara": {"image": "42"}}
for j in range(self.users_per_tenant):
self.users_key.append({"id": "%s_%s" % (str(i), str(j)),
"tenant_id": str(i),
"credential": mock.MagicMock()})
CONF.set_override("sahara_cluster_check_interval", 0, "openstack")
self.context.update({
"config": {
"users": {
"tenants": self.tenants_num,
"users_per_tenant": self.users_per_tenant
},
"sahara_cluster": {
"master_flavor_id": "test_flavor_m",
"worker_flavor_id": "test_flavor_w",
"workers_count": 2,
"plugin_name": "test_plugin",
"hadoop_version": "test_version"
}
},
"admin": {"credential": mock.MagicMock()},
"users": self.users_key,
"tenants": self.tenants
})
@mock.patch("%s.sahara_cluster.resource_manager.cleanup" % CTX)
@mock.patch("%s.sahara_cluster.utils.SaharaScenario._launch_cluster" % CTX,
return_value=mock.MagicMock(id=42))
def test_setup_and_cleanup(self, mock_sahara_scenario__launch_cluster,
mock_cleanup):
sahara_ctx = sahara_cluster.SaharaCluster(self.context)
launch_cluster_calls = []
for i in self.tenants:
launch_cluster_calls.append(mock.call(
flavor_id=None,
plugin_name="test_plugin",
hadoop_version="test_version",
master_flavor_id="test_flavor_m",
worker_flavor_id="test_flavor_w",
workers_count=2,
image_id=self.context["tenants"][i]["sahara"]["image"],
floating_ip_pool=None,
volumes_per_node=None,
volumes_size=1,
auto_security_group=True,
security_groups=None,
node_configs=None,
cluster_configs=None,
enable_anti_affinity=False,
enable_proxy=False,
wait_active=False,
use_autoconfig=True
))
self.clients("sahara").clusters.get.side_effect = [
mock.MagicMock(status="not-active"),
mock.MagicMock(status="active")]
sahara_ctx.setup()
mock_sahara_scenario__launch_cluster.assert_has_calls(
launch_cluster_calls)
sahara_ctx.cleanup()
mock_cleanup.assert_called_once_with(
names=["sahara.clusters"],
users=self.context["users"],
superclass=sahara_utils.SaharaScenario,
task_id=self.context["owner_id"])
@mock.patch("%s.sahara_cluster.utils.SaharaScenario._launch_cluster" % CTX,
return_value=mock.MagicMock(id=42))
def test_setup_and_cleanup_error(self,
mock_sahara_scenario__launch_cluster):
sahara_ctx = sahara_cluster.SaharaCluster(self.context)
launch_cluster_calls = []
for i in self.tenants:
launch_cluster_calls.append(mock.call(
flavor_id=None,
plugin_name="test_plugin",
hadoop_version="test_version",
master_flavor_id="test_flavor_m",
worker_flavor_id="test_flavor_w",
workers_count=2,
image_id=self.context["tenants"][i]["sahara"]["image"],
floating_ip_pool=None,
volumes_per_node=None,
volumes_size=1,
auto_security_groups=True,
security_groups=None,
node_configs=None,
cluster_configs=None,
wait_active=False,
use_autoconfig=True
))
self.clients("sahara").clusters.get.side_effect = [
mock.MagicMock(status="not-active"),
mock.MagicMock(status="error")
]
self.assertRaises(exceptions.ContextSetupFailure, sahara_ctx.setup)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,910
|
openstack/rally-openstack
|
refs/heads/master
|
/rally_openstack/task/scenarios/octavia/loadbalancers.py
|
# Copyright 2018: Red Hat Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally.task import validation
from rally_openstack.common import consts
from rally_openstack.task import scenario
from rally_openstack.task.scenarios.octavia import utils as octavia_utils
"""Scenarios for Octavia Loadbalancer."""
@validation.add("required_services", services=[consts.Service.OCTAVIA])
@validation.add("required_platform", platform="openstack", users=True)
@validation.add("required_contexts", contexts=["network"])
@scenario.configure(context={"cleanup@openstack": ["octavia"]},
name="Octavia.create_and_list_loadbalancers",
platform="openstack")
class CreateAndListLoadbalancers(octavia_utils.OctaviaBase):
def run(self, description=None, admin_state=True,
listeners=None, flavor_id=None, provider=None,
vip_qos_policy_id=None):
"""Create a loadbalancer per each subnet and then list loadbalancers.
:param description: Human-readable description of the loadbalancer
:param admin_state: The administrative state of the loadbalancer,
which is up(true) or down(false)
:param listeners: The associated listener id, if any
:param flavor_id: The ID of the flavor
:param provider: Provider name for the loadbalancer
:param vip_qos_policy_id: The ID of the QoS policy
"""
subnets = []
loadbalancers = []
networks = self.context.get("tenant", {}).get("networks", [])
project_id = self.context["tenant"]["id"]
for network in networks:
subnets.extend(network.get("subnets", []))
for subnet_id in subnets:
lb = self.octavia.load_balancer_create(
subnet_id=subnet_id,
description=description,
admin_state=admin_state,
project_id=project_id,
listeners=listeners,
flavor_id=flavor_id,
provider=provider,
vip_qos_policy_id=vip_qos_policy_id)
loadbalancers.append(lb)
for loadbalancer in loadbalancers:
self.octavia.wait_for_loadbalancer_prov_status(loadbalancer)
self.octavia.load_balancer_list()
@validation.add("required_services", services=[consts.Service.OCTAVIA])
@validation.add("required_platform", platform="openstack", users=True)
@validation.add("required_contexts", contexts=["network"])
@scenario.configure(context={"cleanup@openstack": ["octavia"]},
name="Octavia.create_and_delete_loadbalancers",
platform="openstack")
class CreateAndDeleteLoadbalancers(octavia_utils.OctaviaBase):
def run(self, description=None, admin_state=True,
listeners=None, flavor_id=None, provider=None,
vip_qos_policy_id=None):
"""Create a loadbalancer per each subnet and then delete loadbalancer
:param description: Human-readable description of the loadbalancer
:param admin_state: The administrative state of the loadbalancer,
which is up(true) or down(false)
:param listeners: The associated listener id, if any
:param flavor_id: The ID of the flavor
:param provider: Provider name for the loadbalancer
:param vip_qos_policy_id: The ID of the QoS policy
"""
subnets = []
loadbalancers = []
networks = self.context.get("tenant", {}).get("networks", [])
project_id = self.context["tenant"]["id"]
for network in networks:
subnets.extend(network.get("subnets", []))
for subnet_id in subnets:
lb = self.octavia.load_balancer_create(
subnet_id=subnet_id,
description=description,
admin_state=admin_state,
project_id=project_id,
listeners=listeners,
flavor_id=flavor_id,
provider=provider,
vip_qos_policy_id=vip_qos_policy_id)
loadbalancers.append(lb)
for loadbalancer in loadbalancers:
self.octavia.wait_for_loadbalancer_prov_status(loadbalancer)
self.octavia.load_balancer_delete(
loadbalancer["id"])
@validation.add("required_services", services=[consts.Service.OCTAVIA])
@validation.add("required_platform", platform="openstack", users=True)
@validation.add("required_contexts", contexts=["network"])
@scenario.configure(context={"cleanup@openstack": ["octavia"]},
name="Octavia.create_and_update_loadbalancers",
platform="openstack")
class CreateAndUpdateLoadBalancers(octavia_utils.OctaviaBase):
def run(self, description=None, admin_state=True,
listeners=None, flavor_id=None, provider=None,
vip_qos_policy_id=None):
"""Create a loadbalancer per each subnet and then update
:param description: Human-readable description of the loadbalancer
:param admin_state: The administrative state of the loadbalancer,
which is up(true) or down(false)
:param listeners: The associated listener id, if any
:param flavor_id: The ID of the flavor
:param provider: Provider name for the loadbalancer
:param vip_qos_policy_id: The ID of the QoS policy
"""
subnets = []
loadbalancers = []
networks = self.context.get("tenant", {}).get("networks", [])
project_id = self.context["tenant"]["id"]
for network in networks:
subnets.extend(network.get("subnets", []))
for subnet_id in subnets:
lb = self.octavia.load_balancer_create(
subnet_id=subnet_id,
description=description,
admin_state=admin_state,
project_id=project_id,
listeners=listeners,
flavor_id=flavor_id,
provider=provider,
vip_qos_policy_id=vip_qos_policy_id)
loadbalancers.append(lb)
update_loadbalancer = {
"name": self.generate_random_name()
}
for loadbalancer in loadbalancers:
self.octavia.wait_for_loadbalancer_prov_status(loadbalancer)
self.octavia.load_balancer_set(
lb_id=loadbalancer["id"],
lb_update_args=update_loadbalancer)
@validation.add("required_services", services=[consts.Service.OCTAVIA])
@validation.add("required_platform", platform="openstack", users=True)
@validation.add("required_contexts", contexts=["network"])
@scenario.configure(context={"cleanup@openstack": ["octavia"]},
name="Octavia.create_and_stats_loadbalancers",
platform="openstack")
class CreateAndShowStatsLoadBalancers(octavia_utils.OctaviaBase):
def run(self, description=None, admin_state=True,
listeners=None, flavor_id=None, provider=None,
vip_qos_policy_id=None):
"""Create a loadbalancer per each subnet and stats
:param description: Human-readable description of the loadbalancer
:param admin_state: The administrative state of the loadbalancer,
which is up(true) or down(false)
:param listeners: The associated listener id, if any
:param flavor_id: The ID of the flavor
:param provider: Provider name for the loadbalancer
:param vip_qos_policy_id: The ID of the QoS policy
"""
subnets = []
loadbalancers = []
networks = self.context.get("tenant", {}).get("networks", [])
project_id = self.context["tenant"]["id"]
for network in networks:
subnets.extend(network.get("subnets", []))
for subnet_id in subnets:
lb = self.octavia.load_balancer_create(
subnet_id=subnet_id,
description=description,
admin_state=admin_state,
project_id=project_id,
listeners=listeners,
flavor_id=flavor_id,
provider=provider,
vip_qos_policy_id=vip_qos_policy_id)
loadbalancers.append(lb)
for loadbalancer in loadbalancers:
self.octavia.wait_for_loadbalancer_prov_status(loadbalancer)
self.octavia.load_balancer_stats_show(
loadbalancer["id"])
@validation.add("required_services", services=[consts.Service.OCTAVIA])
@validation.add("required_platform", platform="openstack", users=True)
@validation.add("required_contexts", contexts=["network"])
@scenario.configure(context={"cleanup@openstack": ["octavia"]},
name="Octavia.create_and_show_loadbalancers",
platform="openstack")
class CreateAndShowLoadBalancers(octavia_utils.OctaviaBase):
def run(self, description=None, admin_state=True,
listeners=None, flavor_id=None, provider=None,
vip_qos_policy_id=None):
"""Create a loadbalancer per each subnet and then compare
:param description: Human-readable description of the loadbalancer
:param admin_state: The administrative state of the loadbalancer,
which is up(true) or down(false)
:param listeners: The associated listener id, if any
:param flavor_id: The ID of the flavor
:param provider: Provider name for the loadbalancer
:param vip_qos_policy_id: The ID of the QoS policy
"""
subnets = []
loadbalancers = []
networks = self.context.get("tenant", {}).get("networks", [])
project_id = self.context["tenant"]["id"]
for network in networks:
subnets.extend(network.get("subnets", []))
for subnet_id in subnets:
lb = self.octavia.load_balancer_create(
subnet_id=subnet_id,
description=description,
admin_state=admin_state,
project_id=project_id,
listeners=listeners,
flavor_id=flavor_id,
provider=provider,
vip_qos_policy_id=vip_qos_policy_id)
loadbalancers.append(lb)
for loadbalancer in loadbalancers:
self.octavia.wait_for_loadbalancer_prov_status(loadbalancer)
self.octavia.load_balancer_show(
loadbalancer["id"])
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,911
|
openstack/rally-openstack
|
refs/heads/master
|
/tests/unit/task/scenarios/monasca/test_utils.py
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import ddt
from rally_openstack.task.scenarios.monasca import utils
from tests.unit import test
@ddt.ddt
class MonascaScenarioTestCase(test.ScenarioTestCase):
def setUp(self):
super(MonascaScenarioTestCase, self).setUp()
self.scenario = utils.MonascaScenario(self.context)
self.kwargs = {
"dimensions": {
"region": "fake_region",
"hostname": "fake_host_name",
"service": "fake_service",
"url": "fake_url"
}
}
def test_list_metrics(self):
return_metric_value = self.scenario._list_metrics()
self.assertEqual(return_metric_value,
self.clients("monasca").metrics.list.return_value)
self._test_atomic_action_timer(self.scenario.atomic_actions(),
"monasca.list_metrics")
@ddt.data(
{"name": ""},
{"name": "fake_metric"},
)
@ddt.unpack
def test_create_metrics(self, name=None):
self.name = name
self.scenario._create_metrics(name=self.name, kwargs=self.kwargs)
self.assertEqual(1, self.clients("monasca").metrics.create.call_count)
|
{"/tests/unit/doc/test_docker_readme.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_zuul_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/rally_jobs/test_jobs.py": ["/rally_openstack/__init__.py"], "/tests/unit/test__compat.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_task_samples.py": ["/rally_openstack/__init__.py"], "/tests/unit/task/test_scenario.py": ["/rally_openstack/common/credential.py"], "/tests/ci/playbooks/roles/list-os-resources/library/osresources.py": ["/rally_openstack/__init__.py"], "/tests/functional/test_certification_task.py": ["/rally_openstack/__init__.py"]}
|
24,917
|
cespena/Process_Resource_Manager
|
refs/heads/main
|
/project1manager.py
|
'''
design and implement extended version of manager
PCB[16]
3-level RL
RCB[4]
RCB[0] and RCB[1] have 1 unit
RCB[2] has 2 units
RCB[3] has 3 units
create()
destroy()
request()
release()
timeout()
scheduler()
init()
init should
erase all previous contents of the data structures PCB, RCB, RL
Create a single running process at PCB[0] with priority 0
Enter the process into the RL at the lowest-priority level 0
'''
class CreateMoreThan16ProcessesError(Exception):
pass
class DestroyProcessThatsNotAChildOfCurrentProcessError(Exception):
pass
class RequestANonExistentResourceError(Exception):
pass
class RequestAResourceProcessAlreadyHolding(Exception):
pass
class ReleaseAResourceProcessIsNotHolding(Exception):
pass
class Process0RequestingAResourceError(Exception):
pass
class DestroyProcess0Error(Exception):
pass
class SizeOfUnitsIsZeroError(Exception):
pass
class IncorrectResourceSizePairError(Exception):
pass
class RequestedSizeTooBigError(Exception):
pass
class FixedListClass:
def __init__(self, s, value):
self.fixed_size = s
self.fixed_list = [None] * self.fixed_size
self.count = 0
if value == 1:
self.set_resources()
if value == 2:
self.set_rl()
def __getitem__(self, i):
return self.fixed_list[i]
def __setitem__(self, i, value):
self.fixed_list[i] = value
def add_process(self, item):
for i in range(len(self.fixed_list)):
if self.fixed_list[i] == None:
self.fixed_list[i] = item
self.count += 1
return i
return None
def set_resources(self):
for i in range(self.fixed_size):
if i == 0 or i == 1:
self.fixed_list[i] = ResourceClass(1)
elif i == 2:
self.fixed_list[i] = ResourceClass(2)
else:
self.fixed_list[i] = ResourceClass(3)
self.count = 4
def set_rl(self):
for i in range(self.fixed_size):
self.fixed_list[i] = []
self.count = 3
class ProcessClass:
def __init__(self, parent, prior):
self.priority = prior
self.current_state = 1
self.parent = parent
self.children = []
self.resources = []
self.resource_counter = [[],[], [], []]
def set_state(self, new_state):
self.current_state = new_state
def add_child(self, child):
self.children.append(child)
def remove_child(self, child):
self.children.remove(child)
def add_resource(self, resource):
self.resources.append(resource)
def remove_resource(self, resource):
self.resources.remove(resource)
class ResourceClass:
def __init__(self, state):
self.current_state = state
self.waitlist = []
self.inventory = state
def set_state(self, new_state):
self.current_state = new_state
def add_to_waitlist(self, pcb_index):
self.waitlist.append(pcb_index)
def remove_from_waitlist(self, pcb_index):
self.waitlist.remove(pcb_index)
class ManagerClass:
def __init__(self, db):
self.debugging = db
self.pcb = FixedListClass(16, 0)
self.rcb = FixedListClass(4, 1)
self.rl = FixedListClass(3, 2)
self.release_processes = []
#create a single running process at PCB[0] with priority 0
self.pcb.add_process(ProcessClass(None, 0))
self.rl[0].append(0)
if self.debugging == 1:
print("* initialized")
else:
self.scheduler()
def create(self, prior):
'''
allocate new PCB[j]
state = ready
insert j into children of i
parent = i
children = null
resources = null
insert j into RL
display: "process j created"
'''
if self.pcb.count > 15:
raise CreateMoreThan16ProcessesError
current_process = self.get_current_process()
new_process = self.pcb.add_process(ProcessClass(current_process, prior))
self.pcb[current_process].add_child(new_process)
self.rl[prior].append(new_process)
if self.debugging == 1:
print("* process ", new_process, " created")#######
self.scheduler()
else:
self.scheduler()########
def destroy(self, index):
'''
for all k in children of j, destroy(k)
remove j from the parent's list
remove j from RL or waiting list
release all resources of j
free PCB of j
'''
if index == 0:
raise DestroyProcess0Error
current = self.get_current_process()
if index not in self.pcb[current].children and index != current:
raise DestroyProcessThatsNotAChildOfCurrentProcessError
final_count = self.destroy_processes(index)
if self.debugging == 1:
print("* ", final_count, " processes destroyed")
self.scheduler()
else:
self.scheduler()
def request(self, resource, size):
if resource > 3 or resource < 0:
raise RequestANonExistentResourceError
current_process = self.get_current_process()
if current_process == 0:
raise Process0RequestingAResourceError
# if resource in self.pcb[current_process].resources:
# raise RequestAResourceProcessAlreadyHolding
# if (resource, size) in self.pcb[current_process].resources:
# raise RequestAResourceProcessAlreadyHolding
if len(self.pcb[current_process].resource_counter[resource]) != 0:
if resource == 0 or resource == 1:
if (resource, size) in self.pcb[current_process].resources:
raise RequestAResourceProcessAlreadyHolding
if resource == 2 and \
sum(self.pcb[current_process].resource_counter[resource]) == 2:
raise RequestAResourceProcessAlreadyHolding
if resource == 3 and \
sum(self.pcb[current_process].resource_counter[resource]) == 3:
raise RequestAResourceProcessAlreadyHolding
if size == 0:
raise SizeOfUnitsIsZeroError
if size > self.rcb[resource].inventory:
raise RequestedSizeTooBigError
if (self.rcb[resource].current_state >= size and \
self.rcb[resource].waitlist == []):
self.rcb[resource].current_state -= size
self.pcb[current_process].add_resource((resource, size))
self.pcb[current_process].resource_counter[resource].append(size)
if self.debugging == 1:
print("* resource ", resource, " allocated")
self.scheduler()
else:
prior = self.pcb[current_process].priority
self.pcb[current_process].set_state(0)
self.rl[prior].remove(current_process)
self.rcb[resource].add_to_waitlist((current_process, size))
if self.debugging == 1:
print("* process ", current_process, " blocked")
self.scheduler()
else:
self.scheduler()
def release(self, resource, size):
if resource > 3 or resource < 0:
raise RequestANonExistentResourceError
current_process = self.get_current_process()
if (resource, size) not in self.pcb[current_process].resources:
if size < sum(self.pcb[current_process].resource_counter[resource]) and \
len(self.pcb[current_process].resource_counter[resource]) == 1:
count = size
while count != 0:
m = self.pcb[current_process].resource_counter[resource][0]
self.pcb[current_process].remove_resource((resource, m))
self.pcb[current_process].resource_counter[resource].remove(m)
self.rcb[resource].current_state += size
m -= size
self.pcb[current_process].add_resource((resource, m))
self.pcb[current_process].resource_counter[resource].append(m)
count -= size
elif size <= sum(self.pcb[current_process].resource_counter[resource]) and \
sum(self.pcb[current_process].resource_counter[resource]) != 0:
count = size
while count != 0:
m = max(self.pcb[current_process].resource_counter[resource])
self.pcb[current_process].remove_resource((resource, m))
self.pcb[current_process].resource_counter[resource].remove(m)
count -= m
self.rcb[resource].current_state += m
else:
raise IncorrectResourceSizePairError
else:
self.pcb[current_process].remove_resource((resource, size))
self.pcb[current_process].resource_counter[resource].remove(size)
self.rcb[resource].current_state += size
if self.debugging == 1:
print("* resource ", resource, " released")
while (self.rcb[resource].waitlist != [] and self.rcb[resource].current_state > 0):
next_process = self.rcb[resource].waitlist[0]
if self.rcb[resource].current_state >= next_process[1]:
self.rcb[resource].current_state -= next_process[1]
self.pcb[next_process[0]].add_resource((resource, next_process[1]))
self.pcb[next_process[0]].resource_counter[resource].append(next_process[1])
self.pcb[next_process[0]].set_state(1)
self.rcb[resource].remove_from_waitlist(next_process)
prior = self.pcb[next_process[0]].priority
self.rl[prior].append(next_process[0])
if self.debugging == 1:
print("* process ", next_process[0], " got ", resource)
else:
break
self.scheduler()
def timeout(self):
'''
move process i from the head of RL to end of RL
scheduler()
'''
current_process = self.get_current_process()
prior = self.pcb[current_process].priority
self.rl[prior].append(self.rl[prior].pop(0))
self.scheduler()
def scheduler(self):
'''
find process i currently at the head of RL
display: "process i running"
'''
current = self.get_current_process()
if self.debugging == 1:
print("* process ", current, " running")
else:
print(current, "", end='')
########################################################################
def destroy_processes(self, index):
count = 0
process = self.pcb[index]
priority = process.priority
for i in range(len(process.children)):
count += self.destroy_processes(process.children[0])
if index != 0:
parent = self.pcb[process.parent]
parent.remove_child(index)
'''check for waitlist also'''#########################
if process.current_state == 1:
self.rl[priority].remove(index)
else:
for i in range(self.rcb.fixed_size):
for j in range(len(self.rcb[i].waitlist)):
waiting = self.rcb[i].waitlist[j]
if waiting[0] == index:
self.rcb[i].waitlist.remove(waiting)
break
'''release all resources of j'''######################
for i in range(len(process.resources)):
self.destroy_release(process.resources[0], index)
self.pcb[index] = None
self.pcb.count -= 1
return count + 1
else:
return count
def get_current_process(self):
for i in range(self.rl.fixed_size - 1, -1, -1):
for j in self.rl[i]:
return j
print("get_current_process failed")
return -1
def destroy_release(self, pair, index):
resource = pair[0]
size = pair[1]
current_process = index
self.pcb[current_process].remove_resource((resource, size))
self.pcb[current_process].resource_counter[resource].remove(size)
self.rcb[resource].current_state += resource
if self.debugging == 1:
print("* d_resource ", resource, " released")
while (self.rcb[resource].waitlist != [] and self.rcb[resource].current_state > 0):
next_process = self.rcb[resource].waitlist[0]
if self.rcb[resource].current_state >= next_process[1]:
self.rcb[resource].current_state -= next_process[1]
self.pcb[next_process[0]].add_resource((resource, next_process[1]))
self.pcb[next_process[0]].resource_counter[resource].append(next_process[1])
self.pcb[next_process[0]].set_state(1)
self.rcb[resource].remove_from_waitlist(next_process)
prior = self.pcb[next_process[0]].priority
self.rl[prior].append(next_process[0])
if self.debugging == 1:
print("* d_process ", next_process[0], " got ", resource)
else:
break
|
{"/project1shell.py": ["/project1manager.py"]}
|
24,918
|
cespena/Process_Resource_Manager
|
refs/heads/main
|
/project1shell.py
|
##from project1manager import ManagerClass
import project1manager as p1m
class WrongInputLengthError(Exception):
pass
class WrongLength1Error(Exception):
pass
class WrongLength2Error(Exception):
pass
class WrongLength3Error(Exception):
pass
class SecondElementNotIntError(Exception):
pass
class ThirdElementNotIntError(Exception):
pass
class IncorrectDestroyIndexError(Exception):
pass
class IncorrectCreateIndexError(Exception):
pass
class ManagerIsNoneError(Exception):
pass
class NegativeValueError(Exception):
pass
class ShellClass:
def __init__(self):
self.Manager = None
self.running = 1
self.user_input = None
self.split_text = None
self.debugging = 0############ REMEMBER TO CHANGE ##########
def run_shell(self):
while self.running:
try:
if self.debugging == 1:
self.user_input = input()
else:
self.user_input = input()
if self.user_input == 'cesar':
self.running = 0
else:
self.split_text = self.user_input.split()
self.check_input()
except WrongInputLengthError:
self.print_error_message("Wrong Input Length")
except WrongLength1Error:
self.print_error_message("Wrong Length 1 Error")
except WrongLength2Error:
self.print_error_message("Wrong Length 2 Error")
except WrongLength3Error:
self.print_error_message("Wrong Length 3 Error")
except SecondElementNotIntError:
self.print_error_message("Second Element Not Int")
except ThirdElementNotIntError:
self.print_error_message("Third Element Not Int")
except IncorrectDestroyIndexError:
self.print_error_message("Incorrect Destroy Index Error")
except IncorrectCreateIndexError:
self.print_error_message("Incorrect Create Index Error")
except ManagerIsNoneError:
self.print_error_message("Manager Is None Error")
except NegativeValueError:
self.print_error_message("NegativeValueError")
except p1m.CreateMoreThan16ProcessesError:
self.print_error_message("CreateMoreThan16ProcessesError")
except p1m.DestroyProcessThatsNotAChildOfCurrentProcessError:
self.print_error_message("DestroyProcessThatsNotAChildOfCurrentProcessError")
except p1m.RequestANonExistentResourceError:
self.print_error_message("RequestANonExistentResourceError")
except p1m.RequestAResourceProcessAlreadyHolding:
self.print_error_message("RequestAResourceProcessAlreadyHolding")
except p1m.ReleaseAResourceProcessIsNotHolding:
self.print_error_message("ReleaseAResourceProcessIsNotHolding")
except p1m.Process0RequestingAResourceError:
self.print_error_message("Process0RequestingAResourceError")
except p1m.DestroyProcess0Error:
self.print_error_message("DestroyProcess0Error")
except p1m.SizeOfUnitsIsZeroError:
self.print_error_message("SizeOfUnitsIsZeroError")
except p1m.IncorrectResourceSizePairError:
self.print_error_message("IncorrectResourceSizePairError")
except p1m.RequestedSizeTooBigError:
self.print_error_message("RequestedSizeTooBigError")
except EOFError:
if self.debugging == 1:
print("* EndOfFile")
# else:
# print()
self.running = 0
def check_input(self):
## print(self.split_text)
if self.Manager != None:
if len(self.split_text) > 3:
raise WrongInputLengthError
elif len(self.split_text) == 3:
self.check_length_3_functions()
elif len(self.split_text) == 2:
self.check_length_2_functions()
elif len(self.split_text) == 1:
self.check_length_1_functions()
else:
pass
elif self.Manager == None:
if len(self.split_text) == 1:
if self.split_text[0] == "in":
self.check_length_1_functions()
else:
raise ManagerIsNoneError
else:
raise ManagerIsNoneError
def check_length_3_functions(self):
'''
rq<r><n> request(r, n)
rl<r><n> release(r, n)
'''
try:
self.split_text[1] = int(self.split_text[1])
except ValueError:
raise SecondElementNotIntError
if self.split_text[1] < 0:
raise NegativeValueError
try:
self.split_text[2] = int(self.split_text[2])
except ValueError:
raise ThirdElementNotIntError
if self.split_text[2] < 0:
raise NegativeValueError
## print(self.split_text)
if self.split_text[0] == "rq":
self.Manager.request(self.split_text[1], self.split_text[2])
elif self.split_text[0] == "rl":
self.Manager.release(self.split_text[1], self.split_text[2])
else:
raise WrongLength3Error
def check_length_2_functions(self):
'''
de<i> destroy(i)
cr<i> create(i)
'''
try:
self.split_text[1] = int(self.split_text[1])
except ValueError:
raise SecondElementNotIntError
if self.split_text[0] == "de":
if self.split_text[1] < 0 or self.split_text[1] > 15:
raise IncorrectDestroyIndexError
else:
self.Manager.destroy(self.split_text[1])
elif self.split_text[0] == "cr":
if self.split_text[1] == 1 or self.split_text[1] == 2:
self.Manager.create(self.split_text[1])
else:
raise IncorrectCreateIndexError
else:
raise WrongLength2Error
def check_length_1_functions(self):
'''
to timeout()
in init()
'''
if self.split_text[0] == "to":
self.Manager.timeout()
elif self.split_text[0] == "in":
if self.Manager == None:
self.Manager = p1m.ManagerClass(self.debugging)
else:
print()
self.Manager = p1m.ManagerClass(self.debugging)
else:
raise WrongLength1Error
def print_error_message(self, message):
if(self.debugging == 1):
print(message)
else:
print("-1 ", end='')
if __name__ == "__main__":
shell = ShellClass()
shell.run_shell()
|
{"/project1shell.py": ["/project1manager.py"]}
|
24,934
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Player.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Player.py
import Static
from Weapon_Module import Wand_Weapon
from Item_Module import Spell
from Item_Module import Potion
from Armor import Armor
from Effect import *
import random
#Note - Superclass of Creature and Adventurer
class Player:
def __init__(self, name, hp, armor, weapon):
#code here
self.name = name
self.hp = hp
if armor == None:
self.armor = list()
else:
self.armor = armor
if weapon == None:
self.weapon = list()
else:
self.weapon = weapon
self.max_hp = hp
self.spells = list()
self.potion = list()
self.effect = list()
self.OS = 0
self.DS = 0
self.primary = None
self.strength = 0
self.agility = 0
self.dexterity = 0
self.intel = 0
self.stamina = 0
self.level = 1
self.gold = 0
def to_string(self):
return ''
def __str__(self):
return self.name + " (HP: " + str(self.hp) + ")"
def add_spell(self, spell):
#adds a new spell to the spell inventory
self.spells.append(spell)
def add_weapon(self, weapon):
#adds a new weapon to the weapon inventory
self.weapon.append(weapon)
def heal(self, amt):
if self.hp + amt > self.max_hp:
self.hp = self.max_hp
else:
self.hp += amt
def add_potion(self, potion):
#adds a new potion to the potion inventory
self.potion.append(potion)
def primary_weapon(self):
if self.weapon == None or len(self.weapon) == 0:
return Weapon(1, 1, 0, 1, 'None', 'Nothing')
else:
return self.weapon[0]
def primary_armor(self):
if self.armor == None or len(self.armor) == 0:
return Armor(10, 0, 'None', 'Nothing')
else:
return self.armor[0]
def add_armor(self, armor):
#adds a new armor to the armor inventory
self.armor.append(armor)
def add_effect(self, effect):
#adds a new effect to the player
self.effect.append(effect)
def remove_effect(self, effect):
#removes an effect from the player
self.effect.remove(effect)
def is_stunned(self):
#returns True if Player is stunned, False if not
#check all effects for stun type, else return False
for e in self.effect:
if isinstance(e, Stun_Effect):
return True
return False
def offense_bonus(self):
#returns the amount of offensive bonus to physical attacks
#from effects
bonus = 0
for e in self.effect:
if isinstance(e, Offense_Effect):
bonus += e.bonus
return bonus
def offense_bonus_magic(self):
#returns the amount of offensive bonus to magic attacks
#from effects
bonus = 0
for e in self.effect:
if isinstance(e, Magic_Offense_Effect):
bonus += e.bonus
return bonus
def defense_bonus(self):
#returns the amount of defensive bonus to physical attacks
#from effects
bonus = 0
for e in self.effect:
if isinstance(e, Defense_Effect):
bonus += e.bonus
return bonus
def defense_bonus_magic(self):
#returns the amount of defensive bonus to magic attacks
#from effects
bonus = 0
for e in self.effect:
if isinstance(e, Magic_Defense_Effect):
bonus += e.bonus
return bonus
def calc_DS_Physical(self):
#simulate encumbrance
d = self.agility - self.encum()
#Primary armor's defense value
x = self.primary_armor().defense
#Add bonus from effects
x += self.defense_bonus()
if d > 0:
x += d
if self.is_stunned():
x -= 3
if x < 0:
x = 0
return x
def calc_DS_Magic(self):
x = self.intel + self.defense_bonus_magic()
if self.is_stunned():
x -= 3
if x < 0:
x = 0
return x
def calc_OS_Physical(self):
x = self.primary_weapon().chance
x += self.offense_bonus()
if isinstance(self.primary_weapon(), Wand_Weapon):
off = self.intel - self.encum()
else:
off = self.dexterity - self.encum()
if off > 0:
x += off
return x
def calc_OS_Magic(self):
return self.intel + self.offense_bonus_magic()
def encum(self):
return self.primary_armor().required_strength
def calc_num_attacks(self):
a = self.current_attack()
if isinstance(a, Spell) or isinstance(a, Potion):
return 1
num = self.dexterity
num += self.agility
num -= self.encum()
num += self.primary_weapon().speed
num = num // 7
if num < 1:
num = 1
return num
def current_attack(self):
if self.primary == None:
self.primary = self.primary_weapon()
return self.primary
def all_equipment(self):
temp = list()
for w in self.weapon:
temp.append(w)
for a in self.armor:
temp.append(a)
for p in self.potion:
temp.append(p)
for s in self.spells:
temp.append(s)
return temp
class Creature(Player):
def __init__(self, name, hp, armor=list(), weapon=list(), element=None):
Player.__init__(self, name, hp, armor, weapon)
self.element = element
def select_attack(self):
#returns the attack selected by the creature
#todo: add some kind of biased selection system that we can generate "attack scripts" from
self.primary = self.primary_weapon()
return self.primary
def calc_experience(self):
xp = self.strength * 2
xp += self.stamina * 2
xp += self.dexterity * 2
xp += self.agility * 2
xp += self.intel * 2
xp += self.max_hp // 5
xp += self.primary_weapon().score // 5
xp += self.primary_armor().damage_reduction * 2
return xp * 3
class Adventurer(Player):
def __init__(self, name, hp):
Player.__init__(self, name, hp,None,None)
self.experience = 0
self.next_level = 1000
self.ap = 0
def calc_next_level(self):
return 1000 + (1500 * (self.level-1))
def grant_xp(self, xp):
self.experience += xp
while self.experience > self.next_level:
self.gain_level()
def gain_level(self):
self.level += 1
self.next_level = self.calc_next_level()
hp_gain = random.randint(self.stamina*4, self.stamina*10)
self.max_hp += hp_gain
self.hp = self.max_hp
self.ap = self.level * 2 + self.intel
print "Congratulations! You are now Level %s!" % self.level
print "You gained %s max hp and" % hp_gain, "%s attribute points."
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,935
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Item_Interface.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Item_Interface.py
#The item interface is not really in the item heirarchy. It is just an
#interface that relates to "items" in the game. Such as armor, potions,
#spells, weapons, etc.
class Item_Interface:
def attack_pre(self, attacker, defender):
return
def attack_post(self, attacker, defender):
return
def defense_pre(self, attacker, defender):
return
def defense_post(self, attacker, defender):
return
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,936
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Room_Module.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Room.py
import random
from Static import *
from Player import *
from Creature_Factory import *
from Weapon_Factory import *
from Armor_Factory import *
from Item_Factory import *
class Room:
def __init__(self, description, creature=None, item=list(), gold=0):
#code here
self.description = description
self.creature = creature
self.item = item
self.gold = gold
class Room_Factory:
def __init__(self):
self
#static definition to generate random descriptions
def get_room_description(self):
descrip = [
'room 1',
'room 2',
'room 3',
'room 4',
'room 5',
'room 6',
'room 7',
'room 8',
'room 9',
'room 10',
'room 11',
'room 12',
]
return descrip[random.randrange(0, len(descrip))]
def generate(self):
#description item and gold
description = self.get_room_description()
gold = random.randrange(101)
#generate creature
chance = random.randrange(1000)
if( chance > 300 ):
cf = Creature_Factory()
creature = cf.generate()
else:
creature = None
#generate items
items = list()
itf = Item_Factory()
items.append( itf.generate() )
wf = Weapon_Factory()
items.append( wf.generate() )
af = Armor_Factory()
items.append( af.generate() )
return Room( description, creature, items, gold )
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,937
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Test.py
|
from Player import Adventurer
from Creature_Factory import *
from Proc import *
from Item_Module import Healing_Potion
from Arena import Arena
from Distributed_Random import Distributed_Random
import random
class Test:
def __init__(self):
self.wf = Weapon_Factory()
self.cf = Creature_Factory()
self.af = Armor_Factory()
#self.player.add_weapon(self.wf.generate_by_quality(2))
#self.player = self.cf.generate_player_stats(self.player)
#self.player.primary_weapon().proc.append(Leech_Proc(50,20))
#self.player.add_armor(self.af.generate_high_quality())
self.reset(1)
def fight(self, diff):
self.reset(diff)
while self.player.hp > 0 and self.gen.hp > 0:
self.arena.attack()
print "Gen: HP = %s" % self.gen.hp, "/%s" % self.gen.max_hp,
print "OS = %s" % self.gen.OS, "DS = %s" % self.gen.DS,
print "WPN Score = %s" % self.gen.primary_weapon().score
print "PLR: HP = %s" % self.player.hp, "/%s" % self.player.max_hp,
print "OS = %s" % self.player.OS, "DS = %s" % self.player.DS,
print "WPN Score = %s" % self.player.primary_weapon().score
if self.player.hp > 0:
print "Player WIN"
else:
print "Player LOSS"
def temp(self):
wpn = self.wf.generate_by_type(random.randint(0,3),random.randint(0,2))
agi_high = 0
agi_low = 10
str_high = 0
str_low = 10
cnt = 0
while cnt < 1000:
if wpn.required_agility > agi_high:
agi_high = wpn.required_agility
if wpn.required_agility < agi_low:
agi_low = wpn.required_agility
if wpn.required_strength > str_high:
str_high = wpn.required_strength
if wpn.required_strength < str_low:
str_low = wpn.required_strength
wpn = self.wf.generate_by_type(random.randint(0,3), random.randint(0,2))
cnt += 1
print agi_low, agi_high, str_low, str_high
def reset(self, diff):
self.player = Adventurer("Valna",300)
self.player.add_weapon(self.wf.generate_by_quality(2))
self.player.add_armor(self.af.generate_by_quality(2))
self.gen = self.cf.generate_difficulty(diff)
#self.player.primary_weapon().proc.append(Poison_Proc(50,1,10))
#self.gen.add_effect(DOT_Effect(3,200))
self.arena = Arena(self.player, self.gen)
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,938
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Item_Factory.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Item_Factory.py
from Item_Module import *
import random
import Config
class Item_Factory:
def __init__(self):
self.spell = Config.item['spell']
self.potion = Config.item['potion']
##---------------------------------------------------------
## Generic Generate (generates abundant to medium-rare
## items)
##---------------------------------------------------------
def generate(self, rarity = -1):
if( rarity == -1 ):
rarity = random.randrange(1, 4) #random range from 1 to 3 inclusive
elif( rarity > 3 ):
rarity = 3
elif( rarity < 1 ):
rarity = 1
item_type = random.randrange(100)
#generate a spell
if( item_type < 50 ):
return self.generate_spell(rarity)
#generate a potion
else:
return self.generate_potion(rarity)
#rarity = {1: weak, 2: medium, 3: rare}
def generate_potion(self, rarity = 1):
spell_type = random.randrange(100)
if( spell_type < 20 ):
#create healing potion
return self.generate_potion_healing(rarity)
elif( spell_type < 40 ):
#create defense potion
return self.generate_potion_defense(rarity)
elif( spell_type < 60 ):
#create offense potion
return self.generate_potion_offense(rarity)
elif( spell_type < 80 ):
#create magic deffense potion
return self.generate_potion_magic_defense(rarity)
else:
#create magic offense potion
return self.generate_potion_magic_offense(rarity)
def generate_potion_magic_offense(self, rarity):
nd = self.get_random_potion_magic_offense_description(rarity)
return (
Magic_Offense_Potion(nd[0], nd[1], random.randrange(self.potion['magic_offense']['common'][0],self.potion['magic_offense']['common'][1]),
random.randrange(self.potion['magic_offense']['common'][2],self.potion['magic_offense']['common'][3]) ),
Magic_Offense_Potion(nd[0], nd[1], random.randrange(self.potion['magic_offense']['normal'][0],self.potion['magic_offense']['normal'][1]),
random.randrange(self.potion['magic_offense']['normal'][2],self.potion['magic_offense']['normal'][3]) ),
Magic_Offense_Potion(nd[0], nd[1], random.randrange(self.potion['magic_offense']['rare'][0],self.potion['magic_offense']['rare'][1]),
random.randrange(self.potion['magic_offense']['rare'][2],self.potion['magic_offense']['rare'][3]) ),
)[rarity - 1]
def generate_potion_magic_defense(self, rarity):
nd = self.get_random_potion_magic_defense_description(rarity)
return (
Magic_Offense_Potion(nd[0], nd[1], random.randrange(self.potion['magic_defense']['common'][0], self.potion['magic_defense']['common'][1]),
random.randrange(self.potion['magic_defense']['common'][2], self.potion['magic_defense']['common'][3]) ),
Magic_Offense_Potion(nd[0], nd[1], random.randrange(self.potion['magic_defense']['normal'][0],self.potion['magic_defense']['normal'][1]),
random.randrange(self.potion['magic_defense']['normal'][2],self.potion['magic_defense']['normal'][3]) ),
Magic_Offense_Potion(nd[0], nd[1], random.randrange(self.potion['magic_defense']['rare'][0],self.potion['magic_defense']['rare'][1]),
random.randrange(self.potion['magic_defense']['rare'][2],self.potion['magic_defense']['rare'][3]) ),
)[rarity - 1]
def generate_potion_offense(self, rarity):
nd = self.get_random_potion_offense_description(rarity)
return (
Offense_Potion(nd[0], nd[1], random.randrange(self.potion['magic_offense']['common'][0], self.potion['magic_offense']['common'][1]),
random.randrange(self.potion['magic_offense']['common'][2], self.potion['magic_offense']['common'][3]) ),
Offense_Potion(nd[0], nd[1], random.randrange(self.potion['magic_offense']['rare'][0], self.potion['magic_offense']['rare'][1]),
random.randrange(self.potion['magic_offense']['rare'][2], self.potion['magic_offense']['rare'][3]) ),
Offense_Potion(nd[0], nd[1], random.randrange(self.potion['magic_offense']['rare'][0], self.potion['magic_offense']['rare'][1]),
random.randrange(self.potion['magic_offense']['rare'][2], self.potion['magic_offense']['rare'][3]) ),
)[rarity - 1]
def generate_potion_healing(self, rarity):
if( rarity == 1 ):
#weak potion
nd = self.get_random_potion_healing_description_light()
return Healing_Potion(nd[0], nd[1], self.potion['healing']['common'][0], self.potion['healing']['common'][1])
elif( rarity == 2):
#medium potion
nd = self.get_random_potion_healing_description_medium()
return Healing_Potion(nd[0], nd[1], self.potion['healing']['normal'][0], self.potion['healing']['normal'][1])
else:
#rare potion
nd = self.get_random_potion_healing_description_heavy()
return Healing_Potion(nd[0], nd[1], self.potion['healing']['rare'][0], self.potion['healing']['rare'][1])
def generate_potion_defense(self, rarity):
nd = self.get_random_potion_defense_description(rarity)
if( rarity == 1 ):
#weak potion
return Defense_Potion(nd[0], nd[1], random.randrange(self.potion['defense']['common'][0], self.potion['defense']['common'][1]),
random.randrange(self.potion['defense']['common'][2], self.potion['defense']['common'][3]))
if( rarity == 2 ):
#medium potion
return Defense_Potion(nd[0], nd[1], random.randrange(self.potion['defense']['normal'][0], self.potion['defense']['normal'][1]),
random.randrange(self.potion['defense']['normal'][2],self.potion['defense']['normal'][3]))
else:
#rare potion
return Defense_Potion(nd[0], nd[1], random.randrange(self.potion['defense']['rare'][0],self.potion['defense']['rare'][1]),
random.randrange(self.potion['defense']['rare'][2],self.potion['defense']['rare'][3]))
#rarity = {1: weak, 2: medium, 3: rare}
def generate_spell(self, rarity = 1):
#get a random sell type
spell_type = random.randrange(100)
if( spell_type < 33 ):
#create a attack spell
return self.generate_spell_attack(rarity)
elif( spell_type < 66 ):
#create a defense spell
return self.generate_spell_defense(rarity)
else:
#create a stun spell
return self.generate_spell_stun(rarity)
def generate_spell_stun(self, rarity):
nd = self.get_random_spell_stun_description(rarity)
return (
Stun_Spell(nd[0], nd[1], random.randrange(self.spell['stun']['common'][0], self.spell['stun']['common'][1]),
random.randrange(self.spell['stun']['common'][2], self.spell['stun']['common'][3])),
Stun_Spell(nd[0], nd[1], random.randrange(self.spell['stun']['normal'][0],self.spell['stun']['normal'][1]),
random.randrange(self.spell['stun']['normal'][2],self.spell['stun']['normal'][3])),
Stun_Spell(nd[0], nd[1], random.randrange(self.spell['stun']['rare'][0],self.spell['stun']['rare'][1]),
random.randrange(self.spell['stun']['rare'][2],self.spell['stun']['rare'][3])),
)[rarity - 1]
def generate_spell_defense(self, rarity):
nd = self.get_random_spell_defense_description(rarity)
return (
Defense_Spell(nd[0], nd[1], random.randrange(self.spell['defense']['common'][0], self.spell['defense']['common'][1]),
random.randrange(self.spell['defense']['common'][2], self.spell['defense']['common'][3]),
random.randrange(self.spell['defense']['common'][4], self.spell['defense']['common'][5])),
Defense_Spell(nd[0], nd[1], random.randrange(self.spell['defense']['normal'][0],self.spell['defense']['normal'][1]),
random.randrange(self.spell['defense']['normal'][2],self.spell['defense']['normal'][3]),
random.randrange(self.spell['defense']['normal'][4],self.spell['defense']['normal'][5])),
Defense_Spell(nd[0], nd[1], random.randrange(self.spell['defense']['rare'][0],self.spell['defense']['rare'][1]),
random.randrange(self.spell['defense']['rare'][2],self.spell['defense']['rare'][3]),
random.randrange(self.spell['defense']['rare'][4],self.spell['defense']['rare'][5])),
)[rarity - 1]
def generate_spell_attack(self, rarity):
nd = self.get_random_spell_attack_description(rarity)
return (
Attack_Spell(nd[0], nd[1], random.randrange(self.spell['attack']['common'][0], self.spell['attack']['common'][1]),
random.randrange(self.spell['attack']['common'][2], self.spell['attack']['common'][3]),
random.randrange(self.spell['attack']['common'][4],self.spell['attack']['common'][5])),
Attack_Spell(nd[0], nd[1], random.randrange(self.spell['attack']['normal'][0],self.spell['attack']['normal'][1]),
random.randrange(self.spell['attack']['normal'][2],self.spell['attack']['normal'][3]),
random.randrange(self.spell['attack']['normal'][4],self.spell['attack']['normal'][5])),
Attack_Spell(nd[0], nd[1], random.randrange(self.spell['attack']['rare'][0],self.spell['attack']['rare'][1]),
random.randrange(self.spell['attack']['rare'][2],self.spell['attack']['rare'][3]),
random.randrange(self.spell['attack']['rare'][4],self.spell['attack']['rare'][5])),
)[rarity - 1]
##---------------------------------------------------------
## Particular Generate (generates item of specified rarity)
##---------------------------------------------------------
def generate_rare(self):
return self.generate(3)
def generate_normal(self):
return self.generate(2)
def generate_common(self):
return self.generate(1)
##---------------------------------------------------------
## Description Generators
##---------------------------------------------------------
#spells
def get_random_spell_stun_description(self, rarity):
ss = (
('Tazer', 'Stuns an player for one or more turns.'),
('Stun-Gun', 'Stuns a player for one or more turns.'),
('Super Tazer', 'Stuns a player for one or more turns.'),
)
return ss[rarity - 1]
def get_random_spell_attack_description(self, rarity):
sa = (
('Beginner Attack Spell', 'A beginner magical attack spell.'),
('Sage\' Wrath', 'An intermediate magical attack spell.'),
('Magical Beat Down', 'An advanced magical attack spell.'),
)
return sa[rarity - 1]
def get_random_spell_defense_description(self, rarity):
sd = (
('Magical Shield', 'Beginner magical defensive spell.'),
('Magical Armor', 'Intermediate magical defensive spell.'),
('Magical Fortress', 'Advanced magical defenseive spell.'),
)
return sd[rarity - 1]
#potions
def get_random_potion_healing_description_light(self):
ph = (
('Light Health Potion', 'Light healing potion. (20 - 30 HP\'s)'),
('Light Elixer', 'Light healing potion. (20 - 30 HP\'s)'),
)
return ph[random.randrange(len(ph))]
def get_random_potion_healing_description_medium(self):
ph = (
('Medium Health Potion', 'Medium healing potion. (80 - 100 HP\'s)'),
('Medium Elixer', 'Medium healing potion. (80 - 100 HP\'s)'),
)
return ph[random.randrange(len(ph))]
def get_random_potion_healing_description_heavy(self):
ph = (
('Heavy Health Potion', 'Heavy healing potion. (160 - 200 HP\'s)'),
('Heavy Elixer', 'Heavy healing potion. (160 - 200 HP\'s)'),
)
return ph[random.randrange(len(ph))]
def get_random_potion_defense_description(self, rarity = 1):
pd = (
('Light Defense Potion', 'A light defense potion. Increases defense 1/2 points for 1/2 turns.'),
('Medium Defense Potion', 'A medium defense potion. Increases defense 3/4 points for 1/4 turns.'),
('Heavy Defense Potion', 'A heavy defense potion. Increases defense 3/6 points for 3/6 turns.'),
)
return pd[rarity - 1]
def get_random_potion_offense_description(self, rarity):
po = (
('Light Offense Potion.', 'A light offensive potion. Increases offense 2/4 for 1/2 turns.'),
('Medium Offense Potion', 'A medium offensive potion. Increases offense 3/6 for 1/4 turns.'),
('Potion of Beast Mode', 'A heavy offensive potion. Increases offense 5/10 for 3/6 turns.'),
)
return po[rarity - 1]
def get_random_potion_magic_defense_description(self, rarity):
pmd = (
('Light Magic Defense Potion', 'A light magical defense potion. Increases magical defense 1/2 for 1/2 turns.'),
('Mediurm Magic Defense Potion', 'A medium magical defense potion. Increases magical defense 2/4 for 3/4 turns.'),
('Heavy Magic Defense Potion', 'A heavy magical defense potion. Increases magical defense 3/6 for 4/5 turns.'),
)
return pmd[rarity - 1]
def get_random_potion_magic_offense_description(self, rarity):
pmo = (
('Ligth Magic Offense Potion', 'A light magical offense potion. Increases magical offense 1/2 for 1/2 turns.'),
('Medium Magic Offense Potion', 'A medium magical offense potion. Increases magical offense 3/5 for 1/4 turns.'),
('Heavy Magic Offense Potion', 'A heavy magical offense potion. Increases magical offense 4/7 for 3/6 turns.'),
)
return pmo[rarity - 1]
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,939
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Arena.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File Arena.py
import random
import math
from Weapon_Module import *
from Armor import Armor
from Item_Module import *
#Note - this class does all the cool stuff
class Arena:
def __init__(self, player, creature):
#Creates an Arena instance
self.player = player
self.creature = creature
def round(self, attacker, victim):
#Represents one round of a turn, an atomic action either potion, spell, weapon attack
#Hooks in place for items
attacker.current_attack().attack_pre(attacker, victim)
victim.primary_armor().defense_pre(attacker, victim)
result = self.fight(attacker, victim)
damage = self.calc_damage(attacker, victim)
if damage < 0:
damage = 0
if result > 0:
victim.hp -= damage
if attacker == self.player:
if damage > 0:
attacker.current_attack().output_result_first(result, damage)
else:
attacker.current_attack().output_result_first(result)
else:
if damage > 0:
print attacker.name,
attacker.current_attack().output_result_third(result, damage)
else:
print attacker.name,
attacker.current_attack().output_result_third(result)
#Post hooks
attacker.current_attack().attack_post(attacker, victim)
victim.primary_armor().defense_post(attacker, victim)
def fight(self, attacker, victim):
#one attack, ambivalent to player/creature
#kickin' it old school with THAC0
return attacker.OS - victim.DS + random.randint(1, 20)
def calc_damage(self, attacker, victim):
#calculates damage for an attack
#does not currently account for elemental or effects
if isinstance(attacker.current_attack(), Weapon):
damage = random.randint(attacker.current_attack().min_damage, attacker.current_attack().max_damage)
damage -= victim.primary_armor().damage_reduction
damage -= victim.stamina // 2
if not isinstance(attacker.current_attack(), Arrow_Weapon):
damage += attacker.strength * 2
return damage
elif isinstance(attacker.current_attack(), Attack_Spell) or isinstance(attacker.current_attack(), Wand_Weapon):
damage = random.randint(attacker.current_attack().min_damage, attacker.current_attack().max_damage)
damage += attacker.intel
damage -= victim.intel // 2
#Possible location for elemental resistances
return damage
else:
return 0
def magic_attack(self, id):
self.player.primary = self.player.spells[id]
self.player.OS = self.player.calc_OS_Magic()
self.creature.DS = self.creature.calc_DS_Magic()
#Select creature attack
self.select_creature_attack()
self.turn()
def attack(self):
self.player.primary = self.player.primary_weapon()
self.player.OS = self.player.calc_OS_Physical()
self.creature.DS = self.creature.calc_DS_Physical()
self.select_creature_attack()
self.turn()
def potion(self, id):
self.player.primary = self.player.potion[id]
self.player.OS = 0
self.creature.DS = self.creature.calc_DS_Physical()
self.select_creature_attack()
self.turn()
def select_creature_attack(self):
self.creature.select_attack()
#Determine if creature selected a spell or something else
#Calculate OS/DS accordingly
if isinstance(self.creature.primary, Spell):
self.creature.OS = self.creature.calc_OS_Magic()
self.player.DS = self.player.calc_DS_Magic()
else:
self.creature.OS = self.creature.calc_OS_Physical()
self.player.DS = self.player.calc_DS_Physical()
def turn(self):
#self.creature.select_attack()
#check for player stun
#possible iniative roll here, for now alternate attacks
p_attacks = self.player.calc_num_attacks()
c_attacks = self.creature.calc_num_attacks()
while (p_attacks > 0 or c_attacks > 0) and (self.player.hp > 0 and self.creature.hp >0):
if self.player.is_stunned():
#creature gets a freebie
if c_attacks > 0 and self.creature.hp > 0:
self.round(self.creature, self.player)
self.update_effects()
else:
#player attacks first
if p_attacks > 0:
self.round(self.player, self.creature)
if self.creature.hp > 0 and not self.creature.is_stunned() and c_attacks > 0:
#it lives! Counter attack!
self.round(self.creature, self.player)
self.update_effects()
c_attacks -= 1
p_attacks -= 1
def update_effects(self):
#reduce the duration of all effects by one turn for creature and player
player_pending = list()
creature_pending = list()
for e in self.player.effect:
e.apply(self.player)
e.duration -= 1
if(e.duration == 0):
player_pending.append(e)
for e in self.creature.effect:
e.apply(self.creature)
e.duration -= 1
if(e.duration == 0):
creature_pending.append(e)
for p in player_pending:
self.player.effect.remove(p)
for p in creature_pending:
self.creature.effect.remove(p)
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,940
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Armor.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Armor.py
from Item_Module import Item
#All armor is represented by the Armor class
#Armors are broken into 3 rough categories (Light, Medium, Heavy)
#Light armor would be clothing or hide armors
#They generally provide high defensive bonuses but little damage reduction
#Medium armor would be chain mail or composite armors
#They typically offer a good mix between defense and damage reduction
#Heavy armor would be plate mail and other armors of solid metal construction
#They typically present easy targets but are very solid
class Armor(Item):
#Defense adds a bonus to DS vs Physical attacks
#Damage_Reduction reduces damage from incoming Physical attacks
def __init__(self, defense, damage_reduction, name, desc):
Item.__init__(self, name, desc)
#code here
self.defense = defense
self.damage_reduction = damage_reduction
self.required_strength = self.calc_required_strength()
self.proc = list()
def calc_required_strength(self):
return int(self.damage_reduction // 2.6)
def add_proc(self, proc):
self.proc.append(proc)
def __str__(self):
return self.name
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,941
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Weapon_Factory.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Weapon_Factory.py
import random
from Distributed_Random import Distributed_Random
from Weapon_Module import *
import Config
from Proc_Factory import Proc_Factory
#Generates Weapons
class Weapon_Factory:
def __init__(self):
self
#Returns a subclass of Weapon
def generate(self):
#create an instance of the weapon with it's stats
return self.generate_by_quality(random.randint(0,2))
#Generates an item of random type of the quality level requested
#0 = Low Quality, 1 = Medium Quality, 2 = High Quality
#Returns a subclass of Weapon
def generate_by_quality(self, quality):
gen = {
0: self.generate_sword(quality),
1: self.generate_arrow(quality),
2: self.generate_spear(quality),
3: self.generate_hammer(quality),
4: self.generate_wand(quality),
}
wpn = gen[self.select_weapon_type()]
if quality == 1 and random.randint(1,100) < 20:
pf = Proc_Factory()
proc = pf.generate_weapon_proc(random.randint(1,2))
wpn.name = proc.prefix + " " + wpn.name
wpn.add_proc(proc)
if quality == 2 and random.randint(1,100) < 40:
pf = Proc_Factory()
proc2 = None
proc = pf.generate_weapon_proc(random.randint(1,3))
if random.randint(1,100) < 20:
proc2 = pf.generate_weapon_proc(random.randint(1,3))
wpn.name = proc.prefix + " " + wpn.name
wpn.add_proc(proc)
if proc2 != None:
wpn.name = wpn.name + " " + proc2.suffix
wpn.add_proc(proc2)
return wpn
#Generates a weapon of the requested type and quality
#Type is 0 for Sword, 1 for Arrow, 2 for Spear, 3 for Hammer
#Quality is optional 0 = Low Quality, 1 = Medium Quality, 2 = High Quality
#Default is Medium Quality
def generate_by_type(self, type, quality=1):
gen = {
0: self.generate_sword(quality),
1: self.generate_arrow(quality),
2: self.generate_spear(quality),
3: self.generate_hammer(quality),
4: self.generate_wand(quality),
}
return gen[type]
#Returns 0 for Sword, 1 for Arrow, 2 for Spear, 3 for Hammer, 4 for Wand
def select_weapon_type(self):
#Would like to make this configurable
#currently 30% sword, 20% arrow, 20% spear, 20% hammer, 10% wand
rand = random.randint(1,100)
if rand <= 30:
return 0
elif rand <= 50:
return 1
elif rand <= 70:
return 2
elif rand <= 90:
return 3
else:
return 4
#Hard coded material look up, production product would use external data storage
def get_material(self, quality = 1):
materials = [ "Stone", "Copper", "Bronze", "Brass", "Silver", "Iron", "Gold", "Steel", "Platinum", "Mithril", "Adamantium" ]
if quality == 0:
return materials[random.randint(0,2)]
elif quality == 1:
return materials[random.randint(3,6)]
else:
return materials[random.randint(7,9)]
#Hard coded material look up, wood for wands (spears?)
def get_wood_material(self, quality = 1):
materials = [ "Fir", "White Oak", "Pine", "Alder", "Maple", "Hickory", "Mahogany", "Black Oak", "Black Walnut", "Yew", "Ironwood" ]
if quality == 0:
return materials[random.randint(0,2)]
elif quality == 1:
return materials[random.randint(3,7)]
else:
return materials[random.randint(8,10)]
#Generates a wand based on quality
def generate_wand(self, quality=1):
dist = Distributed_Random()
abs_range = Config.weapon["wand"]["abs_range"][quality]
min_range = Config.weapon["wand"]["min_range"][quality]
chance_range = Config.weapon["wand"]["chance_range"][quality]
chance_min = Config.weapon["wand"]["chance_min"][quality]
abs_min = Config.weapon["wand"]["abs_min"][quality]
min_min = Config.weapon["wand"]["min_min"][quality]
min_dam = dist.randint(min_min, min_range)
abs_dam = dist.randint(abs_min, abs_range)
max_dam = min_dam + abs_dam
chance = dist.randint(chance_min, chance_range)
name = self.get_wood_material(quality) + " Wand"
return Wand_Weapon(min_dam, max_dam, chance, name, 'desc')
#Generates a hammer's name based on quality
#0 for low, 1 for medium, 2 for high
#Returns a string
def generate_hammer_name(self, quality = 1):
mat = self.get_material(quality)
names = [ "Club", "Cudgel", "Mace", "Hammer", "Morning Star", "Flail", "Maul", "War Hammer", "Tetsubo", "Great Maul" ]
if quality == 0:
selected = names[random.randint(0,1)]
elif quality == 1:
selected = names[random.randint(2,6)]
else:
selected = names[random.randint(7,8)]
return mat + ' ' + selected
#Generates a hammer of variable quality
#Returns Hammer
#Quality parameter follows same format throughout
def generate_hammer(self, quality = 1):
dist = Distributed_Random()
abs_range = Config.weapon["hammer"]["abs_range"][quality]
min_range = Config.weapon["hammer"]["min_range"][quality]
chance_range = Config.weapon["hammer"]["chance_range"][quality]
chance_min = Config.weapon["hammer"]["chance_min"][quality]
abs_min = Config.weapon["hammer"]["abs_min"][quality]
min_min = Config.weapon["hammer"]["chance_range"][quality]
#Vary stats for high/low quality
min_dam = dist.randint(min_min,min_range)
abs_dam = dist.randint(abs_min,abs_range)
max_dam = min_dam + abs_dam
chance = dist.randint(chance_min,chance_range)
name = self.generate_hammer_name(quality)
return Hammer_Weapon(min_dam, max_dam, chance, name, 'desc')
#Same as the others, Generates Arrow names
def generate_arrow_name(self, quality=1):
mat = self.get_material(quality)
names = [ "Dart", "Throwing Knife", "Short Bow", "Long Bow", "Compound Bow", "Recurve Bow", "Light Crossbow", "Heavy Crossbow", "Matchlock Pistol", "Matchlock Rifle" ]
if quality == 0:
name = names[random.randint(0,2)]
elif quality == 1:
name = names[random.randint(3,6)]
else:
name = names[random.randint(7,9)]
return mat + ' embossed ' + name
#Generates an Arrow object of variable quality
def generate_arrow(self, quality = 1):
dist = Distributed_Random()
abs_range = Config.weapon["arrow"]["abs_range"][quality]
min_range = Config.weapon["arrow"]["min_range"][quality]
chance_range = Config.weapon["arrow"]["chance_range"][quality]
chance_min = Config.weapon["arrow"]["chance_min"][quality]
abs_min = Config.weapon["arrow"]["abs_min"][quality]
min_min = Config.weapon["arrow"]["min_min"][quality]
min_dam = dist.randint(min_min,min_range)
abs_dam = dist.randint(abs_min, abs_range)
max_dam = min_dam + abs_dam
chance = dist.randint(chance_min, chance_range)
return Arrow_Weapon(min_dam, max_dam, chance, self.generate_arrow_name(quality), 'desc')
#Generates a name for a spear of variable quality
def generate_spear_name(self, quality):
names = [ "Crude Spear", "Short Spear", "Long Spear", "Halberd", "Pike", "Yari", "Naginata", "Lance" ]
mat = self.get_material(quality)
if quality == 0:
name = names[random.randint(0,1)]
elif quality == 1:
name = names[random.randint(2,4)]
else:
name = names[random.randint(5,6)]
return mat + '-tipped ' + name
#Generates a Spear object of variable quality
def generate_spear(self, quality = 1):
dist = Distributed_Random()
abs_range = Config.weapon["spear"]["abs_range"][quality]
min_range = Config.weapon["spear"]["min_range"][quality]
chance_range = Config.weapon["spear"]["chance_range"][quality]
chance_min = Config.weapon["spear"]["chance_min"][quality]
abs_min = Config.weapon["spear"]["abs_min"][quality]
min_min = Config.weapon["spear"]["min_min"][quality]
min_dam = dist.randint(min_min, min_range)
abs_dam = dist.randint(abs_min, abs_range)
max_dam = min_dam + abs_dam
chance = dist.randint(chance_min, chance_range)
return Spear_Weapon(min_dam, max_dam, chance, self.generate_spear_name(quality), 'desc')
#Generates a name for a sword of variable quality
def generate_sword_name(self, quality):
names = [ "Shiv", "Knife", "Dagger", "Cleaver", "Short Sword", "Longsword", "Broadsword", "Rapier", "Epee", "Claymore", "Basterd Sword", "Greatsword" ]
mat = self.get_material(quality)
if quality == 0:
name = names[random.randint(0,3)]
elif quality == 1:
name = names[random.randint(4,7)]
else:
name = names[random.randint(8,11)]
return mat + ' ' + name
def generate_sword(self, quality = 1):
#generate sword with random stats and magical properties
dist = Distributed_Random()
abs_range = Config.weapon["sword"]["abs_range"][quality]
min_range = Config.weapon["sword"]["min_range"][quality]
chance_range = Config.weapon["sword"]["chance_range"][quality]
chance_min = Config.weapon["sword"]["chance_min"][quality]
abs_min = Config.weapon["sword"]["abs_min"][quality]
min_min = Config.weapon["sword"]["min_min"][quality]
min_dam = dist.randint(min_min, min_range)
abs_dam = dist.randint(abs_min, abs_range)
max_dam = min_dam + abs_dam
chance = dist.randint(chance_min, chance_range)
return Sword_Weapon(min_dam, max_dam, chance, self.generate_sword_name(quality), 'desc')
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,942
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Effect.py
|
#Authers: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Effect.py
#Base class which other Effects descend, should never be instantiated
class Effect:
def __init__(self, duration):
self.duration = duration
#Active effects need to be applied each round
#When the effect duration is decremented this method will be called
#Only Active effects need implement apply
def apply(self, owner):
#just apply yourself, slacker
self
#Stun Effect of variable duration, Stun prevents player or creatures for acting
class Stun_Effect(Effect):
def __init__(self, duration):
Effect.__init__(self, duration)
self.duration = duration
#Heal-Over-Time Effect, heals the effect by bonus hp every round
#for duration rounds
class HOT_Effect(Effect):
def __init__(self, duration, bonus):
Effect.__init__(self, duration)
self.bonus = bonus
def apply(self, owner):
owner.heal(self.bonus)
#Damage-Over-Time Effect, like HOT--but damage, (duh)
class DOT_Effect(Effect):
def __init__(self, duration, damage):
Effect.__init__(self, duration)
self.damage = damage
def apply(self, owner):
owner.hp -= self.damage
#Defense effect of variable duration and strength (bonus)
#Defense effects give you a bonus to DS vs Physical Attacks
class Defense_Effect(Effect):
def __init__(self, duration, bonus):
Effect.__init__(self, duration)
self.bonus = bonus
#Same as Defense_Effect, but gives you a bonus vs Magic Attacks
class Magic_Defense_Effect(Effect):
def __init__(self, duration, bonus):
Effect.__init__(self, duration)
self.bonus = bonus
#Offense effect of variable duration and strength (bonus)
#Offense effects give you a bonus to OS for Physical Attacks (Weapons)
class Offense_Effect(Effect):
def __init__(self, duration, bonus):
Effect.__init__(self, duration)
self.bonus = bonus
#Same as Offense_Effect, but gives you a bonus for Magic Attacks
class Magic_Offense_Effect(Effect):
def __init__(self, duration, bonus):
Effect.__init__(self, duration)
self.bonus = bonus
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,943
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Item_Module.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Item_Module.py
from Item_Interface import Item_Interface
from Effect import *
import random
#Base class from which all items descend
#Siblings include Potion, Spell, Weapon
class Item(Item_Interface):
def __init__(self, name, description):
self.name = name
self.description = description
#This method is the common interface that all items use to output the result of their use
#the "first" refers to first person, as in the player used the item
def output_result_first(self, result):
print "You used a Base class for %s damage... stupid" % result
#"third" here refers to third person, a creature used the item
def output_result_third(self, result):
print "hits you with an abstract base class for %s damage, ouch" % result
def __str__(self):
return self.name + ": " + self.description
class Potion(Item):
def __init__(self, name, description):
Item.__init__(self, name, description)
#output first for the use of a potion
def output_result_first(self, result):
print "You drink a %s" % self.name
#output third for the use of a potion
def output_result_third(self, result):
print "drinks a %s" % self.name
class Healing_Potion(Potion):
def __init__(self, name, description, min_heal, max_heal):
Potion.__init__(self, name, description)
self.min_heal = min_heal
self.max_heal = max_heal
#Special effects like healing the player are accomplished via these hooks
def attack_post(self, attacker, defender):
attacker.heal(random.randint(self.min_heal, self.max_heal))
class Defense_Potion(Potion):
def __init__(self, name, description, duration, bonus):
Potion.__init__(self, name, description)
self.duration = duration
self.bonus = bonus
#Give the user a Defense_Effect
def attack_post(self, attacker, defender):
attacker.add_effect(Defense_Effect(self.duration, self.bonus))
class Offense_Potion(Potion):
def __init__(self, name, description, duration, bonus):
Potion.__init__(self, name, description)
self.duration = duration
self.bonus = bonus
#Give the user an Offense_Effect
def attack_post(self, attacker, defender):
attacker.add_effect(Offense_Effect(self.duration, self.bonus))
class Magic_Defense_Potion(Potion):
def __init__(self, name, description, duration, bonus):
Potion.__init__(self, name, description)
self.duration = duration
self.bonus = bonus
#Give the user a Defense_Effect
def attack_post(self, attacker, defender):
attacker.add_effect(Magic_Defense_Effect(self.duration, self.bonus))
class Magic_Offense_Potion(Potion):
def __init__(self, name, description, duration, bonus):
Potion.__init__(self, name, description)
self.duration = duration
self.bonus = bonus
#Give the user an Offense_Effect
def attack_post(self, attacker, defender):
attacker.add_effect(Magic_Offense_Effect(self.duration, self.bonus))
class Spell(Item):
def __init__(self, name, description, difficulty):
Item.__init__(self, name, description)
self.difficulty = difficulty
#output a failed spell message first person
def print_fail_first(self):
print "You attempt to cast %s... but fail" % self.name
#output a failed spell message third person
def print_fail_third(self):
print "mutters a chant, nothing happens"
#output message for use a spell, first person
def output_result_first(self, result):
if result >= self.difficulty:
print "You cast %s" % self.name
else:
self.print_fail_first()
#output message for use of a spell, third person
def output_result_third(self, result):
if result >= self.difficulty:
print "casts %s" % self.name
else:
self.print_fail_third()
#Attack spells represent damaging spells
#Subclass of Spell
class Attack_Spell(Spell):
def __init__(self, name, description, difficulty, min_damage, max_damage):
Spell.__init__(self, name, description, difficulty)
self.min_damage = min_damage
self.max_damage = max_damage
#Output the result of an attack spell, first person
def output_result_first(self, result, damage=0):
self.result = result
if result >= self.difficulty:
print "You cast %s" % self.name, "hitting for %s damage" % damage
else:
self.print_fail_first()
#Output the result of an attack spell, first person
def output_result_third(self, result, damage=0):
self.result = result
if result >= self.difficulty:
print "casts %s on you," % result, "hitting for %s damage." % damage
else:
self.print_fail_third()
#Defense Spells grant defensive bonuses vs Physical attacks
#Duration is how long the effect lasts and bonus is how big the effect is
class Defense_Spell(Spell):
def __init__(self, name, description, difficulty, bonus, duration=3):
Spell.__init__(self, name, description, difficulty)
self.bonus = bonus
self.duration = duration
def output_result_first(self, result):
self.result = result
if result >= self.difficulty:
print "A glowing aura surrounds you, protecting you from harm"
else:
self.print_fail_first()
def output_result_third(self, result):
self.result = result
if result >= self.difficulty:
print "is suddenly wrapped in a protective aura"
else:
self.print_fail_third()
#this hook creates the effect that grants the user the bonus
#Note this appends the effect to the attacker (person using the spell)
#Generally spells could be targeted, but this game is really simple
def attack_post(self, attacker, defender):
if self.result >= self.difficulty:
attacker.effect.append(Defense_Effect(self.duration, self.bonus))
#Stun Spells stun the victim, rendering them unable to act
class Stun_Spell(Spell):
def __init__(self, name, description, difficulty, duration):
Spell.__init__(self, name, description, difficulty)
self.duration = duration
def output_result_first(self, result):
self.result = result
if result >= self.difficulty:
print "You cast %s" % self.name, "stunning your opponent for %s rounds!" % self.duration
else:
self.print_fail_first()
def output_result_third(self, result):
self.result = result
if result >= self.difficulty:
print "casts %s" % self.name, "stunning you for %s rounds!" % self.duration
else:
self.print_fail_third()
#This is where the stun effect is applied, again applied to the defender all the time
def attack_post(self, attacker, defender):
if self.result >= self.difficulty:
defender.add_effect(Stun_Effect(self.duration))
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,944
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Creature_Factory.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#File: Creature_Factory.py
from Armor_Factory import Armor_Factory
from Weapon_Factory import Weapon_Factory
from Player import Creature
import random
class Creature_Factory:
def __init__(self):
self
def generate(self):
return self.generate_difficulty(random.randint(0,10))
def generate_difficulty(self, diff):
#generate random name based on difficulty
#generate hp based on difficulty
hp = random.randint(30,50) * diff
genesis = Creature('Gen',hp)
genesis.weapon = list()
genesis.armor = list()
genesis = self.generate_stats(diff, genesis)
wf = Weapon_Factory()
af = Armor_Factory()
if diff <= 3:
genesis.add_armor(af.generate_by_quality(0))
genesis.add_weapon(wf.generate_by_quality(0))
elif diff <= 8:
genesis.add_armor(af.generate_by_quality(1))
genesis.add_weapon(wf.generate_by_quality(1))
else:
genesis.add_armor(af.generate_by_quality(2))
genesis.add_weapon(wf.generate_by_quality(2))
genesis.level = diff
genesis.gold = random.randint(0,diff*100)
genesis.name = self.generate_name(diff)
return genesis
def stat_max(self, max, gen):
gen.strength = random.randint(1, max)
gen.agility = random.randint(1, max)
gen.dexterity = random.randint(1, max)
gen.intel = random.randint(1, max)
gen.stamina = random.randint(1, max)
return gen
def generate_stats(self, diff, gen):
if diff <= 3:
gen = self.stat_max(3,gen)
elif diff <= 5:
gen = self.stat_max(diff, gen)
elif diff <= 10:
gen = self.stat_max(7, gen)
else:
gen = self.stat_max(diff, gen)
return gen
def generate_player_stats(self, player):
return self.generate_stats(5, player)
def generate_name(self, diff=1):
diff -= 1
if diff < 0:
diff = 0
if diff > 9:
diff = 9
names = [ "Kobold", "Goblin", "Orc", "Centaur", "Dark Elf", "Orc Chieftan", "Ogre", "Troll", "Cyclops", "Minotaur" ]
return names[diff]
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,945
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Treasure.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Treasure.py
from Weapon_Factory import *
from Armor_Factory import *
from Item_Factory import *
from Distributed_Random import *
class Treasure:
def __init__(self):
self
def generate(self, level):
dist = Distributed_Random()
wf = Weapon_Factory()
af = Armor_Factory()
items = Item_Factory()
treasure = list()
if random.randint(1,100) - (level*2) < 25:
#generate a random number of items
num = dist.randint(1,level//2)
while num > 0:
treasure.append(self.gen(level))
return treasure
def gen(self, level):
wf = Weapon_Factory()
af = Armor_Factory()
items = Item_Factory()
type = random.randint(1,3)
if type == 1:
if level <= 3:
return wf.generate_by_quality(random.randint(0,1))
elif level <= 7:
return wf.generate_by_quality(random.randint(1,2))
else:
return wf.generate_by_quality(2)
elif type == 2:
if level <= 3:
return af.generate_by_quality(random.randint(0,1))
elif level <= 7:
return af.generate_by_quality(random.randint(1,2))
else:
return af.generate_by_quality(2)
else:
if level <= 3:
return items.generate_by_quality(random.randint(1,2))
elif level <= 7:
return items.generate(random.randint(2,3))
else:
return items.generate(3)
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,946
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Static.py
|
class Static:
def __init__(self, static_method):
self.__call__ = static_method
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,947
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/CLI_Interface.py
|
#Authors: Brad Stephens, John Murray
#sProject: CSC 407 - Program 3
#Due: July 19th, 2010
#File: CLI_Interface.py
import random
import Arena
import sys
import Treasure
from Weapon_Module import *
from Player import *
from Item_Module import *
from Armor import *
from Arena import Arena
from Creature_Factory import *
from Treasure import Treasure
#class: CLI
#purpose: A Command Line Interface class that handles the parsing of user
# input and validation of input, the execution of non-turn based
# commands, and returns the values of turn-based commands.
class CLI:
def __init__(self, player, level):
self.player = player
self.level = level
#lists commands with a dict and tuple that defines
#(cli-controlled/handled, options(name), description(for help), param_type)
self.commands = {
"help" : (True, '', 'Shows the help dialog all available commands (not much un-similar to this page)turn/move.', None),
"vhelp" : (True, 'command', 'Verbose help command. Show description for individual commands. (type `vhelp *` to see all commands)', str),
"map" : (True, '', 'Shows the map of the Level and where all the creatures on on the map', None),
"status" : (True, '', 'Shows current player stats.', None),
"move-north": (False, '', 'Moves through the level. Not allowed when you enter a room with a creature (an alive one).', None),
"move-east": (False, '', 'Moves through the level. Not allowed when you enter a room with a creature (an alive one).', None),
"move-south": (False, '', 'Moves through the level. Not allowed when you enter a room with a creature (an alive one).', None),
"move-west": (False, '', 'Moves through the level. Not allowed when you enter a room with a creature (an alive one).', None),
"flee": (True, '', 'Similar to move-* command. Allows you to flee a room where monster is, but the room is random and you may drop weapons, items, or gold when fleeing.', None),
"attack": (True, '', 'Attack an opponent when in battle with primary weapon.', None),
"magic-attack": (True, 'id', 'Attack an opponent with a spell. Must give id.(Use the inventory-spell to get spell id).', int),
"look-around": (True, '', 'Look at all the items currently in the room. Shows item name and id.', None),
"study": (True, 'id', 'View an item in the room in great detail. A.K.A - View the item\'s stats and/or description, etc. Must give item id. (use look-around to get item id)', int),
"pickup": (True, 'id', 'Pick up and item in the room. Must give item id. (use look-around to get item id)', int),
"switch-weapon": (True, 'id', 'Change your primary weapon. Must give id. (use weapon-inventory to get id)', int),
"switch-armor":(True, 'id', 'Change your primary armor. Must give id. (use inventory-armor to get id)', int),
"inventory-weapon": (True, '', 'List your current weapon inventory. View each weapon\'s name and id.', None),
"inventory-armor": (True, '', 'List your current armor inventory. View each armor\'s name and id.', None),
"inventory-potion": (True, '', 'List your current potion inventory. View each potion\'s name and id.', None),
"inventory-spell": (True, '', 'List your current spell inventory. View each spell\'s name and id.', None),
"inspect-weapon": (True, 'id',
'View an weapon in the inventory in great detail. A.K.A - View the weapon\'s stats and/or description, etc. Must give id. (use inventory-weapon to get item id)', int),
"inspect-armor": (True, 'id',
'View an armor in the inventory in great detail. A.K.A - View the armor\'s stats and/or description, etc. Must give id. (use inventory-armor to get item id)', int),
"inspect-potion": (True, 'id',
'View an potion in the inventory in great detail. A.K.A - View the potion\'s stats and/or description, etc. Must give id. (use inventory-potion to get item id)', int),
"inspect-spell": (True, 'id',
'View an spell in the inventory in great detail. A.K.A - View the spell\'s stats and/or description, etc. Must give id. (use inventory-spell to get item id)', int),
"drop-weapon": (True, 'id', 'Drop a weapon in the inventory. Must give weapon id. (use inventory-weapon to get weapon id)', int),
"drop-armor": (True, 'id', 'Drop an armor in the inventory. Must give armor id. (use inventory-armor to get armor id)', int),
"drop-potion": (True, 'id', 'Drop a potion in the inventory. Must give potion id. (use inventory-potion to get potion id)', int),
"drop-spell": (True, 'id', 'Drop an spell in the inventory. Must give spell id. (use inventory-spell to get spell id)', int),
"buy-attribute": (True, 'attribute', 'Buy a specific attribute point with your current AP.', str),
"use-potion": (True, 'id', 'Use a potion.', int),
}
self.command = ''
self.params = ''
#def: get_command
#purpose: return a command from the user.
#note: This command is a recursive definition
#note: If a non-turn command is entered, it is executed
#returns: list() in form of:
# 0 => command
# 1 => parameter or empty string (for no-parameter)
def get_command(self):
print "command> "
command = raw_input()
while( not self.valid_command(command) ):
command = raw_input()
print "Error: Command is not of valid syntax. `command [options]`"
print "command>"
(self.command, seperator, self.params) = command.partition(" ")
#check and see if the command exists
if( self.command_defined() ):
#validate the parameter (if required)
if( self.validate_parameter() ):
#check if the parameter is execute locally
if( self.cli_handled() ):
self.execute()
return self.get_command()
else:
return [self.command, self.params]
#parameter validation has faild (aka - none given when one or more needed)
else:
print "Error: Parameter must be given and of correct type. Please refer to the help guide by typing 'help.'"
return self.get_command()
#command is not defined
else:
#print error and start over
print "Error: Command not defined"
return self.get_command()
def cli_handled(self):
return self.commands.get(self.command)[0]
#def: valid_command
#purpose: determine if the user input is valid (aka - not empty)
def valid_command(self, command):
(first_token, seperator, second_token) = command.partition(" ")
#determine if the command (first_token) is valid and then if the
#parameters are valid
if( first_token != ''):
return True
else:
return False
#def: command_defined
#purpose: determine of a command is in the list of commands
def command_defined(self):
command = self.commands.get(self.command, None)
if( command != None ):
return True
else:
return False
def validate_parameter(self):
#if it requires a param, check that there is one
if(self.commands.get(self.command)[1] != ''):
if( self.params != ''):
if( self.commands.get(self.command)[3] == int ):
try:
self.params = int(self.params)
except:
return False
return True
elif( self.commands.get(self.command)[3] == str ):
try:
self.params = str( self.params )
except:
return False
return True
else:
return False
#this should 'theoretically' NEVER be reached, but for safety...
else:
return True
#EXECUTE (or related) FUNCTION(S) FROM THIS POINT ON
#def: execute
#purpose: execute a command that is non-turn based.
def execute(self):
#allow these commands regardless
creature = self.level.get_current_room().creature
if( self.command == "help" ):
self.execute_help()
elif( self.command == "vhelp" ):
self.execute_vhelp()
elif( self.command == "map" ):
self.execute_map()
elif( self.command == "look-around" ):
self.execute_lookaround()
elif( self.command == "study" ):
self.execute_study()
elif( self.command[0:9] == "inventory" ):
self.execute_inventory()
elif( self.command[0:7] == "inspect" ):
self.execute_inspect()
elif( self.command == "switch-weapon" ):
self.execute_switch_weapon()
elif( self.command == "switch-armor" ):
self.execute_switch_armor()
elif( self.command == "status" ):
self.execute_status()
#if there are NO creatures in the room, then allow these
#command
elif( self.level.get_current_room().creature == None ):
if( self.command == "pickup" ):
self.execute_pickup()
elif( self.command[0:4] == "drop" ):
self.execute_drop()
elif( self.command == 'use-potion' ):
self.execute_use_potion()
elif( self.command == 'buy-attribute' ):
self.execute_buy_attribute()
#possibly generate mob since there is no creature in a room
if( creature == None and self.level.mob_size > 0):
if( random.randrange(100) > 80 ):
cf = Creature_Factory()
c = cf.generate()
self.level.get_current_room().creature = c
self.level.mob_size -= 1
print c.name + " entered the room!"
#if there is a creature in the room, then allow these commands
elif( self.level.get_current_room().creature != None ):
if( self.command == "flee" ):
self.execute_flee()
elif( self.command == "attack" ):
self.execute_attack()
elif( self.command == "magic-attack" ):
self.execute_magic_attack()
elif(self.command == 'use-potion' ):
self.execute_use_potion()
#check if the creature or the player is dead
if(creature != None):
if( creature.hp <= 0 ):
diff = creature.level - self.player.level
xp = 0
if diff >= 0:
xp = creature.calc_experience() * (diff+1)
else:
tmp = (diff * -20) // 100
xp = int(creature.calc_experience() * tmp)
self.player.grant_xp(xp)
print "You gained %s XP for slaying the" % xp,
print creature.name + "."
print "You collected %s gold coins from the corpse." % creature.gold
self.player.gold += creature.gold
tf = Treasure()
treasure = tf.generate(creature.level)
for t in treasure:
self.level.get_current_room().item.append(t)
for p in creature.all_equipment():
self.level.get_current_room().item.append(p)
self.level.get_current_room().creature = None
if(self.player.hp <= 0):
print "Game Over! You died sucka!"
sys.exit()
def execute_buy_attribute(self):
ap = self.player.ap
suck = False
if( self.params == "strength" ):
s = self.player.strength
cost = (s ** 2) / 2
if( ap >= cost ):
self.player.strength += 1
print "Strength increased by one"
self.player.ap -= cost
else:
suck = True
elif( self.params == "agility" ):
a = self.player.agility
cost = (a ** 2) / 2
if( ap >= cost ):
self.player.agility += 1
self.player.ap -= cost
print "Agility increased by one"
else:
suck = True
elif( self.params == "dexterity" ):
d = self.params.dexterity
cost = (d ** 2) / 2
if( ap >= cost ):
self.player.dexterity += 1
self.player.ap -= cost
print "Dexterity increased by one"
else:
suck = True
elif( self.params == "intelligence" ):
i = self.player.intel
cost = (i ** 2) / 2
if( ap >= cost):
self.player.intel += 1
self.player.ap -= cost
print "Intelligence increased by one"
else:
suck = True
elif( self.params == "stamina" ):
s = self.player.stamina
cost = (s ** 2) / 2
if( ap >= cost ):
self.player.stamina += 1
self.player.ap -= cost
print "Stamina increased by one"
else:
suck = True
else:
print "You cannot buy an attribute that does not exist."
if suck:
print "You don't have enough AP, try again later."
def execute_status(self):
print "Status: %(n)s" % {'n': self.player.name}
p = self.player
out = 'HP: ' + str(p.hp) + '/' + str(p.max_hp) + "\n"
out += 'Strength: ' + str(p.strength) + "\n"
out += 'Agility: ' + str(p.agility) + "\n"
out += 'Dexterity: ' + str(p.dexterity) + "\n"
out += 'Intelligence: ' + str(p.intel) + "\n"
out += 'Stamina: ' + str(p.stamina) + "\n"
out += 'AP: ' + str(p.ap) + "\n"
print out
#assuming 80 console width
bar_width = 74
out = 'XP: |'
completion = float(self.player.experience) / float(self.player.next_level)
completion2 = int(round(float(74 * completion)))
for i in range(completion2):
out += '='
for i in range(bar_width - completion2):
out += ' '
out += '|'
print out
print str( round(completion*100) ) + '%'
def execute_map(self):
#print header
print "Level Map"
print self.level
def execute_switch_armor(self):
if( self.params > len(self.player.armor) - 1 or self.params < 0 ):
print "Armor does not exist, try again"
elif( self.params == 0 ):
print "Already eqquiped"
else:
#make sure they meet the weapon requirements
p = self.player
if( p.strength < p.armor[self.params].required_strength ):
print "Do not have the required strength to equip armor. It didn't look good on anyways."
return
temp = self.player.armor[self.params]
self.player.armor[self.params] = self.player.armor[0]
self.player.armor[0] = temp
print "Armor equipped"
def execute_switch_weapon(self):
if( self.params > len(self.player.weapon) - 1 or self.params < 0 ):
print "Weapon does not exist, try again"
elif( self.params == 0 ):
print "Already equipped"
else:
p = self.player
if( p.strength < p.weapon[self.params].required_strength or
p.agility < p.weapon[self.params].required_agility):
print "You do not have enough strength or agility to equip weapon. Get out of the computer chair once in a while, workout more."
return
if( isinstance(p.weapon[self.params], Wand_Weapon )):
if( p.intel < p.weapon[self.params].required_intel ):
print "You do not have enough intelligence to use this weapon. Pick up a book or something."
return
temp = self.player.weapon[self.params]
self.player.weapon[self.params] = self.player.weapon[0]
self.player.weapon[0] = temp
print "Weapon equipped"
def execute_use_potion(self):
if( self.level.get_current_room().creature != None ):
arena = Arena(self.player, self.level.get_current_room().creature)
if( len(self.player.potion) - 1 >= self.params and self.params >= 0 ):
arena.potion(self.params)
self.player.potion.pop(self.params)
else:
#use the potion
if( len(self.player.potion) - 1 >= self.params and self.params >= 0 ):
self.player.potion[self.params].attack_post(self.player, None)
self.player.potion.pop(self.params)
def execute_magic_attack(self):
arena = Arena(self.player, self.level.get_current_room().creature)
if( len(self.player.spells) - 1 >= self.params and self.params >= 0 ):
arena.magic_attack(self.params)
self.player.spells.pop(self.params)
def execute_attack(self):
arena = Arena(self.player, self.level.get_current_room().creature)
arena.attack()
def execute_flee(self):
#get random direction
valid = False
while( not valid ):
direction = random.randrange(1, 5)
if( direction == 1 ):
if( self.level.has_north() ):
valid = True
if( direction == 2 ):
if( self.level.has_east() ):
valid = True
if( direction == 3 ):
if( self.level.has_south() ):
valid = True
if( direction == 4 ):
if( self.level.has_west() ):
valid = True
#get randome type {1:weapon, 2:armor, 3:potion, 4:spell}
drop_type = random.randrange(1, 5)
if( drop_type == 1 ):
if( len(self.player.weapon) > 1 ):
drop_id = random.randrange(len(self.player.weapon))
print "you dropped a weapon"
else:
drop_id = -1
if( drop_type == 2 ):
if( len(self.player.armor) > 1 ):
drop_id = random.randrange(len(self.player.armor))
print "you dropped your armor"
else:
drop_id = -1
if( drop_type == 3 ):
if( len(self.player.potion) > 0 ):
drop_id = random.randrange(len(self.player.potion))
print "you dropped a potion"
else:
drop_id = -1
if( drop_type == 4 ):
if( len(self.player.spells) > 0 ):
drop_id = random.randrange(len(self.player.spells))
print "you dropped a spell"
else:
drop_id = -1
#get amount of gold to drop
if( self.player.gold > 0 ):
gold_range = round(self.player.gold * .1)
if( gold_range > 0 ):
gold_drop = random.randrange(1, gold_range + 1)
else:
gold_drop = 0
else:
gold_drop = 0
#move to a random room
{
1: self.level.move_north,
2: self.level.move_east,
3: self.level.move_south,
4: self.level.move_west,
}[direction]()
#drop something random
if( drop_id != -1 ):
self.level.get_current_room().item.append( {
1: self.player.weapon,
2: self.player.armor,
3: self.player.potion,
4: self.player.spells,
}[drop_type].pop(drop_id))
#decrement player's gold
self.player.gold -= gold_drop
def execute_inspect(self):
try:
if( self.command[8:] == "weapon" ):
print self.player.weapon[self.params]
if( self.command[8:] == "armor" ):
print self.player.armor[self.params]
if( self.command[8:] == "potion" ):
print self.player.potion[self.params]
if( self.command[8:] == "spell" ):
print self.player.spells[self.params]
except:
print "Can't inspect " + self.command[8:] + " that does not exist"
def execute_inventory(self):
i = 0
if( self.command[10:] == "weapon" ):
for w in self.player.weapon:
print "[%(id)i] %(d)s" % {'id': i, 'd': str(w)}
i += 1
if( self.command[10:] == "armor" ):
for a in self.player.armor:
print "[%(id)i] %(d)s" % {'id': i, 'd': str(a)}
i += 1
if( self.command[10:] == "potion" ):
for p in self.player.potion:
print "[%(id)i] %(d)s" % {'id': i, 'd': str(p)}
i += 1
if( self.command[10:] == "spell" ):
for s in self.player.spells:
print "[%(id)i] %(d)s" % {'id': i, 'd': str(s)}
i += 1
def execute_drop(self):
try:
if( self.command[5:] == 'weapon' ):
item = self.player.weapon.pop(self.params)
if( self.command[5:] == 'armor' ):
item = self.player.armor.pop(self.params)
if( self.command[5:] == 'potion' ):
item = self.player.potion.pop(self.params)
if( self.command[5:] == 'spell' ):
item = self.player.spells.pop(self.params)
self.level.get_current_room().item.append(item)
except:
print "Unable to drop item that is not in inventory"
def execute_pickup(self):
room = self.level.get_current_room()
try:
item = room.item[self.params]
#get item type
if( isinstance(item, Potion) ):
self.player.potion.append(item)
print "Potion added to inventory"
elif( isinstance(item, Spell) ):
self.player.spells.append(item)
print "Spell added to inventory"
elif( isinstance(item, Armor) ):
self.player.armor.append(item)
print "Armor added to inventory"
elif( isinstance(item, Weapon) ):
self.player.weapon.append(item)
print "Weapon added to inventory"
room.item.pop(self.params)
except:
print 'Item with id of ' + str(self.params) + ' does not exist in the room'
def execute_study(self):
if( self.params == -1 ):
try:
print self.level.get_current_room().creature
except:
print "Sorry, no information"
else:
try:
print self.level.get_current_room().item[self.params]
except:
print ''
def execute_lookaround(self):
room = self.level.get_current_room()
items = room.item
i = 0
for item in items:
print "[%(id)i] - %(descrip)s" % {'id':i, 'descrip':item.name}
i += 1
if( room.creature != None ):
print "[%(id)i] - %(descrip)s" % {'id':-1, 'descrip':room.creature.name}
def execute_help(self):
for tag, (turn_based, params, description, junk) in self.commands.items():
print tag
print ""
def execute_vhelp(self):
for tag, (turn_based, params, description, junk) in self.commands.items():
if( self.params == '*' or self.params == tag ):
if( params == '' ):
tag_param = ''
else:
tag_param = ' [%s]' % params
print tag + tag_param
print "\t" + description
print ""
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,948
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Config.py
|
#Authors: Brad Stephens, John Murray
#Configuration File
weapon = {}
sword = {}
sword["min_min"] = ( 1, 1, 7 )
sword["abs_min"] = ( 3, 3, 7 )
sword["chance_min"] = ( 0, 0, 5 )
sword["abs_range"] = ( 21, 33, 33 )
sword["min_range"] = ( 12, 21, 21 )
sword["chance_range"] = ( 5, 10, 10 )
weapon["sword"] = sword
hammer = {}
hammer["min_min"] = ( 10, 10, 18 )
hammer["abs_min"] = ( 5, 5, 10 )
hammer["chance_min"] = ( 0, 0, 1 )
hammer["abs_range"] = ( 31, 41, 41 )
hammer["min_range"] = ( 22, 30, 30 )
hammer["chance_range"] = ( 3, 6, 6 )
weapon["hammer"] = hammer
spear = {}
spear["min_min"] = ( 5, 5, 11, )
spear["abs_min"] = ( 3, 3, 9, )
spear["chance_min"] = ( 0, 0, 2, )
spear["abs_range"] = ( 21, 33, 33, )
spear["min_range"] = ( 16, 25, 25, )
spear["chance_range"] = ( 4, 8, 8, )
weapon["spear"] = spear
arrow = {}
arrow["min_min"] = ( 12, 12, 22, )
arrow["abs_min"] = ( 5, 5, 10, )
arrow["chance_min"] = ( 0, 0, 1, )
arrow["abs_range"] = ( 26, 36, 36, )
arrow["min_range"] = ( 25, 35, 35, )
arrow["chance_range"] = ( 3, 6, 6, )
weapon["arrow"] = arrow
wand = {}
wand["min_min"] = ( 14, 14, 28, )
wand["abs_min"] = ( 3, 3, 7, )
wand["chance_min"] = ( 0, 0, 1, )
wand["abs_range"] = ( 10, 20, 20 )
wand["min_range"] = ( 18, 37, 37 )
wand["chance_range"] = ( 3, 5, 5 )
weapon["wand"] = wand
item = {
'spell': {
'attack': {
'common': (1, 3, 1, 3, 1, 3),
'normal': (2, 4, 2, 4, 2, 4),
'rare': (4, 6, 4, 6, 4, 6),
},
'defense': {
'common': (1, 3, 1, 3, 1, 3),
'normal': (2, 4, 2, 4, 2, 4),
'rare': (4, 6, 4, 6, 4, 6),
},
'stun': {
'common': (1, 3, 1, 3),
'normal': (2, 4, 2, 4),
'rare': (4, 6, 4, 6),
},
},
'potion': {
'magic_offense': {
'common': (1, 3, 1, 3),
'normal': (1, 5, 3, 6),
'rare': (3, 7, 4, 8),
},
'magic_defense': {
'common': (1, 3, 1, 3),
'normal': (3, 5, 2, 5),
'rare': (4, 6, 3, 7),
},
'healing': {
'common': (20, 30),
'normal': (80, 100),
'rare': (160, 200),
},
'defense': {
'common': (1, 3, 1, 3),
'normal': (1, 5, 3, 5),
'rare': (3, 7, 4, 6),
},
'offense': {
'common': (1, 3, 2, 5),
'normal': (1, 6, 3, 6),
'rare': (3, 7, 5, 11),
},
},
}
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,949
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Weapon_Module.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Weapon.py
from Item_Module import Item
import random
from Distributed_Random import Distributed_Random
class Weapon(Item):
def __init__(self, min_damage, max_damage, chance, name, description):
Item.__init__(self, name, description)
self.min_damage = min_damage
self.max_damage = max_damage
self.abs_damage = min_damage + max_damage * 2
if chance > 20:
self.chance = 20
else:
self.chance = chance
self.speed = self.calc_speed()
self.required_strength = self.calc_required_strength()
self.required_agility = self.calc_required_agility()
self.score = self.score()
self.proc = list()
return
def output_result_first(self, result, damage=0):
self.result = result
self.damage = damage
if result >= 0:
print "You attack for %s damage" % damage
else:
print "You attack, but miss"
def output_result_third(self, result, damage=0):
self.result = result
self.damage = damage
if result >= 0:
print "attacks you for %s damage" % damage
else:
print "attacks you, but misses"
def attack_post(self, attacker, defender):
for p in self.proc:
p.attack_post(attacker, defender, self.result, self.damage)
#Quick way of quantifying a weapon's statistics
#not a very accurate estimate of actual quality
def score(self):
score = self.min_damage
score += 2 * self.max_damage
score += 5 * self.chance
score += 3 * self.speed
return score
def calc_required_strength(self):
return self.abs_damage // 18
def calc_required_agility(self):
req = self.chance - 4
if req < 0:
req = 0
return req
def calc_speed(self):
speed = 21 - (self.abs_damage // 10)
return speed
def add_proc(self, proc):
self.proc.append(proc)
class Sword_Weapon(Weapon):
def __init__(self, min_damage, max_damage, chance, name, description):
Weapon.__init__(self, min_damage, max_damage, chance, name, description)
#In production could would have a database of attack descriptions
#choosing them at random based on result and damage (critical hits)
def output_result_first(self, result, damage=0):
self.result = result
self.damage = damage
if result >= 0:
print "You swing your %s," % self.name,
print "hitting for %s damage." % damage
else:
print "You swing your %s, but miss" % self.name
def output_result_third(self, result, damage=0):
self.result = result
self.damage = damage
if result >= 0:
print "swings a %s at you," % self.name,
print "hitting you for %s damage." % damage
else:
print "swings a %s at you, but misses." % self.name
class Arrow_Weapon(Weapon):
def __init__(self, min_damage, max_damage, chance, name, description):
Weapon.__init__(self, min_damage, max_damage, chance, name, description)
def output_result_first(self, result, damage=0):
self.result = result
self.damage = damage
aim = "You aim and fire your " + self.name + ","
if result>= 0:
print aim,
print "it hits the target for %s damage." % damage
else:
print aim,
print "but miss the target."
def output_result_third(self, result, damage=0):
self.result = result
self.damage = damage
aim = "aims and fires a " + self.name + " at you,"
if result >= 0:
print aim,
print "it hits you for %s damage." % damage
else:
print aim,
print "it flies wide."
def calc_required_agility(self):
abs_damage = self.min_damage + self.max_damage * 2
return abs_damage // 18
def calc_required_strength(self):
return self.calc_required_agility() // 2
def calc_speed(self):
speed = 18 - self.abs_damage // 10
return speed
class Spear_Weapon(Weapon):
def __init__(self, min_damage, max_damage, chance, name, description):
Weapon.__init__(self, min_damage, max_damage, chance, name, description)
def output_result_first(self, result, damage=0):
self.result = result
self.damage = damage
tmp = "You thrust your " + self.name + " at your foe,"
if result >= 0:
print tmp,
print "you hit your target for %s damage." % damage
else:
print tmp,
print "but miss."
def output_result_third(self, result, damage=0):
self.result = result
self.damage = damage
tmp = "thrusts a " + self.name + " at you,"
if result >= 0:
print tmp,
print "it hits you for %s damage" % damage
else:
print tmp,
print "but misses you."
class Hammer_Weapon(Weapon):
def __init__(self, min_damage, max_damage, chance, name, description):
Weapon.__init__(self, min_damage, max_damage, chance, name, description)
def output_result_first(self, result, damage=0):
self.result = result
self.damage = damage
tmp = "You swing your " + self.name + " at the enemy,"
if result >= 0:
print tmp,
print "bashing it for %s damage." % damage
else:
print tmp,
print "WHIFF!"
def output_result_third(self, result, damage=0):
self.result = result
self.damage = damage
tmp = "swings a " + self.name + " at you,"
if result >= 0:
print tmp,
print "slamming you for %s damage." % damage
else:
print tmp,
print "you dodge."
def calc_speed(self):
speed = 14 - self.abs_damage // 10
return speed
#Probably not how I would implement wands ideally. Quicky and dirty, right?
class Wand_Weapon(Weapon):
def __init__(self, min_damage, max_damage, chance, name, description):
Weapon.__init__(self, min_damage, max_damage, chance, name, description)
self.required_intel = self.calc_required_intel()
def output_result_first(self, result, damage=0):
self.result = result
self.damage = damage
tmp = "You wave your " + self.name + " at the enemy,"
if result >= 0:
print tmp,
print "the bolt of magical energy lands for %s damage." % damage
else:
print tmp,
print "but you miss the mark."
def output_result_third(self, result, damage=0):
self.result = result
self.damage = damage
tmp = "waves a " + self.name + " at you, a blast of magical energy flies toward you,"
if result >= 0:
print tmp,
print "striking you for %s damage." % damage
else:
print tmp,
print "but misses."
def calc_required_intel(self):
return self.abs_damage // 18
def calc_required_strength(self):
return 1
def calc_required_agility(self):
return 1
def calc_speed(self):
speed = 14 - self.abs_damage // 10
return speed
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,950
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Level.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Level.py
#Note: Level consists of a 2-dimensional list (acts as an array) that creates
# a matrix of Rooms. This makes moving directionally (north, south, etc.)
# more natural programatically
import Room_Module
from Room_Module import *
import random
#Level
# __init__ : constructor
# move_(north, east, south, west): move to a new room
# (get, set)_current_room: getter and setter for current/active room
# defeated_all_creatures: (bool) are all creatures defeated
# number_of_creatures_left: the num. of creatures in level still
# __iter__ : exposes and iterator for the Level class
class Level:
def __init__(self, dimension, mob_size = -1):
#code here
#self.rooms = list()
#for i in range(0, dimension):
# #create a sub-list
# self.rooms.append(list())
# for j in range(0, dimension):
# #create a room
# rf = Room_Factory()
# room = rf.generate()
# self.rooms[i].append(room)
#self.current = (0, 0)
#new labyrinth code here
self.gen_lab(dimension)
self.current = (0, 0)
#determine mob size here
if( mob_size == -1 ):
self.mob_size = round(dimension / 2)
else:
self.mob_size = mob_size
#def: rr
#purpose: random room (rr) return
def rr(self, r):
if( random.randrange(100) > 50):
return r
else:
return None
def gen_lab(self, dimension):
self.rooms = list()
for i in range(dimension):
self.rooms.append(list())
for j in range(dimension):
rf = Room_Factory()
room = rf.generate()
if( i == 0 and j == 0 ):
self.rooms[i].append(room)
elif( i == dimension - 1 ):
self.rooms[i].append(room)
else:
#if room above
if( i > 0 and self.rooms[i - 1][j] != None ):
#if no room above left
if( j == 0 or self.rooms[i - 1][j - 1] == None ):
#if no room above right
if( j == dimension - 1 or self.rooms[i - 1][j + 1] == None ):
self.rooms[i].append(room)
#there is a room above-right
else:
self.rooms[i].append(self.rr(room))
#there is room above-left
else:
k = i - 1
l = j - 1
solved = False
#while there are rooms still to the left
while( l > -1 and self.rooms[k][l] != None and not solved):
#room has a room below
if( k < dimension - 1 and self.rooms[k + 1][l] != None ):
self.rooms[i].append(self.rr(room))
solved = True
#room has no room below
else:
l -= 1
else:
#we did not find a connecting path/room
if( solved == False ):
self.rooms[i].append(room)
#there are no rooms above
else:
self.rooms[i].append(self.rr(room))
def __str__(self):
out = ''
for i in self.rooms:
out2 = ''
for j in i:
if j == None:
out2 += ' '
elif( j == self.get_current_room() ):
out2 += 'I'
else:
out2 += 'X'
out += out2 + "\n"
out += "Legend:\nX => Room\nI => You\n"
return out
def move_north(self):
i = self.current[0]
j = self.current[1]
if i == 0:
i = len(self.rooms) - 1
else:
i+=1
self.current = (i, j)
def move_north_lab(self):
i = self.current[0]
j = self.current[1]
if( i == 0 ):
print "You cannot travel north form here."
else:
if( self.rooms[i-1][j] == None ):
print "You cannot travel north from here."
else:
i -= 1
self.current = (i, j)
def move_east(self):
i = self.current[0]
j = self.current[1]
if j == len(self.rooms[i]) - 1:
j = 0
else:
j+=1
self.current = (i, j)
def move_east_lab(self):
i = self.current[0]
j = self.current[1]
if( j == len(self.rooms[i]) - 1):
print "You cannot travel east from here."
else:
if( self.rooms[i][j+1] == None ):
print "You cannot travel east from here."
else:
j += 1
self.current = (i, j)
def move_south(self):
i = self.current[0]
j = self.current[1]
if i == len(self.rooms) - 1:
i = 0
else:
i-=1
self.current = (i, j)
def move_south_lab(self):
i = self.current[0]
j = self.current[1]
if( i == len(self.rooms) - 1 ):
print "You cannot move south from here."
else:
if( self.rooms[i + 1][j] == None ):
print "You cannot move south from here."
else:
i += 1
self.current = (i, j)
def move_west(self):
i = self.current[0]
j = self.current[1]
if j == 0:
j = len(self.rooms[i]) - 1
else:
j-=1
self.current = (i, j)
def move_west_lab(self):
i = self.current[0]
j = self.current[1]
if( j == 0 ):
print "You cannot travel west from here."
else:
if( self.rooms[i][j - 1] == None ):
print "You cannot travel west from here."
else:
j -= 1
self.current = (i, j)
def get_current_room(self):
return self.rooms[self.current[0]][self.current[1]]
def set_current_room(self, room):
self.rooms[self.current[0]][self.current[1]] = room
def defeated_all_creatures(self):
flag = True
for i in self.rooms:
for j in i:
if( j != None ):
if j.creature != None:
flag = False
return flag
def number_of_creatures_left(self):
count = 0
for i in self.rooms:
for j in i:
if j != None:
if j.creature != None:
count+=1
def __iter__(self):
for i in self.rooms:
for j in i:
yield j
def has_north(self):
i = self.current[0]
j = self.current[1]
if( i == 0 ):
return False
elif(self.rooms[i-1][j] == None ):
return False
return True
def has_east(self):
i = self.current[0]
j = self.current[1]
if( j == len(self.rooms[i])-1 ):
return False
elif( self.rooms[i][j+1] == None ):
return False
return True
def has_south(self):
i = self.current[0]
j = self.current[1]
if( i == len(self.rooms)-1 ):
return False
elif( self.rooms[i + 1][j] == None ):
return False
return True
def has_west(self):
i = self.current[0]
j = self.current[1]
if( j == 0 ):
return False
elif( self.rooms[i][j-1] == None ):
return False
return True
#override for navigation (remove to use old nav style)
move_north = move_north_lab
move_east = move_east_lab
move_south = move_south_lab
move_west = move_west_lab
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,951
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Distributed_Random.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File Distributed_Random.py
import math
import random
#A class to generate random numbers with distributions rather than equal chance
class Distributed_Random:
def __init__(self):
self
def randint(self, low, high):
diff = math.floor(high - low)
mid = low + (diff // 2)
mid *= 1000
diff *= 1000
sd1 = math.floor(.33 * diff)
sd2 = math.floor(.44 * diff)
sd3 = diff // 2
#Can make it err towards inferior stats to make great equipment more rare
positive = random.randint(1,100)
roll = random.randint(1,100)
if roll <= 66:
if positive >= 75:
return random.randint(round(mid / 1000),round((mid+sd1) / 1000))
else:
return random.randint(round((mid-sd1) / 1000),round(mid / 1000))
elif roll <= 88:
if positive >= 75:
return random.randint(round(mid / 1000),round((mid+sd2) / 1000))
else:
return random.randint(round((mid-sd2) / 1000),round(mid / 1000))
else:
if positive >= 75:
return random.randint(round(mid / 1000),round((mid+sd3) / 1000))
else:
return random.randint(round((mid-sd3) / 1000),round(mid / 1000))
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,952
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Proc.py
|
#Authors Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Proc.py
import random
from Effect import *
from Player import Adventurer
import math
#Procs are effects that can be attached to weapons/armor
#Procs cause various effects examples elemental damage, chance to stun
#Procs are classified as Armor_Proc and Weapon_Proc
class Proc:
def __init__(self):
self.prefix = ""
self.suffix = ""
#Armor_Proc's happen on defense_post and have various effects
#Typically require a hit and a chance of firing
#Not for human consumption, use concrete implementations
class Armor_Proc(Proc):
def __init__(self):
Proc.__init__(self)
#abstract implementation of defense_post
def defense_post(self, attacker, defender, result, damage):
pass
#Weapon_Proc's happen on attack_post and have various effects
#Typically require a hit and have a chance of firing
#Not for human consumption use concrete implementations
class Weapon_Proc(Proc):
def __init__(self):
Proc.__init__(self)
#abstract implementation of attack_post
def attack_post(self, attacker, defender, result, damage):
pass
#Thorn_Proc does damage to an attack on a hit
class Thorn_Proc(Armor_Proc):
def __init__(self, chance, damage):
Armor_Proc.__init__(self)
self.chance = chance
self.damage = damage
self.prefix = "Thorny"
self.suffix = "of Thorns"
#Remove thorn damage hp from attacker
def defense_post(self, attacker, defender, result):
#If hit and less roll < chance
if result >= 0 and random.randint(1,100) <= self.chance:
attacker.hp -= self.damage
#Leech_Proc drains life from the attacker on a hit
#Draining the defenders hp and giving it to the attacker
#chance is likelihood the proc will fire
#percent is percent of damage inflicted in the attack that will be given to the attacker
#percent should be very low for balance (20-30 would be very good)
class Leech_Proc(Weapon_Proc):
def __init__(self, chance, percent):
Weapon_Proc.__init__(self)
self.chance = chance
self.percent = percent
self.prefix = "Vampiric"
self.suffix = "of draining"
def attack_post(self, attacker, defender, result, damage):
if result >= 0 and random.randint(1,100) < self.chance:
attacker.heal(int(math.floor(self.percent * damage / 100)))
#Poison_Proc poisons the defender
class Poison_Proc(Weapon_Proc):
def __init__(self, chance, duration, damage):
Weapon_Proc.__init__(self)
self.chance = chance
self.duration = duration
self.damage = damage
self.prefix = "Putrid"
self.suffix = "of decay"
def attack_post(self, attacker, defender, result, damage):
if result >= 0 and random.randint(1,100) <= self.chance:
defender.add_effect(DOT_Effect(self.duration,self.damage))
if isinstance(attacker, Adventurer):
print "Your %s oozes venom on" % attacker.current_attack().name,
print defender.name + "."
else:
print "%s's" % attacker.name,
print "%s oozes venom on you! *** PoIsOnEd ***" % attacker.current_attack().name
#Stun_Proc stuns the defender for duration rounds
class Stun_Proc(Weapon_Proc):
def __init__(self, chance, duration):
Weapon_Proc.__init__(self)
self.chance = chance
self.duration = duration
self.prefix = "Dazzling"
self.suffix = "of victory"
def attack_post(self, attacker, defender, result, damage):
if defender.is_stunned():
return
if result >= 0 and random.randint(1,100) <= self.chance:
defender.add_effect(Stun_Effect(self.duration))
if isinstance(attacker, Adventurer):
print "Your %s flashes with mystical power," % attacker.current_attack().name,
print "stunning your opponent for %s rounds!" % self.duration
else:
print "You're blinded by a flash from the %s," % attacker.current_attack().name,
print "you are stunned for %s rounds!" % self.duration
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,953
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/main.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: main.py
#not sure if we need to really have a class, or just a procedural
#launching of the game, class here may just be overkill
#import statements
from Level import *
from Player import *
from CLI_Interface import *
from Weapon_Module import *
from Item_Module import *
from Armor import *
from Armor_Factory import *
from Weapon_Factory import *
from Item_Factory import *
#define main's global variables
level = None
game_name = "Labyrinth"
character_name = ""
items = Item_Factory()
wf = Weapon_Factory()
af = Armor_Factory()
def print_initial_instructions():
global game_name
f = open('labyrinth.txt')
for line in f:
print line
game_instructions = "\n\tThe point of " + game_name + " is to defeat all the"
game_instructions += "\n\tcreatures in the level and collect as much gold as"
game_instructions += "\n\tpossible. You can move from room to room to defeat"
game_instructions += "\n\tcreatures and collect gold, items, weapons, and new"
game_instructions += "\n\tarmor. If you die (loose all of your hp) you must"
game_instructions += "\n\tstart over from the beginning. You may type 'help'"
game_instructions += "\n\tat any point in the game to get a list of game "
game_instructions += "\n\tcommands. Type `vhelp *` for a verbose list."
print "Welcome to", game_name, "!"
print "Instructions"
print game_instructions
def get_user_settings():
valid_input = False
while( not valid_input ):
print "What level size would you like to play on?"
print "[1] Extra-Large (100 rooms)"
print "[2] Large (64 rooms)"
print "[3] Medium (36 rooms)"
print "[4] Medium-Small (25 rooms)"
print "[5] Small (16 rooms)"
print "[6] Extra-Small (9 rooms)"
print "[7] Tiny (4 rooms)"
level_size = raw_input(": ")
try:
level_size = int(level_size)
if( type(level_size) == int and level_size > 0 and level_size < 8):
valid_input = True
else:
print "Not valid input. Try again."
except:
print "Not a number, try again"
valid_input = False
while( not valid_input ):
print ""
print "What would you like your character name to be?"
character_name = raw_input(": ")
if( len(character_name) > 0 ):
valid_input = True
else:
print "Not valid input. Try again."
valid_input = False
while( not valid_input ):
print ""
print "What difficulty would you like to play at?"
print "[1] Extreme (25% hp)"
print "[2] Hard (50% hp)"
print "[3] Medium (75% hp)"
print "[4] Easy (100% hp)"
difficulty = raw_input(": ")
try:
difficulty = int(difficulty)
if( type(difficulty) == int and difficulty > 0 and difficulty < 5):
valid_input = True
else:
print "Not valid input. Try again."
except:
print "Not a number, try again"
return {
"level_size":level_size,
"character_name":character_name,
"difficulty":difficulty
}
def victorious(level):
return level.defeated_all_creatures()
def print_class_information():
print "Warrior:"
print " Warriors excel at melee combat, if you don't know what",
print "excel means this is the class for you"
print " Warriors receive a + 1 to Strength and Stamina"
print " Warriors receive a - 1 to Intelligence and Agility"
print ""
print "Rogue:"
print " Rogues rely on wit and fleetness of foot to survive",
print "the perils of the labyrinth"
print " Rogues receive a + 1 to Agility and Dexterity"
print " Rogues receive a - 1 to Strength and Stamina"
print ""
print "Mage:"
print " Mages are ineffective fighters, but they have access",
print "to powerful arts of mystic origin."
print " Should they live long enough to use them..."
print " Mages receive a + 2 to Intelligence"
print " Mages receive a - 1 to Strength and Dexterity"
def calc_starting_hp(stamina):
return 200 + random.randint(stamina^2, stamina*10)
def equip_potion(player):
player.potion = list()
player.add_potion(items.generate_potion_healing(1))
player.add_potion(items.generate_potion_healing(1))
return player
def equip_weapon(player):
player.weapon = list()
wpn = wf.generate_by_quality(0)
while wpn.required_strength > player.strength or wpn.required_agility > player.agility:
wpn = wf.generate_by_quality(0)
player.add_weapon(wpn)
return player
def equip_armor(player):
player.armor = list()
armor = af.generate_by_quality(0)
while armor.required_strength > player.strength:
armor = af.generate_by_quality(0)
player.add_armor(armor)
return player
def standard_equipment(player):
player = equip_potion(player)
player = equip_weapon(player)
player = equip_armor(player)
return player
def equip_mage(player):
player = standard_equipment(player)
player.add_spell(items.generate_spell_attack(2))
player.add_spell(items.generate_spell_attack(2))
player.add_spell(items.generate_spell(2))
player.add_spell(items.generate_spell(2))
player.add_spell(items.generate_spell(1))
player.add_spell(items.generate_spell(1))
player.add_spell(items.generate_spell(1))
player.add_spell(items.generate_spell(1))
wpn = wf.generate_by_type(4)
while wpn.required_intel > player.intel:
wpn = wf.generate_by_type(4, random.randint(0,1))
player.add_weapon(wpn)
return player
def equip_rogue(player):
player = standard_equipment(player)
wpn = wf.generate_by_type(1)
while wpn.required_agility > player.agility or wpn.required_strength > player.strength:
wpn = wf.generate_by_type(1,random.randint(0,1))
player.add_weapon(wpn)
player.add_spell(items.generate_spell(1))
player.add_spell(items.generate_spell(1))
player.add_potion(items.generate_potion(1))
player.add_potion(items.generate_potion(0))
return player
def equip_warrior(player):
player = standard_equipment(player)
wpn = wf.generate_by_quality(1)
while wpn.required_agility > player.agility or wpn.required_strength > player.strength:
wpn = wf.generate_by_quality(random.randint(0,1))
armor = af.generate_by_quality(1)
while armor.required_strength > player.strength:
armor = af.generate_by_quality(random.randint(0,1))
player.add_weapon(wpn)
player.add_armor(armor)
player.add_potion(items.generate_potion_healing(1))
return player
def create_character():
valid_input = False
while( not valid_input ):
print " "
print "Select a class:"
print "[1] Warrior"
print "[2] Rogue"
print "[3] Mage"
print "{i} More information"
#Shamelessly pasted code, the variable's name is stupid
isint = True
difficulty = raw_input(": ")
try:
int_input = int(difficulty)
except:
isint = False
if isint and int_input > 0 and int_input < 4:
valid_input = True
elif difficulty == "i" or difficulty == "I":
print_class_information()
else:
print "Not valid input. Try again."
char = int_input
valid_input = False
cf = Creature_Factory()
player = Adventurer(character_name,0)
roll = True
while not valid_input:
print " "
print character_name
if roll:
player = cf.generate_player_stats(player)
player.max_hp = calc_starting_hp(player.stamina)
if char == 1:
player.strength += 1
player.stamina += 1
if player.intel > 1:
player.intel -= 1
if player.agility > 1:
player.agility -= 1
elif char == 2:
player.agility += 1
player.dexterity += 1
if player.strength > 1:
player.strength -= 1
if player.stamina > 1:
player.stamina -= 1
else:
player.intel += 2
if player.strength > 1:
player.strength -= 1
if player.dexterity > 1:
player.dexterity -= 1
print "Strength: %s" % player.strength
print "Stamina: %s" % player.stamina
print "Agility: %s" % player.agility
print "Dexterity: %s" % player.dexterity
print "Intelligence: %s" % player.intel
player.hp = player.max_hp
print "Starting HP: %s" % player.max_hp
print "Would you like to keep this character?"
print "[Y]es to keep, or [N]o to roll again"
response = raw_input(": ")
roll = False
try:
if response == "Y" or response == "y":
valid_input = True
elif response == "N" or response == "n":
print ""
print "Rolling again..."
roll = True
except:
print "Really? There's only two options."
if char == 1:
player = equip_warrior(player)
elif char == 2:
player = equip_rogue(player)
else:
player = equip_mage(player)
return player
##---------------------------------------------------------
## start the game!! WOO HOO!!
##---------------------------------------------------------
#print instructions
print_initial_instructions()
#get user-settings
settings = get_user_settings()
#intialize the Level and Player
dimension = {
1: 10,
2: 8,
3: 6,
4: 5,
5: 4,
6: 3,
7: 2,
}[settings['level_size']]
level = Level(dimension)
player = create_character()
#initialize the CLI object
cli = CLI(player, level)
#start the game loop
while( not victorious(level) ):
#get the command
cur_cmd = cli.get_command()
#check if there is a creature in the room
if( level.get_current_room().creature != None ):
print "You cannot move when a creature is in the room"
else:
{
'north': level.move_north,
'east': level.move_east,
'south': level.move_south,
'west': level.move_west
}[cur_cmd[0][5:]]()
else:
print "You've won the game!"
print ""
print "Your final stats:"
print "\tHP: " + str(player.hp)
print "\tGold: " + str(player.gold)
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,954
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Proc_Factory.py
|
#Authors Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#File: Proc_Factory.py
from Proc import *
from Distributed_Random import Distributed_Random
class Proc_Factory:
def __init__(self):
self
def generate_weapon_proc(self, quality=0):
#returns a random Weapon_Proc
procs = {
1: self.generate_leech_proc,
2: self.generate_poison_proc,
3: self.generate_stun_proc,
}
if quality == 0:
#default, random quality
return procs[random.randint(1,3)](random.randint(1,3))
else:
return procs[random.randint(1,3)](quality)
def generate_armor_proc(self, quality=0):
#returns a random Armor_Proc
#only have thorn right now
if quality == 0:
return self.generate_thorn_proc(random.randint(1,3))
else:
return self.generate_thorn_proc(quality)
def generate_leech_proc(self, quality=1):
#generates a leech proc of variable quality
dist = Distributed_Random()
chance_min = 15
chance_max = 30
perc_min = 5
perc_max = 15
if quality == 2:
chance_max = 50
perc_min = 10
perc_max = 20
if quality == 3:
chance_min = 40
chance_max = 75
perc_min = 20
perc_max = 30
chance = dist.randint(chance_min, chance_max)
percent = dist.randint(perc_min, perc_max)
return Leech_Proc(chance, percent)
def generate_thorn_proc(self, quality=1):
#generates a thorn proc of variable quality
dist = Distributed_Random()
chance_min = 15
chance_max = 30
damage_min = 5
damage_max = 10
if quality == 2:
chance_max = 50
damage_min = 7
damage_max = 20
if quality == 3:
chance_min = 40
chance_max = 75
damage_max = 30
damage_min = 15
chance = dist.randint(chance_min, chance_max)
damage = dist.randint(damage_min, damage_max)
return Thorn_Proc(chance, damage)
def generate_poison_proc(self, quality=1):
#generates a poison proc of variable quality
dist = Distributed_Random()
dura_max = 4
dura_min = 1
chance_min = 15
chance_max = 30
damage_min = 3
damage_max = 10
if quality == 2:
dura_max = 6
chance_max = 50
damage_min = 5
damage_max = 15
if quality == 3:
dura_min = 3
dura_max = 8
chance_min = 40
chance_max = 75
damage_min = 10
damage_max = 20
chance = dist.randint(chance_min, chance_max)
dura = dist.randint(dura_min, dura_max)
damage = dist.randint(damage_min, damage_max)
return Poison_Proc(chance, dura, damage)
def generate_stun_proc(self, quality=1):
#returns a stun proc of variable quality
dist = Distributed_Random()
dura_max = 2
dura_min = 1
chance_min = 15
chance_max = 30
if quality == 2:
dura_max = 4
chance_max = 50
if quality == 3:
dura_max = 6
dura_min = 3
chance_min = 40
chance_max = 75
return Stun_Proc(dist.randint(chance_min, chance_max), dist.randint(dura_min, dura_max))
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,955
|
JohnMurray/Labyrinth
|
refs/heads/master
|
/Armor_Factory.py
|
#Authors: Brad Stephens, John Murray
#Project: CSC 407 - Program 3
#Due: July 19th, 2010
#File: Armor_Factory.py
from Distributed_Random import Distributed_Random
import random
from Armor import Armor
from Proc_Factory import Proc_Factory
#Armor_Factory generates random and selected pieces of armor
class Armor_Factory:
def __init__(self):
self
def generate_by_quality(self, quality):
gen = {
0: self.generate_low_quality(),
1: self.generate_medium_quality(),
2: self.generate_high_quality(),
}
armor = gen[quality]
if quality == 1 and random.randint(1,100) < 25:
p = Proc_Factory()
proc = p.generate_armor_proc(random.randint(1,2))
armor.name = proc.prefix + " " + armor.name
armor.add_proc(proc)
if quality == 2 and random.randint(1,100) < 40:
p = Proc_Factory()
proc = p.generate_armor_proc(random.randint(1,3))
armor.name = proc.prefix + " " + armor.name
armor.add_proc(proc)
return armor
def generate(self):
#generate a random piece of armor
#create a dictionary of outcomes
gen = {
0: self.generate_light_armor(),
1: self.generate_medium_armor(),
2: self.generate_heavy_armor(),
}
#how awesome are function objects? very.
return gen[self.select_armor_type()]
#Randomly select armor type
def select_armor_type(self):
rand = random.randint(1,100)
#50/30/20 Light/Medium/Heavy ratio, configurable
if rand <= 50:
return 0
elif rand <= 80:
return 1
else:
return 2
#Look up method for light materials
def generate_light_material(self):
names = [ "Cloth", "Bone", "Hide", "Leather" ]
return names[random.randint(0,3)]
#Look up method for medium materials
def generate_medium_material(self):
names = [ "Chain", "Scale", "Banded" ]
return names[random.randint(0,2)]
#Look up method for heavy materials
def generate_heavy_material(self):
names = [ "Steel", "Mithril", "Adamantium" ]
return names[random.randint(0,2)]
#Just call it plate mail and be done with it
def generate_heavy_name(self):
return self.generate_heavy_material() + ' Plate Mail'
#All medium armors just became mail
def generate_medium_name(self):
return self.generate_medium_material() + ' Mail'
#Cloth armor? whatever.
def generate_light_name(self):
return self.generate_light_material() + ' Armor'
#Generate a high quality piece of armor
#Will be a "Heavy" type armor
def generate_high_quality(self):
#generate a random high quality piece of armor
dist = Distributed_Random()
defense = dist.randint(12,17)
dr = dist.randint(12,19)
return Armor(defense, dr, self.generate_heavy_name(), 'desc')
def generate_medium_quality(self):
#generate random medium quality
return self.generate_medium_armor()
def generate_low_quality(self):
#generate low quality piece of armor
dist = Distributed_Random()
defense = dist.randint(10,17)
dr = dist.randint(0,3)
return Armor(defense, dr, self.generate_light_name(), 'desc')
#Generate a random light armor
def generate_light_armor(self):
dist = Distributed_Random()
defense = dist.randint(10,21)
dr = dist.randint(0,5)
return Armor(defense, dr, self.generate_light_name(), 'desc')
#Generate a random medium armor
def generate_medium_armor(self):
dist = Distributed_Random()
defense = dist.randint(10,19)
dr = dist.randint(8,13)
return Armor(defense, dr, self.generate_medium_name(), 'desc')
#Generate a random heavy armor
def generate_heavy_armor(self):
dist = Distributed_Random()
defense = dist.randint(10,17)
dr = dist.randint(12,19)
return Armor(defense, dr, self.generate_heavy_name(), 'desc')
|
{"/Room_Module.py": ["/Static.py", "/Player.py", "/Creature_Factory.py", "/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py"], "/Item_Factory.py": ["/Item_Module.py", "/Config.py"], "/Armor.py": ["/Item_Module.py"], "/Weapon_Factory.py": ["/Distributed_Random.py", "/Weapon_Module.py", "/Config.py", "/Proc_Factory.py"], "/Creature_Factory.py": ["/Armor_Factory.py", "/Weapon_Factory.py", "/Player.py"], "/Treasure.py": ["/Weapon_Factory.py", "/Armor_Factory.py", "/Item_Factory.py", "/Distributed_Random.py"], "/Proc_Factory.py": ["/Proc.py", "/Distributed_Random.py"], "/Armor_Factory.py": ["/Distributed_Random.py", "/Armor.py", "/Proc_Factory.py"]}
|
24,956
|
PyJan/Flask_templates
|
refs/heads/master
|
/models/test_hedgeratio.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 22:00:40 2018
@author: jan
unit test for hedgeratio model
"""
import unittest
from hedgeratio import HedgeRatio
from bokeh.plotting.figure import Figure
class HedgeRatioTestCase(unittest.TestCase):
"""
class for HedgeRatio unit test
"""
def test_simulation(self):
"""
test if simulation was run properly
"""
hedgeratio = HedgeRatio()
hedgeratio.runSimulation()
self.assertEqual(hedgeratio._sim.size, 2*hedgeratio._numobserv,
'Simulation not properly generated - wrong size.')
def test_corr(self):
"""
test that correlation is in <-1,1>
"""
hedgeratio = HedgeRatio()
hedgeratio.runSimulation()
self.assertLessEqual(hedgeratio.calculateCorr()**2, 1,
'Impossible value for correlation')
def test_scatterplot(self):
"""
test existence of scatter plot
"""
hedgeratio = HedgeRatio()
hedgeratio.runSimulation()
self.assertIsInstance(hedgeratio.createScatterPlot(), Figure)
unittest.main()
|
{"/app.py": ["/models/__init__.py"], "/models/__init__.py": ["/models/hedgeratio.py", "/models/schwartz97.py", "/models/gbm.py"]}
|
24,957
|
PyJan/Flask_templates
|
refs/heads/master
|
/app.py
|
from flask import Flask, render_template, url_for, request
from models import HedgeRatio, Schwartz97, GBM
from bokeh.embed import components
from bokeh.plotting import output_file, show
from wtforms import Form, StringField, SubmitField, FloatField, IntegerField
app = Flask(__name__)
app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176'
@app.route('/')
def main():
return render_template('main.html')
@app.route('/base')
def base():
return render_template('base.html')
@app.route('/child')
def child():
return render_template('child.html')
@app.route('/simbase')
def simbase():
return render_template('sim_base.html')
@app.route('/sim', methods=['GET', 'POST'])
def sim():
hedgeratio = HedgeRatio()
if request.method=='POST':
corr = request.form.get('corr')
spotstd = request.form.get('spotstd')
fwdstd = request.form.get('fwdstd')
numobserv = request.form.get('numobserv')
hedgeratio.updateParameters(float(corr), float(spotstd), float(fwdstd), int(numobserv))
else:
corr, spotstd, fwdstd, numobserv = hedgeratio.getParameters()
hedgeratio.runSimulation()
statspotstd, statfwdstd = hedgeratio.calculateSTDs()
statratio = hedgeratio.calculateHedgeRatio()
statcorr = hedgeratio.calculateCorr()
statlinearfit = hedgeratio.getLinearFitCoef()
stats = {
'statspotstd': statspotstd,
'statfwdstd': statfwdstd,
'statratio': statratio,
'statcorr': statcorr,
'statlinearfit': statlinearfit
}
p = hedgeratio.createScatterPlot()
p_line = hedgeratio.createHedgingPlot()
script, div = components(p)
script_line, div_line = components(p_line)
return render_template('sim.html', corr=corr, numobserv=numobserv,
spotstd=spotstd, fwdstd=fwdstd, script=script, div=div, stats=stats,
div_line=div_line, script_line=script_line)
@app.route('/schwartz97', methods=['GET','POST'])
def schwartz97():
schwartz97 = Schwartz97()
if request.method == 'POST':
alpha=float(request.form['alpha'])
dt=float(request.form['dt'])
sigma=float(request.form['sigma'])
mu=float(request.form['mu'])
S0=float(request.form['S0'])
steps=int(request.form['steps'])
numScen=int(request.form['numScen'])
schwartz97.updateParameters(alpha, dt, sigma, mu, S0, steps, numScen)
params = schwartz97.getParameters()
schwartz97.calculateScenarios()
script, div = components(schwartz97.createPlot())
return render_template('sim_schwartz97.html', params=params, script=script, div=div)
class gbmForm(Form):
mu = FloatField(label='mu', id='label')
sigma = FloatField(label='sigma', id='sigma')
S0 = FloatField(label='S0', id='S0')
dt = FloatField(label='dt', id='dt')
steps = IntegerField(label='steps', id='steps')
numScen = IntegerField(label='numScen', id='numScen')
@app.route('/gbm', methods=['GET','POST'])
def gbm():
gbm = GBM() # type: models.gbm.GBM
gbmform = gbmForm(request.form, **gbm.getParameters())
if request.method == 'POST':
gbm.updateParameters(**gbmform.data)
gbm.calculateScenarios()
script, div = components(gbm.createPlot())
return render_template('sim_gbm.html', gbmform=gbmform, script=script, div=div)
if __name__ == '__main__':
app.run(debug=True)
|
{"/app.py": ["/models/__init__.py"], "/models/__init__.py": ["/models/hedgeratio.py", "/models/schwartz97.py", "/models/gbm.py"]}
|
24,958
|
PyJan/Flask_templates
|
refs/heads/master
|
/models/gbm.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 25 19:28:54 2018
@author: jan
contains class for simulation of Geometric Brownian Motion
"""
import pandas as pd
import numpy as np
from pandas import DataFrame
from bokeh.plotting import show, figure
from bokeh.io import reset_output
from bokeh.palettes import Paired12
class GBM():
"""
container for Geometric Brownian Motion simulation
formula: dS / S = mu * dt + sigma * dZ
"""
def __init__(self, mu=0.05, sigma=0.01, S0=50, dt=0.02, steps=50, numScen=10):
"""
parameters:
mu: drift \n
sigma: volatility \n
S0: initial spot price \n
dt: time step \n
steps: number of steps \n
numScen: number of scenarios \n
"""
self._mu = mu
self._sigma = sigma
self._S0 = S0
self._dt = dt
self._steps = steps
self._numScen = numScen
self._sim = None
def calculateScenarios(self):
"""
sceate scenarios and fill self._sim with them
"""
self._sim = np.zeros((self._steps, self._numScen))
self._sim[0] = self._S0
for i in range(self._steps-1):
dZ = np.random.normal(scale=np.sqrt(self._dt), size=self._numScen)
self._sim[i+1] = ((self._mu * self._dt + self._sigma * dZ)
* self._sim[i] + self._sim[i])
columns = ['S{:03d}'.format(i+1) for i in range(self._numScen)]
self._sim = DataFrame(self._sim, columns=columns,
index=np.arange(self._steps)*self._dt)
def createPlot(self):
"""
create Bokeh plot of scenarios
"""
p = figure(width=400, height=400)
p.multi_line(xs=[self._sim.index]*self._numScen,
ys=[self._sim[col].values for col in self._sim],
line_width=2,
line_color=(Paired12*(self._numScen//12+1))[:self._numScen])
return p
def updateParameters(self, mu=None, sigma=None, S0=None, dt=None,
steps=None, numScen=None):
"""
update model parameters
"""
if mu is not None:
self._mu = mu
if sigma is not None:
self._sigma= sigma
if S0 is not None:
self._S0 = S0
if dt is not None:
self._dt = dt
if steps is not None:
self._steps = steps
if numScen is not None:
self._numScen = numScen
def getParameters(self):
"""
returns dictionary of input parameters
"""
return dict(mu = self._mu,
sigma = self._sigma,
S0 = self._S0,
dt = self._dt,
steps = self._steps,
numScen = self._numScen
)
if __name__ == '__main__':
gbm = GBM()
gbm.calculateScenarios()
reset_output()
p = gbm.createPlot()
show(p)
|
{"/app.py": ["/models/__init__.py"], "/models/__init__.py": ["/models/hedgeratio.py", "/models/schwartz97.py", "/models/gbm.py"]}
|
24,959
|
PyJan/Flask_templates
|
refs/heads/master
|
/blueprint_test/functional/myapp/views/profile.py
|
from flask import Blueprint
profile = Blueprint('profile', __name__)
@profile.route('/<username>/desk')
def desk(username):
return 'Your name is ' + username
@profile.route('/<username>/photos')
def photos(username):
return 'Photos for ' + username
|
{"/app.py": ["/models/__init__.py"], "/models/__init__.py": ["/models/hedgeratio.py", "/models/schwartz97.py", "/models/gbm.py"]}
|
24,960
|
PyJan/Flask_templates
|
refs/heads/master
|
/models/hedgeratio.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 11 21:42:09 2018
@author: jan
file containing HedgeRatio class
"""
import pandas as pd
import numpy as np
from pandas import DataFrame, Series
from bokeh.plotting import figure, output_file, show, reset_output
from sklearn import linear_model
class HedgeRatio():
"""
Implementation of hedge ratio model
Usage:
# create object
hedgeratio = HedgeRatio()
# simulate spot scenarios
hedgeratio.runSimulation()
# calculate statistics
corr = hedgeratio.calculateCorr
stds = hedgeratio.calculateSTDs
ratio = hedgeratio.calculateHedgeRatio()
# return scatter plot
p = hedgeratio.createScatterPlot()
"""
def __init__(self, rho=0.8, sigmaspot=2, sigmafwd=3, numobserv=1000):
"""
initialize with default values
"""
self._rho = rho
self._sigmaspot = sigmaspot
self._sigmafwd = sigmafwd
self._numobserv = numobserv
self._sim = pd.DataFrame()
def __str__(self):
return 'Implementation of hedge ratio model'
def __repr__(self):
return 'HedgeRatio({0}, {1}, {2}, {3})'.format(
self._rho,
self._sigmaspot,
self._sigmafwd,
self._numobserv)
def runSimulation(self):
"""
create scenario for daily spot and fwd deltas
"""
x = DataFrame(np.random.normal(size=(self._numobserv,2)),
columns=['rand1','rand2'])
self._sim['spot'] = self._sigmaspot*x['rand1']
self._sim['fwd'] = ((self._rho*x['rand1'] + np.sqrt(1-self._rho**2)*x['rand2'])
*self._sigmafwd)
def calculateCorr(self):
"""
return calculated correlation between spot and fwd
"""
return round(self._sim.corr().iloc[0,1],3)
def calculateSTDs(self):
"""
return calculated standard deviations of spot and fwd
"""
covmatrix = self._sim.cov()
return (round(np.math.sqrt(covmatrix.iloc[0,0]), 3),
round(np.math.sqrt(covmatrix.iloc[1,1]), 3))
def calculateHedgeRatio(self):
"""
return calculated hedge ratio from stats
"""
return round(self.calculateCorr()*
self.calculateSTDs()[0]
/self.calculateSTDs()[1],3)
def calculateHedgeSTD(self, hedgecoef):
"""
standard deviation of 1 hedge strategy
"""
return self._sim.mul([1,hedgecoef*(-1)]).sum(axis=1).std()
def calculateHedgeStrategies(self, granularity=np.arange(0,2.1,0.05)):
"""
Simulate hedge strategies for different hedge ratios
"""
return pd.Series(granularity, index=granularity).map(self.calculateHedgeSTD)
def createScatterPlot(self):
"""
scatter plot between spot and fwd
"""
p = figure(title='Spot delta as a function of forward delta',
x_axis_label='Forward delta', y_axis_label='Spot delta')
p.circle(self._sim['fwd'], self._sim['spot'], size=5)
p.line(self._sim['fwd'], self.calculateLinearFit()[0].flatten(),
line_width=3, color='red')
return p
def showScatterPlot(self):
"""
scatter plot visualization
"""
reset_output()
output_file('showme2.html')
show(self.createScatterPlot())
def updateParameters(self, rho=None, sigmaspot=None, sigmafwd=None, numobserv=None):
"""
update parameters of the model
"""
if rho is not None:
self._rho = rho
if sigmaspot is not None:
self._sigmaspot = sigmaspot
if sigmafwd is not None:
self._sigmafwd = sigmafwd
if numobserv is not None:
self._numobserv = numobserv
def getParameters(self):
"""
return parameters in tuple (rho, sigmaspot, sigmafwd, numobserv)
"""
return self._rho, self._sigmaspot, self._sigmafwd, self._numobserv
def calculateLinearFit(self):
"""
calculate linear fit for fwd
returns tuple prediction, slope, intercept
"""
linreg = linear_model.LinearRegression()
linreg.fit(self._sim[['fwd']].values,self._sim[['spot']].values)
return (linreg.predict(self._sim[['fwd']]),
round(linreg.coef_[0][0],3), round(linreg.intercept_[0],3))
def getLinearFitCoef(self):
"""
returns slope and intercept of linear fit
"""
return self.calculateLinearFit()[1:]
def createHedgingPlot(self):
"""
creates plot of portfolio standard deviation based on hedge ratio
"""
f = figure(x_axis_label='Hedge Ratio',
y_axis_label='Standard Deviation of Portfolio',
title='Risk of portfolio as a function of hedging ratio')
# TODO: 1 call only, approve perfomance
f.line(self.calculateHedgeStrategies().index,
self.calculateHedgeStrategies().values, line_width=5)
return f
def showHedgingPlot(self):
reset_output()
output_file('showme2.html')
show(self.createHedgingPlot())
if __name__ == '__main__':
hedgeratio = HedgeRatio()
hedgeratio.runSimulation()
#hedgeratio.sim.plot()
print(hedgeratio.calculateCorr())
print(hedgeratio.calculateSTDs())
print(hedgeratio.calculateHedgeRatio())
print(hedgeratio.calculateHedgeSTD(0.5))
#hedgeratio.calculateHedgeStrategies().plot()
p = hedgeratio.createScatterPlot()
#print(hedgeratio.calculateLinearFit())
print(hedgeratio.getLinearFitCoef())
hedgeratio.calculateHedgeStrategies()
hedgeratio.showHedgingPlot()
|
{"/app.py": ["/models/__init__.py"], "/models/__init__.py": ["/models/hedgeratio.py", "/models/schwartz97.py", "/models/gbm.py"]}
|
24,961
|
PyJan/Flask_templates
|
refs/heads/master
|
/models/__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 14 19:09:44 2018
@author: jan
"""
from .hedgeratio import HedgeRatio
from .schwartz97 import Schwartz97
from .gbm import GBM
|
{"/app.py": ["/models/__init__.py"], "/models/__init__.py": ["/models/hedgeratio.py", "/models/schwartz97.py", "/models/gbm.py"]}
|
24,962
|
PyJan/Flask_templates
|
refs/heads/master
|
/blueprint_test/functional/myapp/app.py
|
from flask import Flask
from views.profile import profile
app = Flask(__name__)
app.register_blueprint(profile)
if __name__ == '__main__':
app.run(debug=True)
|
{"/app.py": ["/models/__init__.py"], "/models/__init__.py": ["/models/hedgeratio.py", "/models/schwartz97.py", "/models/gbm.py"]}
|
24,963
|
PyJan/Flask_templates
|
refs/heads/master
|
/models/schwartz97.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 19:25:07 2018
@author: jan
modul with class Schwartz97 for mean-reverting model
"""
import pandas as pd
import numpy as np
from pandas import DataFrame, Series
from bokeh.plotting import figure, output_file, show, reset_output
from bokeh.models import ColumnDataSource
class Schwartz97():
"""
Simulation of Schwartz mean-reverting model.
"""
def __init__(self, alpha=0.05, dt=1, sigma=0.04, mu=3.2, S0=20, steps=100,
numScen=10):
"""
Input coefficient:\n
alpha - coefficient of mean reversion\n
dt - time step\n
sigma - volatility\n
mu - long-term level\n
S0 - initial price\
steps - number of steps\n
numScen - number of scenarios
"""
self._alpha = alpha
self._dt = dt
self._sigma = sigma
self._mu = mu
self._S0 = S0
self._steps = steps
self._numScen = numScen
self._sim = None
def __str__(self):
forPrint = """
Schwartz model with parameters
alpha={0}
dt={1}
sigma={2}
mu={3}
S0={4}
step={5}
numScen={6}
"""
return forPrint.format(self._alpha, self._dt, self._sigma, self._mu,
self._S0, self._steps, self._numScen)
def __repr__(self):
return ('Schwartz97(alpha={0}, dt={1}, sigma={2}, mu={3}, S0={4}, '
'steps={5}, numScen={6})'.format(self._alpha, self._dt,
self._sigma, self._mu, self._S0, self._steps, self._numScen))
def calculateScenarios(self):
"""
create scenarios according to formula
dS = alpha*(mu - ln(S))*S*dt + sigma*S*dz
"""
S = np.zeros((self._steps, self._numScen))
dz = (np.random.standard_normal((self._steps, self._numScen))
*np.sqrt(self._dt))
S[0] = self._S0
for t in range(1,self._steps):
S[t]=(S[t-1]+self._alpha*(self._mu-np.log(S[t-1]))*S[t-1]*self._dt
+self._sigma*S[t-1]*dz[t-1])
columns = ['S{:03d}'.format(x+1) for x in range(self._numScen)]
self._sim = DataFrame(S, columns=columns,
index=np.arange(self._steps)*self._dt)
def getTimeLabels(self):
"""
return x axis labels
"""
return np.array(range(self._steps))*self._dt
def createPlot(self):
"""
create Bokeh figure
"""
p = figure(x_axis_label='Time', y_axis_label='Spot Price')
source = ColumnDataSource(self._sim)
for scenario in self._sim.columns:
p.line(x='index', y=scenario, source=source, line_color='blue', line_width=2)
return p
def updateParameters(self, alpha=None, dt=None, sigma=None, mu=None,
S0=None, steps=None, numScen=None):
"""
update model parameters before you run simulation
"""
if alpha is not None:
self._alpha = alpha
if dt is not None:
self._dt = dt
if sigma is not None:
self._sigma = sigma
if mu is not None:
self._mu = mu
if S0 is not None:
self._S0 = S0
if steps is not None:
self._steps= steps
if numScen is not None:
self._numScen = numScen
def getParameters(self):
"""
return dictionary of parameters
"""
return {
'alpha': self._alpha,
'dt': self._dt,
'sigma': self._sigma,
'mu': self._mu,
'S0': self._S0,
'steps': self._steps,
'numScen': self._numScen
}
if __name__ == '__main__':
schwartz97 = Schwartz97()
schwartz97.calculateScenarios()
#schwartz97.createPyPlot()
|
{"/app.py": ["/models/__init__.py"], "/models/__init__.py": ["/models/hedgeratio.py", "/models/schwartz97.py", "/models/gbm.py"]}
|
24,966
|
ndali5/RainPoo
|
refs/heads/main
|
/Agario/main.py
|
from Agario import core, player
from Agario.bille import Bille
from Agario.creep import Creep, creep1
from Agario.player import Player
mon_joueur1 = None
creep1 = []
bille1 = None
def setup():
print("setup START------")
core.fps = 30
core.WINDOW_SIZE = [1200 , 600]
global mon_joueur1
mon_joueur1=Player()
print("Setup END---------")
def run():
for c in creep1:
c.afficher(core)
mon_joueur1.afficher(core)
if core.getMouseLeftClick() is not None:
mon_joueur1.deplacer(core.getMouseLeftClick())
if __name__ == '__main__' :
core.main(setup,run)
|
{"/Agario/main.py": ["/Agario/bille.py", "/Agario/creep.py", "/Agario/player.py"], "/Github/rain.py": ["/Github/drop.py"]}
|
24,967
|
ndali5/RainPoo
|
refs/heads/main
|
/Github/core.py
|
import inspect
import time
from typing import cast
from types import FrameType
import pygame
runfuntion = None
setupfunction = None
screen = None
fps = 60
loopLock = False
WINDOW_SIZE = [100, 100]
width = 0
height = 1
mouseclickleft=[-1,-1]
mouseclickL= False
mouseclickright=[-1,-1]
mouseclickR= False
keyPress=False
keyPressValue=None
def noLoop():
global loopLock
loopLock = True
def getMouseLeftClick():
if mouseclickL:
return mouseclickleft
def getMouseRightClick():
if mouseclickR:
return mouseclickright
def getkeyPress():
return keyPress
def getkeyPressValue():
return keyPressValue
def setup():
pygame.init()
global WINDOW_SIZE
WINDOW_SIZE
if (setupfunction is not None):
setupfunction()
global screen
screen = pygame.display.set_mode(WINDOW_SIZE)
# Set title of screen
pygame.display.set_caption("Window")
def run():
if (runfuntion is not None):
runfuntion()
def main(setupf,runf):
print(inspect.stack()[1].function)
global runfuntion
runfuntion = runf
global setupfunction
setupfunction = setupf
global mouseclickleft, mouseclickL, mouseclickright, mouseclickR,keyPress,keyPressValue
setup()
clock = pygame.time.Clock()
done = False
print("Run START-----------")
while not done:
if not loopLock :
screen.fill(0)
run()
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
elif event.type == pygame.KEYDOWN:
keyPress = True
keyPressValue = event.key
elif event.type == pygame.KEYUP:
keyPressValue = None
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
mouseclickL= True
mouseclickleft = event.pos
if event.button == 3:
mouseclickR = True
mouseclickright = event.pos
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
mouseclickL= False
mouseclickleft=None
if event.button == 3:
mouseclickR= False
mouseclickright=None
elif event.type == pygame.MOUSEMOTION:
if mouseclickL:
mouseclickleft = event.pos
if mouseclickR:
mouseclickright = event.pos
clock.tick(fps)
#print(clock.get_time())
# Go ahead and update the screen with what we 've drawn.
pygame.display.flip()
|
{"/Agario/main.py": ["/Agario/bille.py", "/Agario/creep.py", "/Agario/player.py"], "/Github/rain.py": ["/Github/drop.py"]}
|
24,968
|
ndali5/RainPoo
|
refs/heads/main
|
/Github/rain.py
|
from Github import core
from Github.drop import Drop
drops = []
def setup():
print("Setup START---------")
core.fps = 30
core.WINDOW_SIZE = [1600, 800]
for i in range(0, 1000):
drops.append(Drop(1600))
print("Setup END-----------")
def run():
print("Run")
for d in drops:
d.tomber(800)
d.afficher(core)
core.main(setup, run)
|
{"/Agario/main.py": ["/Agario/bille.py", "/Agario/creep.py", "/Agario/player.py"], "/Github/rain.py": ["/Github/drop.py"]}
|
24,969
|
ndali5/RainPoo
|
refs/heads/main
|
/Github/drop.py
|
import random
import pygame
from pygame.math import Vector2
class Drop:
def __init__(self,largeur):
self.gravity = random.randint(5, 20)
self.size = random.randint(5,20)
self.R = random.randint(0,255)
self.V = random.randint(0,255)
self.B = random.randint(0,255)
self.position = Vector2(random.randint(0,largeur), 0)
def tomber(self, taillefenetre):
self.position.y = self.position.y + self.gravity
if self.position.y > taillefenetre:
self.raz()
def raz(self):
self.position.y = 0
def afficher(self,core):
pygame.draw.line(core.screen, (self.R, self.V, self.B), (self.position.x, self.position.y), (self.position.x, self.position.y + 10), 1)
|
{"/Agario/main.py": ["/Agario/bille.py", "/Agario/creep.py", "/Agario/player.py"], "/Github/rain.py": ["/Github/drop.py"]}
|
24,970
|
ndali5/RainPoo
|
refs/heads/main
|
/Agario/player.py
|
import pygame
from pygame.math import Vector3, Vector2
class Player:
def __init__ (self):
self.taille = 50
self.forme = "rond"
self.direction = Vector2(0,0)
self.position = Vector2(150,150)
self.couleur = Vector3(255,0,0)
def manger (self):
pass
def mourir (self):
pass
def deplacer (self,position):
self.position.x = position[0]
self.position.y = position[1]
pass
def afficher (self,core):
if self.forme == "rond":
pygame.draw.circle(core.screen,(int(self.couleur.x),int(self.couleur.y),int(self.couleur.z)),
(int(self.position.x),int(self.position.y)),self.taille)
pass
|
{"/Agario/main.py": ["/Agario/bille.py", "/Agario/creep.py", "/Agario/player.py"], "/Github/rain.py": ["/Github/drop.py"]}
|
24,971
|
ndali5/RainPoo
|
refs/heads/main
|
/Agario/core.py
|
import inspect
import time
from typing import cast
from types import FrameType
import pygame
runfuntion = None
setupfunction = None
screen = None
fps = 60
loopLock = False
WINDOW_SIZE = [100, 100]
width = 0
height = 1
mouseclickleft=[-1,-1]
mouseclickL= False
mouseclickright=[-1,-1]
mouseclickR= False
keyPress=False
keyPressValue=None
def noLoop():
global loopLock
loopLock = True
def getMouseLeftClick():
if mouseclickL:
return mouseclickleft
def getMouseRightClick():
if mouseclickR:
return mouseclickright
def getkeyPress():
return keyPress
def getkeyPressValue():
return keyPressValue
def setup():
pygame.init()
global WINDOW_SIZE
WINDOW_SIZE
if (setupfunction is not None):
setupfunction()
global screen
screen = pygame.display.set_mode(WINDOW_SIZE)
# Set title of screen
pygame.display.set_caption("Window")
def run():
if (runfuntion is not None):
runfuntion()
def main(setupf,runf):
print(inspect.stack()[1].function)
global runfuntion
runfuntion = runf
global setupfunction
setupfunction = setupf
global mouseclickleft, mouseclickL, mouseclickright, mouseclickR,keyPress,keyPressValue
setup()
clock = pygame.time.Clock()
done = False
print("Run START-----------")
while not done:
if not loopLock :
screen.fill(0)
run()
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
elif event.type == pygame.KEYDOWN:
keyPress = True
keyPressValue = event.key
elif event.type == pygame.KEYUP:
keyPressValue = None
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
mouseclickL= True
mouseclickleft = event.pos
if event.button == 3:
mouseclickR = True
mouseclickright = event.pos
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
mouseclickL= False
mouseclickleft=None
if event.button == 3:
mouseclickR= False
mouseclickright=None
elif event.type == pygame.MOUSEMOTION:
if mouseclickL:
mouseclickleft = event.pos
if mouseclickR:
mouseclickright = event.pos
clock.tick(fps)
#print(clock.get_time())
# Go ahead and update the screen with what we 've drawn.
pygame.display.flip()
|
{"/Agario/main.py": ["/Agario/bille.py", "/Agario/creep.py", "/Agario/player.py"], "/Github/rain.py": ["/Github/drop.py"]}
|
24,972
|
ndali5/RainPoo
|
refs/heads/main
|
/Agario/bille.py
|
from pygame.math import Vector2, Vector3
class Bille:
def __init__(self):
self.taille = 2
self.vitesse = 2
self.direction = Vector2()
self.position = Vector2()
self.couleur = Vector3()
def suivre(self):
pass
def mourir(self):
pass
def manger(self):
pass
def afficher(self):
pass
|
{"/Agario/main.py": ["/Agario/bille.py", "/Agario/creep.py", "/Agario/player.py"], "/Github/rain.py": ["/Github/drop.py"]}
|
24,973
|
ndali5/RainPoo
|
refs/heads/main
|
/Github/piApproximation.py
|
import random
import pygame
from pygame.rect import Rect
import core
def setup():
print("Setup START---------")
core.fps = 1
core.WINDOW_SIZE = [400, 400]
print("Setup END-----------")
def run():
pygame.draw.circle(core.screen,(255, 255, 255),(200,200),100,1)
pygame.draw.rect(core.screen,(0, 255, 0),Rect((100, 100), (200, 200)),1)
count = 0
for i in range(0,100000):
x = random.uniform(100, 300)
y = random.uniform(100, 300)
dist = (200-x)*(200-x)+(200-y)*(200-y)
if dist < 100*100 :
pygame.draw.circle(core.screen, (0, 0, 255), (int(x), int(y)), 2, 1)
count+=1
else :
pygame.draw.circle(core.screen, (255, 0, 0), (int(x), int(y)), 2, 1)
pi = float(4 * count/100000.0)
print("PI : ")
print(pi)
core.noLoop()
core.main(setup,run)
|
{"/Agario/main.py": ["/Agario/bille.py", "/Agario/creep.py", "/Agario/player.py"], "/Github/rain.py": ["/Github/drop.py"]}
|
24,974
|
ndali5/RainPoo
|
refs/heads/main
|
/Agario/creep.py
|
import pygame
from pygame.math import Vector2
from Agario import core
creep1 = []
class Creep:
def __init__ (self) :
self.taille = 5
self.position = Vector2()
def mourir(self):
pass
def afficher(self):
for i in range(0, 1000):
drops.append(Drop(1600))
pygame.draw.circle(core.screen, (int(self.couleur.x), int(self.couleur.y), int(self.couleur.z)),
(int(self.position.x), int(self.position.y)), self.taille)
pass
|
{"/Agario/main.py": ["/Agario/bille.py", "/Agario/creep.py", "/Agario/player.py"], "/Github/rain.py": ["/Github/drop.py"]}
|
24,977
|
jackw01/led-control
|
refs/heads/master
|
/ledcontrol/ledcontroller.py
|
# led-control WS2812B LED Controller Server
# Copyright 2021 jackw01. Released under the MIT License (see LICENSE for details).
import atexit
import serial
import numpy as np
import itertools
import socket
from enum import Enum
import ledcontrol.animationfunctions as animfunctions
import ledcontrol.driver as driver
import ledcontrol.utils as utils
TargetMode = Enum('TargetMode', ['serial', 'udp'])
class LEDController:
def __init__(self,
led_count,
led_pin,
led_data_rate,
led_dma_channel,
led_pixel_order,
serial_port):
if driver.is_raspberrypi():
# This is bad but it's the only way
px_order = driver.WS2811_STRIP_GRB
if led_pixel_order == 'RGB':
px_order = driver.WS2811_STRIP_RGB
elif led_pixel_order == 'RBG':
px_order = driver.WS2811_STRIP_RBG
elif led_pixel_order == 'GRB':
px_order = driver.WS2811_STRIP_GRB
elif led_pixel_order == 'GBR':
px_order = driver.WS2811_STRIP_GBR
elif led_pixel_order == 'BRG':
px_order = driver.WS2811_STRIP_BRG
elif led_pixel_order == 'BGR':
px_order = driver.WS2811_STRIP_BGR
elif led_pixel_order == 'RGBW':
px_order = driver.SK6812_STRIP_RGBW
elif led_pixel_order == 'RBGW':
px_order = driver.SK6812_STRIP_RBGW
elif led_pixel_order == 'GRBW':
px_order = driver.SK6812_STRIP_GRBW
elif led_pixel_order == 'GBRW':
px_order = driver.SK6812_STRIP_GBRW
elif led_pixel_order == 'BRGW':
px_order = driver.SK6812_STRIP_BRGW
elif led_pixel_order == 'BGRW':
px_order = driver.SK6812_STRIP_BGRW
self._has_white = 1 if 'W' in led_pixel_order else 0
self._count = led_count
# Create ws2811_t structure and fill in parameters
self._leds = driver.new_ws2811_t()
# Initialize the channels to zero
for i in range(2):
chan = driver.ws2811_channel_get(self._leds, i)
driver.ws2811_channel_t_count_set(chan, 0)
driver.ws2811_channel_t_gpionum_set(chan, 0)
driver.ws2811_channel_t_invert_set(chan, 0)
driver.ws2811_channel_t_brightness_set(chan, 0)
# Initialize the channel in use
self._channel = driver.ws2811_channel_get(self._leds, 0) # default
driver.ws2811_channel_t_gamma_set(self._channel, list(range(256)))
driver.ws2811_channel_t_count_set(self._channel, led_count)
driver.ws2811_channel_t_gpionum_set(self._channel, led_pin)
driver.ws2811_channel_t_invert_set(self._channel, 0) # 1 if true
driver.ws2811_channel_t_brightness_set(self._channel, 255)
driver.ws2811_channel_t_strip_type_set(self._channel, px_order)
# Initialize the controller
driver.ws2811_t_freq_set(self._leds, led_data_rate)
driver.ws2811_t_dmanum_set(self._leds, led_dma_channel)
# Substitute for __del__, traps an exit condition and cleans up properly
atexit.register(self._cleanup)
# Begin
resp = driver.ws2811_init(self._leds)
if resp != 0:
str_resp = driver.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_init failed with code {0} ({1})'.format(resp, str_resp))
else:
self._where_hue = np.zeros((led_count * 3,),dtype=bool)
self._where_hue[0::3] = True
self._target_mode = TargetMode.udp
if self._target_mode == TargetMode.serial:
self._serial = serial.Serial(serial_port, 115200, timeout=0.01, write_timeout=0)
elif self._target_mode == TargetMode.udp:
self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._udp_target = "lcpico-0e3062"
self._udp_port = 8888
def _cleanup(self):
# Clean up memory used by the library when not needed anymore
if driver.is_raspberrypi() and self._leds is not None:
driver.delete_ws2811_t(self._leds)
self._leds = None
self._channel = None
def set_range(self, pixels, start, end, correction, saturation, brightness, color_mode):
if driver.is_raspberrypi():
if color_mode == animfunctions.ColorMode.hsv:
driver.ws2811_hsv_render_range_float(self._channel, pixels, start, end,
correction, saturation, brightness, 1.0,
self._has_white)
else:
driver.ws2811_rgb_render_range_float(self._channel, pixels, start, end,
correction, saturation, brightness, 1.0,
self._has_white)
else:
data = np.fromiter(itertools.chain.from_iterable(pixels), np.float32)
if color_mode == animfunctions.ColorMode.hsv:
np.fmod(data, 1.0, where=self._where_hue[0:(end - start) * 3], out=data)
data = data * 255.0
else:
data = data * 255.0
data = np.clip(data, 0.0, 255.0)
data = data.astype(np.uint8)
packet = (b'\x00'
+ (b'\x02' if color_mode == animfunctions.ColorMode.hsv else b'\x01')
+ int((end - start) * 3 + 13).to_bytes(2, 'big')
+ correction.to_bytes(3, 'big')
+ int(saturation * 255).to_bytes(1, 'big')
+ int(brightness * 255).to_bytes(1, 'big')
+ start.to_bytes(2, 'big')
+ end.to_bytes(2, 'big')
+ data.tobytes())
self._send(packet)
def show_calibration_color(self, count, correction, brightness):
if driver.is_raspberrypi():
driver.ws2811_rgb_render_calibration(self._leds, self._channel, count,
correction, brightness)
else:
packet = (b'\x00\x00\x00\x08'
+ correction.to_bytes(3, 'big')
+ int(brightness * 255).to_bytes(1, 'big'))
self._send(packet)
def render(self):
if driver.is_raspberrypi():
driver.ws2811_render(self._leds)
else:
packet = b'\x00\x03\x00\x05\x00'
self._send(packet)
def _send(self, packet):
if self._target_mode == TargetMode.serial:
self._serial.write(packet)
elif self._target_mode == TargetMode.udp:
try:
self._socket.sendto(packet, (self._udp_target, self._udp_port))
except:
pass
|
{"/ledcontrol/ledcontroller.py": ["/ledcontrol/animationfunctions.py", "/ledcontrol/driver/__init__.py", "/ledcontrol/utils.py"], "/ledcontrol/animationfunctions.py": ["/ledcontrol/driver/__init__.py", "/ledcontrol/utils.py"], "/ledcontrol/app.py": ["/ledcontrol/animationcontroller.py", "/ledcontrol/ledcontroller.py", "/ledcontrol/homekit.py", "/ledcontrol/pixelmappings.py", "/ledcontrol/animationfunctions.py", "/ledcontrol/utils.py"], "/ledcontrol/driver/__init__.py": ["/ledcontrol/driver/driver_non_raspberry_pi.py"], "/renderpreviews.py": ["/ledcontrol/animationcontroller.py", "/ledcontrol/animationfunctions.py", "/ledcontrol/pixelmappings.py", "/ledcontrol/driver/__init__.py", "/ledcontrol/utils.py"], "/ledcontrol/animationcontroller.py": ["/ledcontrol/intervaltimer.py", "/ledcontrol/animationfunctions.py", "/ledcontrol/driver/__init__.py", "/ledcontrol/utils.py"], "/ledcontrol/__init__.py": ["/ledcontrol/app.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.