Remove the CLI code from the Neutron client.

This project no longer provides CLI support. All code has been
removed. Please use openstack CLI instead

This patch removes entry point for neutron CLI too, bash completion
script and CLI related functional and unit tests but it
still keeps neutronclient/neutron/v2_0 module as this is used by e.g.
Nova.

Co-Authored-By: Slawek Kaplonski <skaplons@redhat.com>

Closes-Bug: #2003861
Change-Id: I5b6c735d1ff931d7991a42b262e7faa47b75edeb
This commit is contained in:
Slawek Kaplonski 2023-04-11 13:12:45 +02:00
parent 3071dfbd0f
commit 52653c95e0
93 changed files with 22 additions and 15350 deletions

View File

@ -7,12 +7,6 @@
- lib-forward-testing-python3 - lib-forward-testing-python3
- release-notes-jobs-python3 - release-notes-jobs-python3
- openstackclient-plugin-jobs - openstackclient-plugin-jobs
check:
jobs:
- neutronclient-functional
gate:
jobs:
- neutronclient-functional
experimental: experimental:
jobs: jobs:
- neutronclient-grenade-neutron-lib: - neutronclient-grenade-neutron-lib:
@ -20,52 +14,6 @@
- ^(test-|)requirements.txt$ - ^(test-|)requirements.txt$
- ^setup.cfg$ - ^setup.cfg$
- job:
name: neutronclient-functional
parent: devstack-tox-functional
irrelevant-files:
- ^.*\.rst$
- ^doc/.*$
- ^releasenotes/.*$
required-projects:
- openstack/python-neutronclient
- openstack/neutron
- openstack/neutron-vpnaas
vars:
tox_envlist: functional
devstack_services:
# NOTE: neutronclient.tests.functional.base.ClientTestBase does not
# support HTTPS endpoints now, so tls-proxy needs to be disabled.
tls-proxy: false
# Disable OVN services
br-ex-tcpdump: false
br-int-flows: false
ovn-controller: false
ovn-northd: false
ovs-vswitchd: false
ovsdb-server: false
q-ovn-metadata-agent: false
# Neutron services
q-agt: true
q-dhcp: true
q-l3: true
q-meta: true
neutron-network-segment-range: true
neutron-segments: true
q-metering: true
q-qos: true
neutron-tag-ports-during-bulk-creation: true
neutron-conntrack-helper: true
devstack_localrc:
USE_PYTHON3: true
LIBS_FROM_GIT: python-neutronclient
Q_AGENT: openvswitch
Q_ML2_TENANT_NETWORK_TYPE: vxlan
Q_ML2_PLUGIN_MECHANISM_DRIVERS: openvswitch
devstack_plugins:
neutron: https://opendev.org/openstack/neutron
neutron-vpnaas: https://opendev.org/openstack/neutron-vpnaas
- job: - job:
name: neutronclient-grenade-neutron-lib name: neutronclient-grenade-neutron-lib
parent: grenade parent: grenade

View File

@ -15,8 +15,7 @@ Python bindings to the Neutron API
:alt: Latest Version :alt: Latest Version
This is a client library for Neutron built on the Neutron API. It This is a client library for Neutron built on the Neutron API. It
provides a Python API (the ``neutronclient`` module) and a command-line tool provides a Python API (the ``neutronclient`` module).
(``neutron``).
* License: Apache License, Version 2.0 * License: Apache License, Version 2.0
* `PyPi`_ - package installation * `PyPi`_ - package installation

View File

@ -24,10 +24,9 @@
Using CLI Using CLI
========= =========
There are two CLIs which support the Networking API: There is `OpenStackClient (OSC)
`OpenStackClient (OSC)
<https://docs.openstack.org/python-openstackclient/latest/>`__ <https://docs.openstack.org/python-openstackclient/latest/>`__
and :doc:`neutron CLI <neutron>` (deprecated). which support the Networking API
OpenStackClient OpenStackClient
--------------- ---------------
@ -49,15 +48,8 @@ neutron CLI
.. warning:: .. warning::
neutron CLI is now deprecated and will be removed in the future. neutron CLI is removed. Use openstack CLI instead. See `openstack CLI command list
Use openstack CLI instead. See `openstack CLI command list
<https://docs.openstack.org/python-openstackclient/latest/cli/command-list.html>`__ <https://docs.openstack.org/python-openstackclient/latest/cli/command-list.html>`__
and :doc:`its extensions for advanced networking services <osc_plugins>`. and :doc:`its extensions for advanced networking services <osc_plugins>`.
The command mapping from neutron CLI to openstack CLI is available The command mapping from neutron CLI to openstack CLI is available
`here <https://docs.openstack.org/python-openstackclient/latest/cli/decoder.html#neutron-cli>`__. `here <https://docs.openstack.org/python-openstackclient/latest/cli/decoder.html#neutron-cli>`__.
.. toctree::
:maxdepth: 2
neutron CLI guide <neutron>
neutron CLI reference <neutron-reference>

View File

@ -1,48 +0,0 @@
..
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.
Convention for heading levels in Neutron devref:
======= Heading 0 (reserved for the title in a document)
------- Heading 1
~~~~~~~ Heading 2
+++++++ Heading 3
''''''' Heading 4
(Avoid deeper levels because they do not render well.)
=====================
neutron CLI reference
=====================
.. warning::
neutron CLI is now deprecated and will be removed in the future.
Use openstack CLI instead. See `openstack CLI command list
<https://docs.openstack.org/python-openstackclient/latest/cli/command-list.html>`__
and :doc:`its extensions for advanced networking services <osc_plugins>`.
The command mapping from neutron CLI to openstack CLI is available
`here <https://docs.openstack.org/python-openstackclient/latest/cli/decoder.html#neutron-cli>`__.
neutron usage
-------------
.. autoprogram-cliff:: neutronclient.shell.NeutronShell
:application: neutron
:arguments: 2.0
neutron API v2.0 commands
-------------------------
.. autoprogram-cliff:: neutron.cli.v2
:application: neutron

View File

@ -1,412 +0,0 @@
..
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.
Convention for heading levels in Neutron devref:
======= Heading 0 (reserved for the title in a document)
------- Heading 1
~~~~~~~ Heading 2
+++++++ Heading 3
''''''' Heading 4
(Avoid deeper levels because they do not render well.)
Using neutron CLI
=================
The **neutron** shell utility interacts with OpenStack Networking API from the
command-line. It supports the entire features of OpenStack Networking API.
.. warning::
neutron CLI is now deprecated and will be removed in the future.
Use openstack CLI instead. See `openstack CLI command list
<https://docs.openstack.org/python-openstackclient/latest/cli/command-list.html>`__
and :doc:`its extensions for advanced networking services <osc_plugins>`.
The command mapping from neutron CLI to openstack CLI is available
`here <https://docs.openstack.org/python-openstackclient/latest/cli/decoder.html#neutron-cli>`__.
Basic Usage
-----------
In order to use the CLI, you must provide your OpenStack username, password,
project, domain information for both user and project, and auth endpoint. Use
the corresponding configuration options (``--os-username``, ``--os-password``,
``--os-project-name``, ``--os-user-domain-id``, ``os-project-domain-id``, and
``--os-auth-url``), but it is easier to set them in environment variables.
.. code-block:: shell
export OS_USERNAME=user
export OS_PASSWORD=pass
export OS_PROJECT_NAME=project
export OS_USER_DOMAIN_ID=default
export OS_PROJECT_DOMAIN_ID=default
export OS_AUTH_URL=http://auth.example.com:5000/v3
If you are using Identity v2.0 API (DEPRECATED), you don't need to pass domain
information.
.. code-block:: shell
export OS_USERNAME=user
export OS_PASSWORD=pass
export OS_TENANT_NAME=tenant
export OS_AUTH_URL=http://auth.example.com:5000/v2.0
Once you've configured your authentication parameters, you can run **neutron**
commands. All commands take the form of:
.. code-block:: none
neutron <command> [arguments...]
Run **neutron help** to get a full list of all possible commands, and run
**neutron help <command>** to get detailed help for that command.
Using with os-client-config
~~~~~~~~~~~~~~~~~~~~~~~~~~~
`os-client-config <https://docs.openstack.org/os-client-config/latest/>`_
provides more convenient way to manage a collection of client configurations
and you can easily switch multiple OpenStack-based configurations.
To use os-client-config, you first need to prepare
``~/.config/openstack/clouds.yaml`` like the following.
.. code-block:: yaml
clouds:
devstack:
auth:
auth_url: http://auth.example.com:5000
password: your-secret
project_domain_id: default
project_name: demo
user_domain_id: default
username: demo
identity_api_version: '3'
region_name: RegionOne
devstack-admin:
auth:
auth_url: http://auth.example.com:35357
password: another-secret
project_domain_id: default
project_name: admin
user_domain_id: default
username: admin
identity_api_version: '3'
region_name: RegionOne
Then, you need to specify a configuration name defined in the above clouds.yaml.
.. code-block:: shell
export OS_CLOUD=devstack
For more detail information, see the
`os-client-config <https://docs.openstack.org/os-client-config/latest/>`_
documentation.
Using with keystone token
~~~~~~~~~~~~~~~~~~~~~~~~~
The command-line tool will attempt to re-authenticate using your provided
credentials for every request. You can override this behavior by manually
supplying an auth token using ``--os-url`` and ``--os-auth-token``. You can
alternatively set these environment variables.
.. code-block:: shell
export OS_URL=http://neutron.example.org:9696/
export OS_TOKEN=3bcc3d3a03f44e3d8377f9247b0ad155
Using noauth mode
~~~~~~~~~~~~~~~~~
If neutron server does not require authentication, besides these two arguments
or environment variables (We can use any value as token.), we need manually
supply ``--os-auth-strategy`` or set the environment variable.
.. code-block:: shell
export OS_AUTH_STRATEGY=noauth
Display options
---------------
Filtering
~~~~~~~~~
Neutron API supports filtering in the listing operation.
**neutron** CLI supports this feature too.
To specify a filter in ``*-list`` command, you need to pass a pair of an
attribute name and an expected value with the format of ``--<attribute> <value>``.
The example below retrieves ports owned by compute instances.
.. code-block:: console
$ neutron port-list --device_owner network:dhcp
+--------------------------------------+------+-------------------+-------------------------------------------------------------------------------------------------------------+
| id | name | mac_address | fixed_ips |
+--------------------------------------+------+-------------------+-------------------------------------------------------------------------------------------------------------+
| 8953d683-29ad-4be3-b73f-060727c7849b | | fa:16:3e:4b:9e:0a | {"subnet_id": "6b832dfe-f271-443c-abad-629961414a73", "ip_address": "10.0.0.2"} |
| | | | {"subnet_id": "cdcc616b-0cff-482f-96f5-06fc63d21247", "ip_address": "fd12:877c:1d66:0:f816:3eff:fe4b:9e0a"} |
+--------------------------------------+------+-------------------+-------------------------------------------------------------------------------------------------------------+
You can also specify multiple filters.
The example below retrieves security group rules applied to IPv4 traffic
which belongs to a security group bfa493f9-2b03-46d2-8399-b9b038a53bc1.
.. code-block:: console
$ neutron security-group-rule-list --security-group-id bfa493f9-2b03-46d2-8399-b9b038a53bc1 --ethertype IPv4
+--------------------------------------+----------------+-----------+-----------+---------------+-----------------+
| id | security_group | direction | ethertype | protocol/port | remote |
+--------------------------------------+----------------+-----------+-----------+---------------+-----------------+
| 65489805-0400-4bce-9bd9-16a81952263c | default | egress | IPv4 | any | any |
| 9429f336-4947-4643-bbd9-24528cc65648 | default | ingress | IPv4 | any | default (group) |
+--------------------------------------+----------------+-----------+-----------+---------------+-----------------+
.. note::
Looking up UUID from name is not supported when specifying a filter.
You need to use UUID to specify a specific resource.
.. note::
Filtering for dictionary or list attributes is not supported.
Changing displayed columns
~~~~~~~~~~~~~~~~~~~~~~~~~~
If you want displayed columns in a list operation, ``-c`` option can be used.
``-c`` can be specified multiple times and the column order will be same as
the order of ``-c`` options.
.. code-block:: console
$ neutron port-list -c id -c device_owner -c fixed_ips
+--------------------------------------+--------------------------+-------------------------------------------------------------------------------------------------------------+
| id | device_owner | fixed_ips |
+--------------------------------------+--------------------------+-------------------------------------------------------------------------------------------------------------+
| 41ca1b9b-4bbd-4aa8-bcaa-31d3d5704205 | network:router_interface | {"subnet_id": "6b832dfe-f271-443c-abad-629961414a73", "ip_address": "10.0.0.1"} |
| 8953d683-29ad-4be3-b73f-060727c7849b | network:dhcp | {"subnet_id": "6b832dfe-f271-443c-abad-629961414a73", "ip_address": "10.0.0.2"} |
| | | {"subnet_id": "cdcc616b-0cff-482f-96f5-06fc63d21247", "ip_address": "fd12:877c:1d66:0:f816:3eff:fe4b:9e0a"} |
| a9da29f8-4504-4526-a5ce-cd3624fbd173 | neutron:LOADBALANCER | {"subnet_id": "6b832dfe-f271-443c-abad-629961414a73", "ip_address": "10.0.0.3"} |
| | | {"subnet_id": "cdcc616b-0cff-482f-96f5-06fc63d21247", "ip_address": "fd12:877c:1d66:0:f816:3eff:feb1:ab71"} |
| d6a1ff96-0a99-416f-a4d6-65d9614cf64e | compute:nova | {"subnet_id": "6b832dfe-f271-443c-abad-629961414a73", "ip_address": "10.0.0.4"} |
| | | {"subnet_id": "cdcc616b-0cff-482f-96f5-06fc63d21247", "ip_address": "fd12:877c:1d66:0:f816:3eff:fe2c:348e"} |
| f4789225-26d0-409f-8047-82d2c7a87a95 | network:router_interface | {"subnet_id": "cdcc616b-0cff-482f-96f5-06fc63d21247", "ip_address": "fd12:877c:1d66::1"} |
+--------------------------------------+--------------------------+-------------------------------------------------------------------------------------------------------------+
.. _cli_extra_arguments:
Extra arguments for create/update operation
-------------------------------------------
**neutron** CLI has a mechanism called the *extra arguments* for ``*-create``
and ``*-update`` commands. It allows users to specify a set of *unknown
options* which are not defined as options and not shown in the help text.
**Unknown options MUST be placed at the end of the command line.**
*unknown options* will be directly passed to the API layer. By this mechanism,
you can pass an attribute which is not defined in the upstream **neutron**
CLI. For example, when you are developing a new feature which add a new
attribute to an existing resource, it is useful because we can test your
feature without changing the existing neutron CLI.
For example, if you run the following command::
neutron resource-update <ID> --key1 value1 --key2 value2
where ``resource`` is some resource name and ``--key1`` and ``--key2`` are
unknown options, then the following JSON will be sent to the neutron API::
PUT /v2.0/resources/<ID>
{
"resource": {
"key2": "value2",
"key1": "value1"
}
}
Key interpretation
~~~~~~~~~~~~~~~~~~
This means an option name (``--key1`` in this case) must be one of valid
resources of a corresponding resource. An option name ``--foo_bar`` is
recognized as an attribute name ``foo_bar``. ``--foo-bar`` is also interpreted
as an attribute name ``foo_bar``.
Value interpretation
~~~~~~~~~~~~~~~~~~~~
By default, if the number of values is 1, the option value is interpreted as a
string and is passed to the API layer as specified in a command-line.
If the number of values is greater than 1, the option value is interpreted as a
list and the result in the API layer will be same as when specifying a list as
described below.
neutron resource-update <ID> --key1 val1 val2 val3 --key2 val4
In the above example, a value of ``key1`` is interpreted as
``["val1", "val2", "val3"]`` and a value of ``key2`` is interpreted
as ``val4``.
The extra argument mechanism supports more complex value like a list or a dict.
Specify a list value
++++++++++++++++++++
A command-line::
neutron resource-update <ID> --key list=true val1 val2 val3
will send the following in the API layer::
{
"key": [
"val1",
"val2",
"val3"
]
}
.. note::
If you want to specify a list value, it is recommended to specify
``list=true``. When ``list=true`` is specified, specified values are
interpreted as a list even regardless of the number of values.
If ``list=true`` is not specified, specified values are interpreted
depends on the number of values how. If the number of values is more than 2,
the specified values are interpreted as a list. If 1, the value
is interpreted as a string.
Specify a dict value
++++++++++++++++++++
A command-line::
neutron resource-update <ID> --key type=dict key1=val1,key2=val2,key3=val3
will send the following in the API layer::
{
"key": {
"key1": "val1",
"key2": "val2",
"key3": "val3"
}
}
.. note::
``type=bool True/False`` and ``type=int 10`` are also supported.
Specify a list of dicts
+++++++++++++++++++++++
A command-line::
neutron resource-update <ID> --key type=dict list=true key1=val1 key2=val2 key3=val3
will send the following in the API layer::
{
"key": [
{"key1": "val1"},
{"key2": "val2"},
{"key3": "val3"}
]
}
Passing None as a value
~~~~~~~~~~~~~~~~~~~~~~~
There is a case where we would like to pass ``None`` (``null`` in JSON)
in the API layer. To do this::
neutron resource-update <ID> --key action=clear
The following body will be in the API layer::
{"key": null}
.. note::
If ``action=clear`` is specified, ``list=true`` or ``type=dict`` is ignored.
It means when ``action=clear`` is specified ``None`` is always sent.
Debugging
---------
Display API-level communication
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``-v`` (or ``--verbose``, ``--debug``) option displays a detail interaction
with your neutron server. It is useful to debug what happens in the API level.
Here is an sample output of ``net-show`` command.
The first line show what parameters are recognized by neutronclient.
It is sometimes useful to check if command-line parameters you specify are recognized properly.
.. code-block:: console
$ neutron -v net-show mynetwork
DEBUG: neutronclient.neutron.v2_0.network.ShowNetwork get_data(Namespace(columns=[], fields=[], formatter='table', id=u'mynetwork', max_width=0, noindent=False, prefix='', request_format='json', show_details=False, variables=[]))
Next, neutronclient sends an authentication request to keystone to get a token
which is used in further operations.
.. code-block:: console
DEBUG: keystoneauth.session REQ: curl -g -i -X GET http://172.16.18.47:5000 -H "Accept: application/json" -H "User-Agent: keystoneauth1"
DEBUG: keystoneauth.session RESP: [300] Content-Length: 593 Vary: X-Auth-Token Keep-Alive: timeout=5, max=100 Server: Apache/2.4.7 (Ubuntu) Connection: Keep-Alive Date: Fri, 27 Nov 2015 20:10:54 GMT Content-Type: application/json
RESP BODY: {"versions": {"values": [{"status": "stable", "updated": "2015-03-30T00:00:00Z", "media-types": [{"base": "application/json", "type": "application/vnd.openstack.identity-v3+json"}], "id": "v3.4", "links": [{"href": "http://172.16.18.47:5000/v3/", "rel": "self"}]}, {"status": "stable", "updated": "2014-04-17T00:00:00Z", "media-types": [{"base": "application/json", "type": "application/vnd.openstack.identity-v2.0+json"}], "id": "v2.0", "links": [{"href": "http://172.16.18.47:5000/v2.0/", "rel": "self"}, {"href": "http://docs.openstack.org/", "type": "text/html", "rel": "describedby"}]}]}}
DEBUG: keystoneauth.identity.v3.base Making authentication request to http://172.16.18.47:5000/v3/auth/tokens
Neutronclient looks up a network ID corresponding to a given network name.
.. code-block:: console
DEBUG: keystoneauth.session REQ: curl -g -i -X GET http://172.16.18.47:9696/v2.0/networks.json?fields=id&name=mynetwork -H "User-Agent: python-neutronclient" -H "Accept: application/json" -H "X-Auth-Token: {SHA1}39300e7398d53a02afd183f13cb6afaef95ec4e5"
DEBUG: keystoneauth.session RESP: [200] Date: Fri, 27 Nov 2015 20:10:55 GMT Connection: keep-alive Content-Type: application/json; charset=UTF-8 Content-Length: 62 X-Openstack-Request-Id: req-ccebf6e4-4f52-4874-a1ab-5499abcba378
RESP BODY: {"networks": [{"id": "3698d3c7-d581-443e-bf86-53c4e3a738f7"}]}
Finally, neutronclient retrieves a detail of a given network using the resolved ID.
.. code-block:: console
DEBUG: keystoneauth.session REQ: curl -g -i -X GET http://172.16.18.47:9696/v2.0/networks/3698d3c7-d581-443e-bf86-53c4e3a738f7.json -H "User-Agent: python-neutronclient" -H "Accept: application/json" -H "X-Auth-Token: {SHA1}39300e7398d53a02afd183f13cb6afaef95ec4e5"
DEBUG: keystoneauth.session RESP: [200] Date: Fri, 27 Nov 2015 20:10:55 GMT Connection: keep-alive Content-Type: application/json; charset=UTF-8 Content-Length: 272 X-Openstack-Request-Id: req-261add00-d6d3-4ea7-becc-105b60ac7369
RESP BODY: {"network": {"status": "ACTIVE", "subnets": [], "name": "mynetwork", "admin_state_up": true, "tenant_id": "8f0ebf767043483a987736c8c684178d", "mtu": 0, "router:external": false, "shared": false, "port_security_enabled": true, "id": "3698d3c7-d581-443e-bf86-53c4e3a738f7"}}
+-----------------------+--------------------------------------+
| Field | Value |
+-----------------------+--------------------------------------+
| admin_state_up | True |
| id | 3698d3c7-d581-443e-bf86-53c4e3a738f7 |
| mtu | 0 |
| name | mynetwork |
| port_security_enabled | True |
| router:external | False |
| shared | False |
| status | ACTIVE |
| subnets | |
| tenant_id | 8f0ebf767043483a987736c8c684178d |
+-----------------------+--------------------------------------+

View File

@ -1,263 +0,0 @@
..
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.
Convention for heading levels in Neutron devref:
======= Heading 0 (reserved for the title in a document)
------- Heading 1
~~~~~~~ Heading 2
+++++++ Heading 3
''''''' Heading 4
(Avoid deeper levels because they do not render well.)
CLI Option Guideline
====================
This document describes the conventions of neutron CLI options.
General conventions
-------------------
#. Option names should be delimited by a hyphen instead of a underscore.
This is the common guidelines across all OpenStack CLIs.
* Good: ``--ip-version``
* Not Good: ``--ip_version``
#. Use at least one required option for ``*-create`` command. If all options
are optional, we typically use ``name`` field as a required option.
#. When you need to specify an ID of a resource, it is better to provide
another way to specify the resource like ``name`` or other reasonable field.
#. If an attribute name in API is ``foo_id``, the corresponding option
should be ``--foo`` instead of ``--foo-id``.
* It is because we usually support ID and ``name`` to specify a resource.
#. Do not use ``nargs='?'`` without a special reason.
* The behavior of ``nargs='?'`` option for python argparse is
bit tricky and may lead to unexpected option parsing different
from the help message. The detail is described in the
:ref:`Background section <background-nargs>` below.
#. (option) Avoid using positional options as much as possible.
* Positional arguments should be limited to attributes which will
be required in the long future.
#. We honor existing options and should keep compatibilities when adding or
changing options.
Options for boolean value
-------------------------
Use the form of ``--option-name {True|False}``.
* For a new option, it is recommended.
* It is suggested to use ``common.utils.add_boolean_argument`` in an
implementation. It allows ``true``/``false`` in addition to ``True``/``False``.
* For existing options, migration to the recommended form is not necessarily
required. All backward-compatibility should be kept without reasonable
reasons.
Options for dict value
----------------------
Some API attributes take a dictionary.
``--foo key1=val1,key2=val2`` is usually used.
This means ``{"key1": "val1", "key2": "val2"}`` is passed in the API layer.
Examples:
* ``--host-route destination=CIDR,nexthop=IP_ADDR`` for a subnet
* ``--fixed-ip subnet_id=SUBNET,ip_address=IP_ADDR`` for a port.
Options for list value
----------------------
Some attributes take a list.
In this case, we usually use:
* Define an option per element (Use a singular form as an option name)
* Allow to specify the option multiple times
For Example, **port-create** has ``--security-group`` option.
``--security-group SG1 --security-group SG2`` generates
``{"security_groups: ["SG1", "SG2"]}`` in the API layer.
This convention applies to a case of a list of dict.
``--allocation-pool`` and ``--host-route`` for a subnet are examples.
Compatibility with extra arguments
----------------------------------
*extra arguments* supports various types of option specifications.
At least the following patterns needs to be considered when defining
a new option. For more detail, see :ref:`cli_extra_arguments`.
* Normal options with value
* Boolean options : ``--foo True``, ``--bar=False``
* List options : ``--bars list=true val1 val2``, ``--bars val1 val2``
* Dict options : ``--foo type=dict key1=va1,key2=val2``
* List of Dict options : ``--bars list=true type=dict key1=val1,key2=val2 key3=val3,key4=val4``
* ``action=clear``
For normal options with value, there are four patterns to specify an option
as extra arguments.
* ``--admin-state-up True`` (a space between option name and value)
* ``--admin-state-up=True`` (= between option name and value)
* ``--admin_state_up True`` (underscore is used as delimiter)
* ``--admin_state_up=True`` (underscore is used as delimiter)
.. _background:
Background
----------
There are a lot of opinions on which form of options are better or not.
This section tries to capture the reason of the current choice.
Use at least one required option
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As a convention, **neutron** CLI requires one required argument.
If all options are optional in the API level and we have ``name`` field,
we usually use ``name`` as a required parameter.
Requiring at least one argument has the following benefits:
* If we run ``neutron *-create`` without a required argument, we will have a
brief help message without detail option help. It is convenient.
* We can avoid miss operation by just hitting ``neutron *-create``.
Requiring at least one parameter is a good balance.
Even though we can change this convention to allow to create a resource
without ``name`` field, it will bring confusions to existing users.
There may be opinion that it is inconsistent with API level requirement
or Horizon behavior, but even if neutron CLI requires ``name`` field
there is no bad impact on regular users. Considering possible confusion
if we change it, it looks better to keep it as-is.
Options for Boolean value
~~~~~~~~~~~~~~~~~~~~~~~~~
* ``--enable-foo``/``--disable-foo`` or similar patterns (including
``--admin-state-down``) is not suggested because we need two exclusive
options for one attribute in REST API. It is meaningless.
* It is not recommended to have an option only to specify non-default value.
For example, we have ``--shared`` or ``--admin-state-down`` options for
net-create. This form only works for ``*-create`` and does not work for
``*-update``. It leads to having different options for ``*-create`` and
``*-update``.
* A flag option like ``--enable-dhcp`` (without value) also has a problem when
considering the compatibility with *extra argument*. We can specify
``-enable-dhcp True/False`` or ``--enable-dhcp=True/False`` in the *extra
argument* mechanism. If we introduce ``--enable-dhcp`` (without value),
the form of ``-enable-dhcp True/False`` cannot be used now.
This is another reason we don't use a flag style option for a boolean parameter.
.. _background-nargs:
Avoid using nargs in positional or optional arguments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The behavior of ``nargs='?'`` option for python argparse is bit tricky.
When we use ``nargs='?'`` and if the order of command-line options is
changed then the command-line parser may fail to parse the arguments
correctly. Two examples of such failures are provided below.
Example 1:
This example shows how the actual behavior can differ from the provided
help message. In the below block, help message at ``[5]`` says ``--bb CC``
is a valid format but the argument parsing for the same format fails at ``[7]``.
.. code-block:: console
In [1]: import argparse
In [2]: parser = argparse.ArgumentParser()
In [3]: parser.add_argument('--bb', nargs='?')
In [4]: parser.add_argument('cc')
In [5]: parser.print_help()
usage: ipython [-h] [--bb [BB]] cc
positional arguments:
cc
optional arguments:
-h, --help show this help message and exit
--bb [BB]
In [6]: parser.parse_args('--bb 1 X'.split())
Out[6]: Namespace(bb='1', cc='X')
In [7]: parser.parse_args('--bb X'.split())
usage: ipython [-h] [--bb [BB]] cc
ipython: error: too few arguments
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
Example 2:
This example shows how fragile ``nargs='?'`` can be when user specifies
options in different order from the help message.
.. code-block:: console
In [1]: import argparse
In [2]: parser = argparse.ArgumentParser()
In [3]: parser.add_argument('--a', help='option a')
In [4]: parser.add_argument('--b', help='option b')
In [5]: parser.add_argument('x', help='positional arg X')
In [6]: parser.add_argument('y', nargs='?', help='positional arg Y')
In [7]: parser.print_help()
usage: ipython [-h] [--a A] [--b B] x [y]
positional arguments:
x positional arg X
y positional arg Y
optional arguments:
-h, --help show this help message and exit
--a A option a
--b B option b
In [8]: parser.parse_args('--a 1 --b 2 X Y'.split())
Out[8]: Namespace(a='1', b='2', x='X', y='Y')
In [9]: parser.parse_args('X Y --a 1 --b 2'.split())
Out[9]: Namespace(a='1', b='2', x='X', y='Y')
In [10]: parser.parse_args('X --a 1 --b 2 Y'.split())
usage: ipython [-h] [--a A] [--b B] x [y]
ipython: error: unrecognized arguments: Y
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
To exit: use 'exit', 'quit', or Ctrl-D.
To exit: use 'exit', 'quit', or Ctrl-D.
Note: Most CLI users don't care about the order of the command-line
options. Hence, such fragile behavior should be avoided.

View File

@ -1,97 +0,0 @@
..
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.
Convention for heading levels in Neutron devref:
======= Heading 0 (reserved for the title in a document)
------- Heading 1
~~~~~~~ Heading 2
+++++++ Heading 3
''''''' Heading 4
(Avoid deeper levels because they do not render well.)
Client command extension support
=================================
The client command extension adds support for extending the neutron client while
considering ease of creation.
Extensions strongly conform to preexisting neutron commands (/neutron/v2_0/).
A sample extension can be seen at:
neutronclient/neutron/v2_0/contrib/_fox_sockets.py
Minimum requirements from an extension
--------------------------------------
* NeutronClientExtension subclasses must have a shell_command class variable
if the command is to be available to the CLI (shell.py)
Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocketsList
Minimum requirements to use canonical neutron CRUD commands framework
----------------------------------------------------------------------
Neutron commands are cliff commands, commands in extension can use their
own way to finish their tasks. But if they want to make use of the canonical
neutron CRUD commands framework, the extension should:
* have a class that subclasses NeutronClientExtension to provide the
requisite resource name, version support, and resource collection and
object paths for a resource the commands will process.
Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocket
* have a class that subclasses from the ClientExtensionList to provide
resource object list function. This is because most commands
need the list function to get object ID via
neutronclient.neutron.v2_0.__init__.find_resource_by_id.
Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocketsList
* if needed, subclass ClientExtensionUpdate to implement update of the resource
object.
Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocketsUpdate
* if needed, subclass ClientExtensionDelete to implement deletion of the resource
object.
Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocketsDelete
* if needed, subclass ClientExtensionShow to get the detail of the resource
object.
Example: neutronclient.neutron.v2_0.contrib._fox_sockets.FoxInSocketsShow
Precedence of command loading
------------------------------
* hard coded commands are loaded first
* external commands (installed in the environment) are loaded then
Commands that have the same name will be overwritten by commands that are
loaded later. To change the execution of a command for your particular
extension you only need to override the execute method.
Currently this extension support is limited to top-level resources.
Parent/child relationships may be added if desired.
neutronclient.extension entry_point
-----------------------------------
To activate the commands in a specific extension module, add an entry in
setup.cfg under neutronclient.extension. For example::
[entry_points]
neutronclient.extension =
fox_sockets = neutronclient.neutron.v2_0.contrib._fox_sockets

View File

@ -31,6 +31,4 @@ OpenStack client.
.. toctree:: .. toctree::
:maxdepth: 2 :maxdepth: 2
client_command_extensions
cli_option_guideline
transition_to_osc transition_to_osc

View File

@ -105,7 +105,7 @@ Transition Steps
In addition, no new features will be added to the CLI, though fixes to In addition, no new features will be added to the CLI, though fixes to
the CLI will be assessed on a case by case basis. the CLI will be assessed on a case by case basis.
8. **Not Started:** Remove the ``neutron`` CLI after two deprecation cycles 8. **Done** Remove the ``neutron`` CLI after two deprecation cycles
once the criteria below have been met. once the criteria below have been met.
* The networking support provide by the ``openstack`` CLI is functionally * The networking support provide by the ``openstack`` CLI is functionally
@ -122,32 +122,8 @@ Transition Steps
Developer Guide Developer Guide
--------------- ---------------
The ``neutron`` CLI version 6.x, without extensions, supports over 200 The ``neutron`` CLI tool is now removed and all new CLI changes should be done
commands while the ``openstack`` CLI version 3.3.0 supports over 70 in the ``OpenStackClient (OSC)`` and, if needed, also in the ``OpenStack SDK``.
networking commands. Of the 70 commands, some do not have all of the options
or arguments of their ``neutron`` CLI equivalent. With this large functional
gap, a few critical questions for developers during this transition are "Which
CLI do I change?", "Where does my CLI belong?", and "Which Python library do I change?"
The answer depends on the state of a command and the state of the overall transition.
Details are outlined in the tables below. Early stages of the transition will require
dual maintenance.
**Which CLI do I change?**
+----------------------+------------------------+-------------------------------------------------+
| ``neutron`` Command | ``openstack`` Command | CLI to Change |
+======================+========================+=================================================+
| Exists | Doesn't Exist | ``neutron`` |
+----------------------+------------------------+-------------------------------------------------+
| Exists | In Progress | ``neutron`` and ``openstack`` |
| | | (update related blueprint or bug) |
+----------------------+------------------------+-------------------------------------------------+
| Exists | Exists | ``openstack`` |
| | | (assumes command parity resulting in |
| | | ``neutron`` being deprecated) |
+----------------------+------------------------+-------------------------------------------------+
| Doesn't Exist | Doesn't Exist | ``openstack`` |
+----------------------+------------------------+-------------------------------------------------+
**Where does my CLI belong?** **Where does my CLI belong?**
@ -186,8 +162,6 @@ is not required as the neutronclient is already deprecated on its own.
+=================================================+===============================================+ +=================================================+===============================================+
| python-openstackclient | openstacksdk | | python-openstackclient | openstacksdk |
+-------------------------------------------------+-----------------------------------------------+ +-------------------------------------------------+-----------------------------------------------+
| python-neutronclient | python-neutronclient |
+-------------------------------------------------+-----------------------------------------------+
| Other | Applicable project owning network resource | | Other | Applicable project owning network resource |
+-------------------------------------------------+-----------------------------------------------+ +-------------------------------------------------+-----------------------------------------------+

View File

@ -24,15 +24,11 @@ python-neutronclient documentation
================================== ==================================
This is a client for OpenStack Networking API. It provides This is a client for OpenStack Networking API. It provides
:doc:`Python API bindings <reference/index>` (the neutronclient module) and :doc:`Python API bindings <reference/index>` (the neutronclient module).
:doc:`command-line interface (CLI) <cli/index>`.
There are two CLIs which support the Networking API: There is
:doc:`neutron CLI <cli/neutron>` and
`OpenStack Client (OSC) <https://docs.openstack.org/python-openstackclient/latest/>`__. `OpenStack Client (OSC) <https://docs.openstack.org/python-openstackclient/latest/>`__.
OpenStack Client provides the basic network commands and CLI which support the Networking API.
python-neutronclient provides extensions (aka OSC plugins)
for advanced networking services.
User Documentation User Documentation
------------------ ------------------

View File

@ -1,165 +0,0 @@
#!/bin/bash
set -x
function die() {
local exitcode=$?
set +o xtrace
echo $@
cleanup
exit $exitcode
}
net_name=mynet1
subnet_name=mysubnet1
port_name=myport1
function cleanup() {
echo Removing test port, subnet and net...
neutron port-delete $port_name
neutron subnet-delete $subnet_name
neutron net-delete $net_name
}
noauth_tenant_id=me
if [ "$1" == "noauth" ]; then
NOAUTH="--tenant_id $noauth_tenant_id"
else
NOAUTH=
fi
echo "NOTE: User should be admin in order to perform all operations."
sleep 3
# test the CRUD of network
network=$net_name
neutron net-create $NOAUTH $network || die "fail to create network $network"
temp=`neutron net-list -- --name $network --fields id | wc -l`
echo $temp
if [ $temp -ne 5 ]; then
die "networks with name $network is not unique or found"
fi
network_id=`neutron net-list -- --name $network --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
echo "ID of network with name $network is $network_id"
neutron net-show $network || die "fail to show network $network"
neutron net-show $network_id || die "fail to show network $network_id"
neutron net-update $network --admin_state_up False || die "fail to update network $network"
neutron net-update $network_id --admin_state_up True || die "fail to update network $network_id"
neutron net-list -c id -- --id fakeid || die "fail to list networks with column selection on empty list"
# test the CRUD of subnet
subnet=$subnet_name
cidr=10.0.1.0/24
neutron subnet-create $NOAUTH $network $cidr --name $subnet || die "fail to create subnet $subnet"
tempsubnet=`neutron subnet-list -- --name $subnet --fields id | wc -l`
echo $tempsubnet
if [ $tempsubnet -ne 5 ]; then
die "subnets with name $subnet is not unique or found"
fi
subnet_id=`neutron subnet-list -- --name $subnet --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
echo "ID of subnet with name $subnet is $subnet_id"
neutron subnet-show $subnet || die "fail to show subnet $subnet"
neutron subnet-show $subnet_id || die "fail to show subnet $subnet_id"
neutron subnet-update $subnet --dns_nameservers list=true 1.1.1.11 1.1.1.12 || die "fail to update subnet $subnet"
neutron subnet-update $subnet_id --dns_nameservers list=true 2.2.2.21 2.2.2.22 || die "fail to update subnet $subnet_id"
# test the crud of ports
port=$port_name
neutron port-create $NOAUTH $network --name $port || die "fail to create port $port"
tempport=`neutron port-list -- --name $port --fields id | wc -l`
echo $tempport
if [ $tempport -ne 5 ]; then
die "ports with name $port is not unique or found"
fi
port_id=`neutron port-list -- --name $port --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
echo "ID of port with name $port is $port_id"
neutron port-show $port || die "fail to show port $port"
neutron port-show $port_id || die "fail to show port $port_id"
neutron port-update $port --device_id deviceid1 || die "fail to update port $port"
neutron port-update $port_id --device_id deviceid2 || die "fail to update port $port_id"
neutron port-update $port_id --allowed-address-pair ip_address=1.1.1.11,mac_address=10:00:00:00:00:00 --allowed-address-pair ip_address=1.1.1.12,mac_address=10:00:00:00:00:01 || die "fail to update port $port_id --allowed-address-pair"
neutron port-show $port || die "fail to show port $port"
neutron port-show $port_id || die "fail to show port $port_id"
neutron port-update $port_id --no-allowed-address-pairs || die "fail to update port $port_id --no-allowed-address-pairs"
neutron port-show $port || die "fail to show port $port"
neutron port-show $port_id || die "fail to show port $port_id"
neutron port-delete $port_id
# test the create port with allowed-address-pairs
port=$port_name
neutron port-create $NOAUTH $network --name $port -- --allowed-address-pairs type=dict list=true ip_address=1.1.1.11,mac_address=10:00:00:00:00:00 ip_address=1.1.1.12,mac_address=10:00:00:00:00:01 || die "fail to create port $port"
tempport=`neutron port-list -- --name $port --fields id | wc -l`
echo $tempport
if [ $tempport -ne 5 ]; then
die "ports with name $port is not unique or found"
fi
port_id=`neutron port-list -- --name $port --fields id | tail -n 2 | head -n 1 | cut -d' ' -f 2`
echo "ID of port with name $port is $port_id"
neutron port-show $port || die "fail to show port $port"
neutron port-show $port_id || die "fail to show port $port_id"
neutron port-update $port_id --no-allowed-address-pairs || die "fail to update port $port_id --no-allowed-address-pairs"
neutron port-show $port_id
# test quota commands RUD
DEFAULT_NETWORKS=10
DEFAULT_PORTS=50
tenant_id=tenant_a
tenant_id_b=tenant_b
neutron quota-update --tenant_id $tenant_id --network 30 || die "fail to update quota for tenant $tenant_id"
neutron quota-update --tenant_id $tenant_id_b --network 20 || die "fail to update quota for tenant $tenant_id"
networks=`neutron quota-list -c network -c tenant_id | grep $tenant_id | awk '{print $2}'`
if [ $networks -ne 30 ]; then
die "networks quota should be 30"
fi
networks=`neutron quota-list -c network -c tenant_id | grep $tenant_id_b | awk '{print $2}'`
if [ $networks -ne 20 ]; then
die "networks quota should be 20"
fi
networks=`neutron quota-show --tenant_id $tenant_id | grep network | awk -F'|' '{print $3}'`
if [ $networks -ne 30 ]; then
die "networks quota should be 30"
fi
neutron quota-delete --tenant_id $tenant_id || die "fail to delete quota for tenant $tenant_id"
networks=`neutron quota-show --tenant_id $tenant_id | grep network | awk -F'|' '{print $3}'`
if [ $networks -ne $DEFAULT_NETWORKS ]; then
die "networks quota should be $DEFAULT_NETWORKS"
fi
# update self
if [ "t$NOAUTH" = "t" ]; then
# with auth
neutron quota-update --port 99 || die "fail to update quota for self"
ports=`neutron quota-show | grep port | awk -F'|' '{print $3}'`
if [ $ports -ne 99 ]; then
die "ports quota should be 99"
fi
ports=`neutron quota-list -c port | grep 99 | awk '{print $2}'`
if [ $ports -ne 99 ]; then
die "ports quota should be 99"
fi
neutron quota-delete || die "fail to delete quota for tenant self"
ports=`neutron quota-show | grep port | awk -F'|' '{print $3}'`
if [ $ports -ne $DEFAULT_PORTS ]; then
die "ports quota should be $DEFAULT_PORTS"
fi
else
# without auth
neutron quota-update --port 100
if [ $? -eq 0 ]; then
die "without valid context on server, quota update command should fail."
fi
neutron quota-show
if [ $? -eq 0 ]; then
die "without valid context on server, quota show command should fail."
fi
neutron quota-delete
if [ $? -eq 0 ]; then
die "without valid context on server, quota delete command should fail."
fi
neutron quota-list || die "fail to update quota for self"
fi
cleanup
echo "Success! :)"

View File

@ -1,654 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# 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.
#
"""
Command-line interface to the Neutron APIs
"""
import argparse
import inspect
import itertools
import logging
import os
import sys
from keystoneauth1 import session
import os_client_config
from oslo_utils import encodeutils
from oslo_utils import netutils
from cliff import app
from cliff import command
from cliff import commandmanager
from neutronclient._i18n import _
from neutronclient.common import clientmanager
from neutronclient.common import exceptions as exc
from neutronclient.common import extension as client_extension
from neutronclient.neutron.v2_0 import subnet
from neutronclient.version import __version__
VERSION = '2.0'
NEUTRON_API_VERSION = '2.0'
NAMESPACE_MAP = {NEUTRON_API_VERSION: 'neutron.cli.v2'}
def run_command(cmd, cmd_parser, sub_argv):
_argv = sub_argv
index = -1
values_specs = []
if '--' in sub_argv:
index = sub_argv.index('--')
_argv = sub_argv[:index]
values_specs = sub_argv[index:]
known_args, _values_specs = cmd_parser.parse_known_args(_argv)
if(isinstance(cmd, subnet.CreateSubnet) and not known_args.cidr):
cidr = get_first_valid_cidr(_values_specs)
if cidr:
known_args.cidr = cidr
_values_specs.remove(cidr)
cmd.values_specs = (index == -1 and _values_specs or values_specs)
return cmd.run(known_args)
def get_first_valid_cidr(value_specs):
# Bug 1442771, argparse does not allow optional positional parameter
# to be separated from previous positional parameter.
# When cidr was separated from network, the value will not be able
# to be parsed into known_args, but saved to _values_specs instead.
for value in value_specs:
if netutils.is_valid_cidr(value):
return value
def env(*_vars, **kwargs):
"""Search for the first defined of possibly many env vars.
Returns the first environment variable defined in vars, or
returns the default defined in kwargs.
"""
for v in _vars:
value = os.environ.get(v, None)
if value:
return value
return kwargs.get('default', '')
def check_non_negative_int(value):
try:
value = int(value)
except ValueError:
raise argparse.ArgumentTypeError(_("invalid int value: %r") % value)
if value < 0:
raise argparse.ArgumentTypeError(_("input value %d is negative") %
value)
return value
COMMANDS = {}
# NOTE(amotoki): This is only to provide compatibility
# to existing neutron CLI extensions. See bug 1706573 for detail.
def _set_commands_dict_for_compat(apiversion, command_manager):
global COMMANDS
COMMANDS = {apiversion: dict((cmd, command_manager.find_command([cmd])[0])
for cmd in command_manager.commands)}
class BashCompletionCommand(command.Command):
"""Prints all of the commands and options for bash-completion."""
def take_action(self, parsed_args):
pass
class HelpAction(argparse.Action):
"""Print help message including sub-commands
Provide a custom action so the -h and --help options
to the main app will print a list of the commands.
The commands are determined by checking the CommandManager
instance, passed in as the "default" value for the action.
"""
def __call__(self, parser, namespace, values, option_string=None):
outputs = []
max_len = 0
app = self.default
parser.print_help(app.stdout)
app.stdout.write(_('\nCommands for API v%s:\n') % app.api_version)
command_manager = app.command_manager
for name, ep in sorted(command_manager):
factory = ep.load()
cmd = factory(self, None)
one_liner = cmd.get_description().split('\n')[0]
outputs.append((name, one_liner))
max_len = max(len(name), max_len)
for (name, one_liner) in outputs:
app.stdout.write(' %s %s\n' % (name.ljust(max_len), one_liner))
sys.exit(0)
class NeutronShell(app.App):
# verbose logging levels
WARNING_LEVEL = 0
INFO_LEVEL = 1
DEBUG_LEVEL = 2
CONSOLE_MESSAGE_FORMAT = '%(message)s'
DEBUG_MESSAGE_FORMAT = '%(levelname)s: %(name)s %(message)s'
log = logging.getLogger(__name__)
def __init__(self, apiversion):
namespace = NAMESPACE_MAP[apiversion]
description = (__doc__.strip() +
" (neutron CLI version: %s)" % __version__)
super(NeutronShell, self).__init__(
description=description,
version=VERSION,
command_manager=commandmanager.CommandManager(namespace), )
self._register_extensions(VERSION)
# Pop the 'complete' to correct the outputs of 'neutron help'.
self.command_manager.commands.pop('complete')
# This is instantiated in initialize_app() only when using
# password flow auth
self.auth_client = None
self.api_version = apiversion
_set_commands_dict_for_compat(apiversion, self.command_manager)
def build_option_parser(self, description, version):
"""Return an argparse option parser for this application.
Subclasses may override this method to extend
the parser with more global options.
:param description: full description of the application
:paramtype description: str
:param version: version number for the application
:paramtype version: str
"""
parser = argparse.ArgumentParser(
description=description,
add_help=False, )
parser.add_argument(
'--version',
action='version',
version=__version__, )
parser.add_argument(
'-v', '--verbose', '--debug',
action='count',
dest='verbose_level',
default=self.DEFAULT_VERBOSE_LEVEL,
help=_('Increase verbosity of output and show tracebacks on'
' errors. You can repeat this option.'))
parser.add_argument(
'-q', '--quiet',
action='store_const',
dest='verbose_level',
const=0,
help=_('Suppress output except warnings and errors.'))
parser.add_argument(
'-h', '--help',
action=HelpAction,
nargs=0,
default=self, # tricky
help=_("Show this help message and exit."))
parser.add_argument(
'-r', '--retries',
metavar="NUM",
type=check_non_negative_int,
default=0,
help=_("How many times the request to the Neutron server should "
"be retried if it fails. Defaults to 0."))
# FIXME(bklei): this method should come from keystoneauth1
self._append_global_identity_args(parser)
return parser
def _append_global_identity_args(self, parser):
# FIXME(bklei): these are global identity (Keystone) arguments which
# should be consistent and shared by all service clients. Therefore,
# they should be provided by keystoneauth1. We will need to
# refactor this code once this functionality is available in
# keystoneauth1.
#
# Note: At that time we'll need to decide if we can just abandon
# the deprecated args (--service-type and --endpoint-type).
parser.add_argument(
'--os-service-type', metavar='<os-service-type>',
default=env('OS_NETWORK_SERVICE_TYPE', default='network'),
help=_('Defaults to env[OS_NETWORK_SERVICE_TYPE] or "network".'))
parser.add_argument(
'--os-endpoint-type', metavar='<os-endpoint-type>',
default=env('OS_ENDPOINT_TYPE', default='public'),
help=_('Defaults to env[OS_ENDPOINT_TYPE] or "public".'))
# FIXME(bklei): --service-type is deprecated but kept in for
# backward compatibility.
parser.add_argument(
'--service-type', metavar='<service-type>',
default=env('OS_NETWORK_SERVICE_TYPE', default='network'),
help=_('DEPRECATED! Use --os-service-type.'))
# FIXME(bklei): --endpoint-type is deprecated but kept in for
# backward compatibility.
parser.add_argument(
'--endpoint-type', metavar='<endpoint-type>',
default=env('OS_ENDPOINT_TYPE', default='public'),
help=_('DEPRECATED! Use --os-endpoint-type.'))
parser.add_argument(
'--os-auth-strategy', metavar='<auth-strategy>',
default=env('OS_AUTH_STRATEGY', default='keystone'),
help=_('DEPRECATED! Only keystone is supported.'))
parser.add_argument(
'--os_auth_strategy',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-cloud', metavar='<cloud>',
help=_('Defaults to env[OS_CLOUD].'))
parser.add_argument(
'--os-auth-url', metavar='<auth-url>',
help=_('Authentication URL, defaults to env[OS_AUTH_URL].'))
parser.add_argument(
'--os_auth_url',
help=argparse.SUPPRESS)
project_name_group = parser.add_mutually_exclusive_group()
project_name_group.add_argument(
'--os-tenant-name', metavar='<auth-tenant-name>',
help=_('Authentication tenant name, defaults to '
'env[OS_TENANT_NAME].'))
project_name_group.add_argument(
'--os-project-name',
metavar='<auth-project-name>',
help=_('Another way to specify tenant name. '
'This option is mutually exclusive with '
' --os-tenant-name. '
'Defaults to env[OS_PROJECT_NAME].'))
parser.add_argument(
'--os_tenant_name',
help=argparse.SUPPRESS)
project_id_group = parser.add_mutually_exclusive_group()
project_id_group.add_argument(
'--os-tenant-id', metavar='<auth-tenant-id>',
help=_('Authentication tenant ID, defaults to '
'env[OS_TENANT_ID].'))
project_id_group.add_argument(
'--os-project-id',
metavar='<auth-project-id>',
help=_('Another way to specify tenant ID. '
'This option is mutually exclusive with '
' --os-tenant-id. '
'Defaults to env[OS_PROJECT_ID].'))
parser.add_argument(
'--os-username', metavar='<auth-username>',
help=_('Authentication username, defaults to env[OS_USERNAME].'))
parser.add_argument(
'--os_username',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-user-id', metavar='<auth-user-id>',
help=_('Authentication user ID (Env: OS_USER_ID)'))
parser.add_argument(
'--os_user_id',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-user-domain-id',
metavar='<auth-user-domain-id>',
help=_('OpenStack user domain ID. '
'Defaults to env[OS_USER_DOMAIN_ID].'))
parser.add_argument(
'--os_user_domain_id',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-user-domain-name',
metavar='<auth-user-domain-name>',
help=_('OpenStack user domain name. '
'Defaults to env[OS_USER_DOMAIN_NAME].'))
parser.add_argument(
'--os_user_domain_name',
help=argparse.SUPPRESS)
parser.add_argument(
'--os_project_id',
help=argparse.SUPPRESS)
parser.add_argument(
'--os_project_name',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-project-domain-id',
metavar='<auth-project-domain-id>',
help=_('Defaults to env[OS_PROJECT_DOMAIN_ID].'))
parser.add_argument(
'--os-project-domain-name',
metavar='<auth-project-domain-name>',
help=_('Defaults to env[OS_PROJECT_DOMAIN_NAME].'))
parser.add_argument(
'--os-cert',
metavar='<certificate>',
help=_("Path of certificate file to use in SSL "
"connection. This file can optionally be "
"prepended with the private key. Defaults "
"to env[OS_CERT]."))
parser.add_argument(
'--os-cacert',
metavar='<ca-certificate>',
help=_("Specify a CA bundle file to use in "
"verifying a TLS (https) server certificate. "
"Defaults to env[OS_CACERT]."))
parser.add_argument(
'--os-key',
metavar='<key>',
help=_("Path of client key to use in SSL "
"connection. This option is not necessary "
"if your key is prepended to your certificate "
"file. Defaults to env[OS_KEY]."))
parser.add_argument(
'--os-password', metavar='<auth-password>',
help=_('Authentication password, defaults to env[OS_PASSWORD].'))
parser.add_argument(
'--os_password',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-region-name', metavar='<auth-region-name>',
help=_('Authentication region name, defaults to '
'env[OS_REGION_NAME].'))
parser.add_argument(
'--os_region_name',
help=argparse.SUPPRESS)
parser.add_argument(
'--os-token', metavar='<token>',
help=_('Authentication token, defaults to env[OS_TOKEN].'))
parser.add_argument(
'--os_token',
help=argparse.SUPPRESS)
parser.add_argument(
'--http-timeout', metavar='<seconds>',
default=env('OS_NETWORK_TIMEOUT', default=None), type=float,
help=_('Timeout in seconds to wait for an HTTP response. Defaults '
'to env[OS_NETWORK_TIMEOUT] or None if not specified.'))
parser.add_argument(
'--os-url', metavar='<url>',
help=_('Defaults to env[OS_URL].'))
parser.add_argument(
'--os_url',
help=argparse.SUPPRESS)
parser.add_argument(
'--insecure',
action='store_true',
default=env('NEUTRONCLIENT_INSECURE', default=False),
help=_("Explicitly allow neutronclient to perform \"insecure\" "
"SSL (https) requests. The server's certificate will "
"not be verified against any certificate authorities. "
"This option should be used with caution."))
def _bash_completion(self):
"""Prints all of the commands and options for bash-completion."""
commands = set()
options = set()
for option, _action in self.parser._option_string_actions.items():
options.add(option)
for _name, _command in self.command_manager:
commands.add(_name)
cmd_factory = _command.load()
cmd = cmd_factory(self, None)
cmd_parser = cmd.get_parser('')
for option, _action in cmd_parser._option_string_actions.items():
options.add(option)
print(' '.join(commands | options))
def _register_extensions(self, version):
for name, module in itertools.chain(
client_extension._discover_via_entry_points()):
self._extend_shell_commands(name, module, version)
def _extend_shell_commands(self, name, module, version):
classes = inspect.getmembers(module, inspect.isclass)
for cls_name, cls in classes:
if (issubclass(cls, client_extension.NeutronClientExtension) and
hasattr(cls, 'shell_command')):
cmd = cls.shell_command
if hasattr(cls, 'versions'):
if version not in cls.versions:
continue
try:
name_prefix = "[%s]" % name
cls.__doc__ = ("%s %s" % (name_prefix, cls.__doc__) if
cls.__doc__ else name_prefix)
self.command_manager.add_command(cmd, cls)
except TypeError:
pass
def run(self, argv):
"""Equivalent to the main program for the application.
:param argv: input arguments and options
:paramtype argv: list of str
"""
try:
index = 0
command_pos = -1
help_pos = -1
help_command_pos = -1
for arg in argv:
if arg == 'bash-completion' and help_command_pos == -1:
self._bash_completion()
return 0
if arg in ('-h', '--help'):
if help_pos == -1:
help_pos = index
# self.command_manager.commands contains 'help',
# so we need to check this first.
elif arg == 'help':
if help_command_pos == -1:
help_command_pos = index
elif arg in self.command_manager.commands:
if command_pos == -1:
command_pos = index
index = index + 1
if command_pos > -1 and help_pos > command_pos:
argv = ['help', argv[command_pos]]
if help_command_pos > -1 and command_pos == -1:
argv[help_command_pos] = '--help'
self.options, remainder = self.parser.parse_known_args(argv)
self.configure_logging()
self.interactive_mode = not remainder
self.initialize_app(remainder)
except Exception as err:
if self.options.verbose_level >= self.DEBUG_LEVEL:
self.log.exception(err)
raise
else:
self.log.error(err)
return 1
if self.interactive_mode:
_argv = [sys.argv[0]]
sys.argv = _argv
return self.interact()
return self.run_subcommand(remainder)
def run_subcommand(self, argv):
subcommand = self.command_manager.find_command(argv)
cmd_factory, cmd_name, sub_argv = subcommand
cmd = cmd_factory(self, self.options)
try:
self.prepare_to_run_command(cmd)
full_name = (cmd_name
if self.interactive_mode
else ' '.join([self.NAME, cmd_name])
)
cmd_parser = cmd.get_parser(full_name)
return run_command(cmd, cmd_parser, sub_argv)
except SystemExit:
print(_("Try 'neutron help %s' for more information.") %
cmd_name, file=sys.stderr)
raise
except Exception as e:
if self.options.verbose_level >= self.DEBUG_LEVEL:
self.log.exception("%s", e)
raise
self.log.error("%s", e)
return 1
def authenticate_user(self):
"""Confirm user authentication
Make sure the user has provided all of the authentication
info we need.
"""
cloud_config = os_client_config.OpenStackConfig().get_one_cloud(
cloud=self.options.os_cloud, argparse=self.options,
network_api_version=self.api_version,
verify=not self.options.insecure)
verify, cert = cloud_config.get_requests_verify_args()
# TODO(singhj): Remove dependancy on HTTPClient
# for the case of token-endpoint authentication
# When using token-endpoint authentication legacy
# HTTPClient will be used, otherwise SessionClient
# will be used.
if self.options.os_token and self.options.os_url:
auth = None
auth_session = None
else:
auth = cloud_config.get_auth()
auth_session = session.Session(
auth=auth, verify=verify, cert=cert,
timeout=self.options.http_timeout)
interface = self.options.os_endpoint_type or self.endpoint_type
if interface.endswith('URL'):
interface = interface[:-3]
self.client_manager = clientmanager.ClientManager(
retries=self.options.retries,
raise_errors=False,
session=auth_session,
url=self.options.os_url,
token=self.options.os_token,
region_name=cloud_config.get_region_name(),
api_version=cloud_config.get_api_version('network'),
service_type=cloud_config.get_service_type('network'),
service_name=cloud_config.get_service_name('network'),
endpoint_type=interface,
auth=auth,
insecure=not verify,
log_credentials=True)
return
def initialize_app(self, argv):
"""Global app init bits:
* set up API versions
* validate authentication info
"""
super(NeutronShell, self).initialize_app(argv)
# If the user is not asking for help, make sure they
# have given us auth.
cmd_name = None
if argv:
cmd_info = self.command_manager.find_command(argv)
cmd_factory, cmd_name, sub_argv = cmd_info
if self.interactive_mode or cmd_name != 'help':
self.authenticate_user()
def configure_logging(self):
"""Create logging handlers for any log output."""
root_logger = logging.getLogger('')
# Set up logging to a file
root_logger.setLevel(logging.DEBUG)
# Send higher-level messages to the console via stderr
console = logging.StreamHandler(self.stderr)
console_level = {self.WARNING_LEVEL: logging.WARNING,
self.INFO_LEVEL: logging.INFO,
self.DEBUG_LEVEL: logging.DEBUG,
}.get(self.options.verbose_level, logging.DEBUG)
# The default log level is INFO, in this situation, set the
# log level of the console to WARNING, to avoid displaying
# useless messages. This equals using "--quiet"
if console_level == logging.INFO:
console.setLevel(logging.WARNING)
else:
console.setLevel(console_level)
if logging.DEBUG == console_level:
formatter = logging.Formatter(self.DEBUG_MESSAGE_FORMAT)
else:
formatter = logging.Formatter(self.CONSOLE_MESSAGE_FORMAT)
logging.getLogger('iso8601.iso8601').setLevel(logging.WARNING)
logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING)
console.setFormatter(formatter)
root_logger.addHandler(console)
return
def main(argv=sys.argv[1:]):
try:
print(_("neutron CLI is deprecated and will be removed "
"in the Z cycle. Use openstack CLI instead."), file=sys.stderr)
return NeutronShell(NEUTRON_API_VERSION).run(
list(map(encodeutils.safe_decode, argv)))
except KeyboardInterrupt:
print(_("... terminating neutron client"), file=sys.stderr)
return 130
except exc.NeutronClientException:
return 1
except Exception as e:
print(e)
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))

View File

@ -1,42 +0,0 @@
# 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 neutronclient.tests.functional import base
class SimpleReadOnlyNeutronFwv1ClientTest(base.ClientTestBase):
"""Tests for FWaaS v1 based client commands that are read only"""
def setUp(self):
super(SimpleReadOnlyNeutronFwv1ClientTest, self).setUp()
if not self.is_extension_enabled('fwaas'):
self.skipTest('FWaaS is not enabled')
def test_neutron_firewall_list(self):
firewall_list = self.parser.listing(self.neutron
('firewall-list'))
self.assertTableStruct(firewall_list, ['id', 'name',
'firewall_policy_id'])
def test_neutron_firewall_policy_list(self):
firewall_policy = self.parser.listing(self.neutron
('firewall-policy-list'))
self.assertTableStruct(firewall_policy, ['id', 'name',
'firewall_rules'])
def test_neutron_firewall_rule_list(self):
firewall_rule = self.parser.listing(self.neutron
('firewall-rule-list'))
self.assertTableStruct(firewall_rule, ['id', 'name',
'firewall_policy_id',
'summary', 'enabled'])

View File

@ -1,57 +0,0 @@
# 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 neutronclient.tests.functional import base
class SimpleReadOnlyNeutronVpnClientTest(base.ClientTestBase):
"""Tests for vpn based client commands that are read only
This is a first pass at a simple read only python-neutronclient test.
This only exercises vpn based client commands that are read only.
This should test commands:
* as a regular user
* as a admin user
* with and without optional parameters
* initially just check return codes, and later test command outputs
"""
def setUp(self):
super(SimpleReadOnlyNeutronVpnClientTest, self).setUp()
if not self.is_extension_enabled('vpnaas'):
self.skipTest('VPNaaS is not enabled')
def test_neutron_vpn_ikepolicy_list(self):
ikepolicy = self.parser.listing(self.neutron('vpn-ikepolicy-list'))
self.assertTableStruct(ikepolicy, ['id', 'name',
'auth_algorithm',
'encryption_algorithm',
'ike_version', 'pfs'])
def test_neutron_vpn_ipsecpolicy_list(self):
ipsecpolicy = self.parser.listing(self.neutron('vpn-ipsecpolicy-list'))
self.assertTableStruct(ipsecpolicy, ['id', 'name',
'auth_algorithm',
'encryption_algorithm',
'pfs'])
def test_neutron_vpn_service_list(self):
vpn_list = self.parser.listing(self.neutron('vpn-service-list'))
self.assertTableStruct(vpn_list, ['id', 'name',
'router_id', 'status'])
def test_neutron_ipsec_site_connection_list(self):
ipsec_site = self.parser.listing(self.neutron
('ipsec-site-connection-list'))
self.assertTableStruct(ipsec_site, ['id', 'name',
'peer_address',
'auth_mode', 'status'])

View File

@ -1,80 +0,0 @@
# 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 os_client_config
from tempest.lib.cli import base
def credentials(cloud='devstack-admin'):
"""Retrieves credentials to run functional tests
Credentials are either read via os-client-config from the environment
or from a config file ('clouds.yaml'). Environment variables override
those from the config file.
devstack produces a clouds.yaml with two named clouds - one named
'devstack' which has user privs and one named 'devstack-admin' which
has admin privs. This function will default to getting the devstack-admin
cloud as that is the current expected behavior.
"""
return get_cloud_config(cloud=cloud).get_auth_args()
def get_cloud_config(cloud='devstack-admin'):
return os_client_config.OpenStackConfig().get_one_cloud(cloud=cloud)
class ClientTestBase(base.ClientTestBase):
"""This is a first pass at a simple read only python-neutronclient test.
This only exercises client commands that are read only.
This should test commands:
* as a regular user
* as an admin user
* with and without optional parameters
* initially just check return codes, and later test command outputs
"""
def _get_clients_from_os_cloud_config(self, cloud='devstack-admin'):
creds = credentials(cloud)
cli_dir = os.environ.get(
'OS_NEUTRONCLIENT_EXEC_DIR',
os.path.join(os.path.abspath('.'), '.tox/functional/bin'))
return base.CLIClient(
username=creds['username'],
password=creds['password'],
tenant_name=creds['project_name'],
project_domain_id=creds['project_domain_id'],
user_domain_id=creds['user_domain_id'],
uri=creds['auth_url'],
cli_dir=cli_dir)
def _get_clients(self):
return self._get_clients_from_os_cloud_config()
def neutron(self, *args, **kwargs):
return self.clients.neutron(*args, **kwargs)
def neutron_non_admin(self, *args, **kwargs):
if not hasattr(self, '_non_admin_clients'):
self._non_admin_clients = self._get_clients_from_os_cloud_config(
cloud='devstack')
return self._non_admin_clients.neutron(*args, **kwargs)
def is_extension_enabled(self, extension_alias):
extensions = self.parser.listing(self.neutron('ext-list'))
aliases = [e['alias'] for e in extensions]
return extension_alias in aliases

View File

@ -1,59 +0,0 @@
# Copyright 2016 NEC Corporation
#
# 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 oslo_serialization import jsonutils
from oslo_utils import uuidutils
import yaml
from neutronclient.tests.functional import base
class TestCLIFormatter(base.ClientTestBase):
def setUp(self):
super(TestCLIFormatter, self).setUp()
self.net_name = 'net-%s' % uuidutils.generate_uuid()
self.addCleanup(self.neutron, 'net-delete %s' % self.net_name)
def _create_net(self, fmt, col_attrs):
params = ['-c %s' % attr for attr in col_attrs]
params.append('-f %s' % fmt)
params.append(self.net_name)
param_string = ' '.join(params)
return self.neutron('net-create', params=param_string)
def test_net_create_with_json_formatter(self):
result = self._create_net('json', ['name', 'admin_state_up'])
self.assertDictEqual({'name': self.net_name,
'admin_state_up': True},
jsonutils.loads(result))
def test_net_create_with_yaml_formatter(self):
result = self._create_net('yaml', ['name', 'admin_state_up'])
self.assertDictEqual({'name': self.net_name,
'admin_state_up': True},
yaml.safe_load(result))
def test_net_create_with_value_formatter(self):
# NOTE(amotoki): In 'value' formatter, there is no guarantee
# in the order of attribute, so we use one attribute in this test.
result = self._create_net('value', ['name'])
self.assertEqual(self.net_name, result.strip())
def test_net_create_with_shell_formatter(self):
result = self._create_net('shell', ['name', 'admin_state_up'])
result_lines = set(result.strip().split('\n'))
self.assertSetEqual(set(['name="%s"' % self.net_name,
'admin_state_up="True"']),
result_lines)

View File

@ -1,61 +0,0 @@
# 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 keystoneauth1 import session
from oslo_utils import uuidutils
from tempest.lib import base
import testtools
from neutronclient.common import exceptions
from neutronclient.tests.functional import base as func_base
from neutronclient.v2_0 import client as v2_client
class LibraryTestCase(base.BaseTestCase):
def setUp(self):
super(LibraryTestCase, self).setUp()
self.client = self._get_client()
def _get_client(self):
cloud_config = func_base.get_cloud_config()
keystone_auth = cloud_config.get_auth()
(verify, cert) = cloud_config.get_requests_verify_args()
ks_session = session.Session(
auth=keystone_auth,
verify=verify,
cert=cert)
return v2_client.Client(session=ks_session)
def test_list_network(self):
nets = self.client.list_networks()
self.assertIsInstance(nets['networks'], list)
def test_post_put_delete_network(self):
name = uuidutils.generate_uuid()
net = self.client.create_network({'network': {'name': name}})
net_id = net['network']['id']
self.assertEqual(name, net['network']['name'])
name2 = uuidutils.generate_uuid()
net = self.client.update_network(net_id, {'network': {'name': name2}})
self.assertEqual(name2, net['network']['name'])
self.client.delete_network(net_id)
with testtools.ExpectedException(exceptions.NetworkNotFoundClient):
self.client.show_network(net_id)
def test_get_auth_ref(self):
# Call some API call to ensure the client is authenticated.
self.client.list_networks()
auth_ref = self.client.httpclient.get_auth_ref()
self.assertIsNotNone(auth_ref)
self.assertIsNotNone(auth_ref.role_names)

View File

@ -1,33 +0,0 @@
# Copyright 2016 NEC Corporation
#
# 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 neutronclient.tests.functional import base
class CLICommonFeatureTest(base.ClientTestBase):
def test_tenant_id_shown_in_list_by_admin(self):
nets = self.parser.table(self.neutron('net-list'))
self.assertIn('tenant_id', nets['headers'])
def test_tenant_id_not_shown_in_list_with_columns(self):
nets = self.parser.table(self.neutron('net-list -c id -c name'))
self.assertNotIn('tenant_id', nets['headers'])
self.assertListEqual(['id', 'name'], nets['headers'])
def test_tenant_id_not_shown_in_list_by_non_admin(self):
output = self.neutron_non_admin('net-list')
self.assertNotIn('tenant_id', self.parser.table(output)['headers'])
self.assertTableStruct(self.parser.listing(output),
['id', 'name'])

View File

@ -1,174 +0,0 @@
# Copyright 2016 Cisco Systems
# 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 neutronclient.tests.functional import base
from tempest.lib import exceptions
class PurgeNeutronClientCLITest(base.ClientTestBase):
def _safe_cleanup(self, delete_command):
try:
self.neutron(delete_command)
except exceptions.CommandFailed:
# This resource was already purged successfully
pass
def _create_subnet(self, name, tenant_id, cidr):
params = ('%(name)s --name %(name)s --tenant-id %(tenant)s '
'%(cidr)s' % {'name': name,
'tenant': tenant_id,
'cidr': cidr})
subnet = self.parser.listing(self.neutron('subnet-create',
params=params))
for row in subnet:
if row['Field'] == 'id':
return row['Value']
def _create_router(self, name, tenant_id):
params = ('%(name)s --tenant_id %(tenant)s' % {'name': name,
'tenant': tenant_id})
router = self.parser.listing(self.neutron('router-create',
params=params))
for row in router:
if row['Field'] == 'id':
return row['Value']
def _create_floatingip(self, network, tenant_id):
params = ('%(network)s --tenant-id %(tenant)s' %
{'network': network, 'tenant': tenant_id})
floatingip = self.parser.listing(self.neutron('floatingip-create',
params=params))
for row in floatingip:
if row['Field'] == 'id':
return row['Value']
def _create_resources(self, name, tenant_id, shared_tenant_id=None):
# If no shared_tenant_id is provided, create the resources for the
# current tenant to test that they will be deleted when not in use.
if not shared_tenant_id:
shared_tenant_id = tenant_id
self.neutron('net-create',
params=('%(name)s --router:external True '
'--tenant-id %(tenant)s' % {'name': name,
'tenant': tenant_id}))
self.addCleanup(self._safe_cleanup, 'net-delete %s' % name)
self.neutron('net-create',
params=('%(name)s-shared --shared '
'--tenant-id %(tenant)s' %
{'name': name, 'tenant': shared_tenant_id}))
self.addCleanup(self._safe_cleanup,
'net-delete %s-shared' % name)
subnet = self._create_subnet(name, tenant_id, '192.168.71.0/24')
self.addCleanup(self._safe_cleanup, 'subnet-delete %s' % name)
subnet = self._create_subnet('%s-shared' % name, tenant_id,
'192.168.81.0/24')
self.addCleanup(self._safe_cleanup, 'subnet-delete %s-shared' % name)
router = self._create_router(name, tenant_id)
self.addCleanup(self._safe_cleanup, 'router-delete %s' % name)
self.neutron('router-interface-add',
params=('%(router)s %(subnet)s '
'--tenant-id %(tenant)s' % {'router': router,
'subnet': subnet,
'tenant': tenant_id}))
self.neutron('port-create',
params=('%(name)s --name %(name)s '
'--tenant-id %(tenant)s' % {'name': name,
'tenant': tenant_id}))
self.addCleanup(self._safe_cleanup, 'port-delete %s' % name)
self.neutron('port-create',
params=('%(name)s-shared --name %(name)s-shared '
'--tenant-id %(tenant)s' % {'name': name,
'tenant': tenant_id}))
self.addCleanup(self._safe_cleanup, 'port-delete %s-shared' % name)
self.neutron('security-group-create',
params=('%(name)s --tenant-id %(tenant)s' %
{'name': name, 'tenant': tenant_id}))
self.addCleanup(self._safe_cleanup, 'security-group-delete %s' % name)
floatingip = self._create_floatingip(name, tenant_id)
self.addCleanup(self._safe_cleanup, ('floatingip-delete '
'%s' % floatingip))
return floatingip
def _verify_deletion(self, resources, resource_type):
purged = True
no_purge_purged = True
router_interface_owners = ['network:router_interface',
'network:router_interface_distributed']
for row in resources:
if resource_type == 'port' and row.get('id', None):
port = self.parser.listing(self.neutron('port-show',
params=row['id']))
port_dict = {}
for row in port:
port_dict[row['Field']] = row['Value']
if port_dict['device_owner'] in router_interface_owners:
if port_dict['tenant_id'] == 'purge-tenant':
purged = False
elif port_dict['tenant_id'] == 'no-purge-tenant':
no_purge_purged = False
if not purged or not no_purge_purged:
self.addCleanup(self.neutron,
('router-interface-delete %(router)s '
'port=%(port)s' %
{'router': port_dict['device_id'],
'port': port_dict['id']}))
if (row.get('name') == 'purge-me' or
row.get('id') == self.purge_floatingip):
purged = False
elif ('no-purge' in row.get('name', '') or
row.get('id') == self.no_purge_floatingip):
no_purge_purged = False
if not purged:
self.fail('%s not deleted by neutron purge' % resource_type)
if no_purge_purged:
self.fail('%s owned by another tenant incorrectly deleted '
'by neutron purge' % resource_type)
def test_purge(self):
self.purge_floatingip = self._create_resources('purge-me',
'purge-tenant')
self.no_purge_floatingip = self._create_resources('no-purge',
'no-purge-tenant',
'purge-tenant')
purge_output = self.neutron('purge', params='purge-tenant').strip()
if not purge_output:
self.fail('Purge command did not return feedback')
networks = self.parser.listing(self.neutron('net-list'))
subnets = self.parser.listing(self.neutron('subnet-list'))
routers = self.parser.listing(self.neutron('router-list'))
ports = self.parser.listing(self.neutron('port-list'))
floatingips = self.parser.listing(self.neutron('floatingip-list'))
self._verify_deletion(networks, 'network')
self._verify_deletion(subnets, 'subnet')
self._verify_deletion(ports, 'port')
self._verify_deletion(routers, 'router')
self._verify_deletion(floatingips, 'floatingip')

View File

@ -1,136 +0,0 @@
# 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 re
from tempest.lib import exceptions
from neutronclient.tests.functional import base
class SimpleReadOnlyNeutronClientTest(base.ClientTestBase):
"""This is a first pass at a simple read only python-neutronclient test.
This only exercises client commands that are read only.
This should test commands:
* as a regular user
* as a admin user
* with and without optional parameters
* initially just check return codes, and later test command outputs
"""
def test_admin_fake_action(self):
self.assertRaises(exceptions.CommandFailed,
self.neutron,
'this-does-neutron-exist')
# NOTE(mestery): Commands in order listed in 'neutron help'
# Optional arguments:
def test_neutron_fake_action(self):
self.assertRaises(exceptions.CommandFailed,
self.neutron,
'this-does-not-exist')
def test_neutron_net_list(self):
net_list = self.parser.listing(self.neutron('net-list'))
self.assertTableStruct(net_list, ['id', 'name', 'subnets'])
def test_neutron_ext_list(self):
ext = self.parser.listing(self.neutron('ext-list'))
self.assertTableStruct(ext, ['alias', 'name'])
def test_neutron_dhcp_agent_list_hosting_net(self):
self.neutron('dhcp-agent-list-hosting-net',
params='private')
def test_neutron_agent_list(self):
agents = self.parser.listing(self.neutron('agent-list'))
field_names = ['id', 'agent_type', 'host', 'alive', 'admin_state_up']
self.assertTableStruct(agents, field_names)
def test_neutron_floatingip_list(self):
self.neutron('floatingip-list')
def test_neutron_meter_label_list(self):
if not self.is_extension_enabled('metering'):
self.skipTest('metering is not enabled')
self.neutron('meter-label-list')
def test_neutron_meter_label_rule_list(self):
if not self.is_extension_enabled('metering'):
self.skipTest('metering is not enabled')
self.neutron('meter-label-rule-list')
def test_neutron_net_external_list(self):
net_ext_list = self.parser.listing(self.neutron('net-external-list'))
self.assertTableStruct(net_ext_list, ['id', 'name', 'subnets'])
def test_neutron_port_list(self):
port_list = self.parser.listing(self.neutron('port-list'))
self.assertTableStruct(port_list, ['id', 'name', 'mac_address',
'fixed_ips'])
def test_neutron_quota_list(self):
self.neutron('quota-list')
def test_neutron_router_list(self):
router_list = self.parser.listing(self.neutron('router-list'))
self.assertTableStruct(router_list, ['id', 'name',
'external_gateway_info'])
def test_neutron_security_group_list(self):
security_grp = self.parser.listing(self.neutron('security-group-list'))
self.assertTableStruct(security_grp, ['id', 'name',
'security_group_rules'])
def test_neutron_security_group_rule_list(self):
security_grp = self.parser.listing(self.neutron
('security-group-rule-list'))
self.assertTableStruct(security_grp, ['id', 'security_group',
'direction', 'ethertype',
'port/protocol', 'remote'])
def test_neutron_subnet_list(self):
subnet_list = self.parser.listing(self.neutron('subnet-list'))
self.assertTableStruct(subnet_list, ['id', 'name', 'cidr',
'allocation_pools'])
def test_neutron_help(self):
help_text = self.neutron('help')
lines = help_text.split('\n')
self.assertFirstLineStartsWith(lines, 'usage: neutron')
commands = []
cmds_start = lines.index('Commands for API v2.0:')
command_pattern = re.compile(r'^ {2}([a-z0-9\-\_]+)')
for line in lines[cmds_start:]:
match = command_pattern.match(line)
if match:
commands.append(match.group(1))
commands = set(commands)
wanted_commands = set(('net-create', 'subnet-list', 'port-delete',
'router-show', 'agent-update', 'help'))
self.assertFalse(wanted_commands - commands)
# Optional arguments:
def test_neutron_version(self):
self.neutron('', flags='--version')
def test_neutron_debug_net_list(self):
self.neutron('net-list', flags='--debug')
def test_neutron_quiet_net_list(self):
self.neutron('net-list', flags='--quiet')

View File

@ -1,36 +0,0 @@
# Copyright 2015 Hewlett-Packard Development Company, L.P
#
# 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 neutronclient.tests.functional import base
class SubnetCreateNeutronClientCLITest(base.ClientTestBase):
def test_create_subnet_net_name_first(self):
self.neutron('net-create', params='netwrk-1')
self.addCleanup(self.neutron, 'net-delete netwrk-1')
self.neutron('subnet-create netwrk-1',
params='--name fake --gateway 192.168.51.1 '
'192.168.51.0/24')
self.addCleanup(self.neutron, 'subnet-delete fake')
subnet_list = self.parser.listing(self.neutron('subnet-list'))
self.assertTableStruct(subnet_list, ['id', 'name', 'cidr',
'allocation_pools'])
found = False
for row in subnet_list:
if row.get('name') == 'fake':
found = True
break
if not found:
self.fail('Created subnet not found in list')

View File

@ -1,2 +0,0 @@
enable_plugin neutron-fwaas https://opendev.org/openstack/neutron-fwaas
enable_service q-fwaas

View File

@ -1,42 +0,0 @@
#!/usr/bin/env bash
set -ex
VENV=${1:-"functional"}
GATE_DEST=$BASE/new
NEUTRONCLIENT_PATH=$GATE_DEST/python-neutronclient
GATE_HOOKS=$NEUTRONCLIENT_PATH/neutronclient/tests/functional/hooks
DEVSTACK_PATH=$GATE_DEST/devstack
LOCAL_CONF=$DEVSTACK_PATH/late-local.conf
DSCONF=/tmp/devstack-tools/bin/dsconf
# Install devstack-tools used to produce local.conf; we can't rely on
# test-requirements.txt because the gate hook is triggered before neutronclient
# is installed
sudo -H pip install virtualenv
virtualenv /tmp/devstack-tools
/tmp/devstack-tools/bin/pip install -U devstack-tools==0.4.0
# Inject config from hook into localrc
function load_rc_hook {
local hook="$1"
local tmpfile
local config
tmpfile=$(tempfile)
config=$(cat $GATE_HOOKS/$hook)
echo "[[local|localrc]]" > $tmpfile
$DSCONF setlc_raw $tmpfile "$config"
$DSCONF merge_lc $LOCAL_CONF $tmpfile
rm -f $tmpfile
}
if [ "$VENV" == "functional-adv-svcs" ]
then
load_rc_hook fwaas
load_rc_hook vpnaas
fi
export DEVSTACK_LOCALCONF=$(cat $LOCAL_CONF)
$BASE/new/devstack-gate/devstack-vm-gate.sh

View File

@ -1,68 +0,0 @@
#!/bin/bash -xe
# 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.
# This script is executed inside post_test_hook function in devstack gate.
SCRIPTS_DIR="/usr/os-testr-env/bin/"
function generate_test_logs {
local path="$1"
# Compress all $path/*.txt files and move the directories holding those
# files to /opt/stack/logs. Files with .log suffix have their
# suffix changed to .txt (so browsers will know to open the compressed
# files and not download them).
if [ -d "$path" ]
then
sudo find $path -iname "*.log" -type f -exec mv {} {}.txt \; -exec gzip -9 {}.txt \;
sudo mv $path/* /opt/stack/logs/
fi
}
function generate_testr_results {
# Give job user rights to access tox logs
sudo -H -u $USER chmod o+rw .
sudo -H -u $USER chmod o+rw -R .stestr
if [ -f ".stestr/0" ] ; then
.tox/$VENV/bin/subunit-1to2 < .stestr/0 > ./stestr.subunit
$SCRIPTS_DIR/subunit2html ./stestr.subunit testr_results.html
gzip -9 ./stestr.subunit
gzip -9 ./testr_results.html
sudo mv ./*.gz /opt/stack/logs/
fi
if [ "$venv" == "functional" ] || [ "$venv" == "functional-adv-svcs" ]
then
generate_test_logs "/tmp/${venv}-logs"
fi
}
export NEUTRONCLIENT_DIR="$BASE/new/python-neutronclient"
sudo chown -R $USER:stack $NEUTRONCLIENT_DIR
# Go to the neutronclient dir
cd $NEUTRONCLIENT_DIR
# Run tests
VENV=${1:-"functional"}
echo "Running neutronclient functional test suite"
set +e
# Preserve env for OS_ credentials
sudo -E -H -u $USER tox -e $VENV
EXIT_CODE=$?
set -e
# Collect and parse result
generate_testr_results
exit $EXIT_CODE

View File

@ -1 +0,0 @@
enable_plugin neutron-vpnaas https://opendev.org/openstack/neutron-vpnaas

View File

@ -1,66 +0,0 @@
# Copyright 2016 Huawei Technologies India Pvt. 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 sys
from neutronclient.neutron.v2_0.bgp import dragentscheduler as bgp_drsched
from neutronclient.tests.unit import test_cli20
from neutronclient.tests.unit import test_cli20_agentschedulers as test_as
BGP_DRAGENT_ID = 'bgp_dragent_id1'
BGP_SPEAKER = 'bgp_speaker_id1'
class CLITestV20DRAgentScheduler(test_as.CLITestV20AgentScheduler):
def test_add_bgp_speaker_to_dragent(self):
resource = 'agent'
cmd = bgp_drsched.AddBGPSpeakerToDRAgent(
test_cli20.MyApp(sys.stdout), None)
args = (BGP_DRAGENT_ID, BGP_SPEAKER)
body = {'bgp_speaker_id': BGP_SPEAKER}
result = {'bgp_speaker_id': 'bgp_speaker_id', }
self._test_add_to_agent(resource, cmd, args,
self.client.BGP_DRINSTANCES,
body, result)
def test_remove_bgp_speaker_from_dragent(self):
resource = 'agent'
cmd = bgp_drsched.RemoveBGPSpeakerFromDRAgent(
test_cli20.MyApp(sys.stdout), None)
args = (BGP_DRAGENT_ID, BGP_SPEAKER)
self._test_remove_from_agent(resource, cmd, args,
self.client.BGP_DRINSTANCES)
def test_list_bgp_speakers_on_dragent(self):
resources = 'bgp_speakers'
cmd = bgp_drsched.ListBGPSpeakersOnDRAgent(
test_cli20.MyApp(sys.stdout), None)
path = ((self.client.agent_path + self.client.BGP_DRINSTANCES) %
BGP_DRAGENT_ID)
self._test_list_resources(resources, cmd, base_args=[BGP_DRAGENT_ID],
path=path)
def test_list_dragents_hosting_bgp_speaker(self):
resources = 'agent'
cmd = bgp_drsched.ListDRAgentsHostingBGPSpeaker(
test_cli20.MyApp(sys.stdout), None)
path = ((self.client.bgp_speaker_path + self.client.BGP_DRAGENTS) %
BGP_DRAGENT_ID)
contents = {self.id_field: 'myid1', 'alive': True}
self._test_list_resources(resources, cmd, base_args=[BGP_DRAGENT_ID],
path=path, response_contents=contents)

View File

@ -1,224 +0,0 @@
# Copyright 2016 Huawei Technologies India Pvt. 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 sys
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0.bgp import peer as bgp_peer
from neutronclient.neutron.v2_0.bgp import speaker as bgp_speaker
from neutronclient.tests.unit import test_cli20
class CLITestV20BGPPeerJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['bgp_peer']
def test_create_bgp_peer_with_mandatory_params(self):
# Create BGP peer with mandatory params.
resource = 'bgp_peer'
cmd = bgp_peer.CreatePeer(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
my_id = 'my-id'
peerip = '1.1.1.1'
remote_asnum = '1'
args = [name,
'--peer-ip', peerip,
'--remote-as', remote_asnum, ]
position_names = ['name', 'peer_ip', 'remote_as',
'auth_type']
position_values = [name, peerip, remote_asnum, 'none']
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def test_create_bgp_peer_with_all_params(self):
# Create BGP peer with all params.
resource = 'bgp_peer'
cmd = bgp_peer.CreatePeer(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
my_id = 'my-id'
peerip = '1.1.1.1'
remote_asnum = '65535'
authType = 'md5'
password = 'abc'
args = [name,
'--peer-ip', peerip,
'--remote-as', remote_asnum,
'--auth-type', authType,
'--password', password]
position_names = ['name', 'peer_ip', 'remote_as',
'auth_type', 'password']
position_values = [name, peerip, remote_asnum, authType, password]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def test_create_bgp_peer_with_invalid_min_remote_asnum(self):
# Create BGP peer with invalid minimum remote-asnum.
resource = 'bgp_peer'
cmd = bgp_peer.CreatePeer(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
my_id = 'my-id'
peerip = '1.1.1.1'
remote_asnum = '0'
args = [name,
'--peer-ip', peerip,
'--remote-as', remote_asnum, ]
position_names = ['name', 'peer_ip', 'remote_as', ]
position_values = [name, peerip, remote_asnum, ]
exc = self.assertRaises(exceptions.CommandError,
self._test_create_resource,
resource, cmd, name, my_id, args,
position_names, position_values)
self.assertEqual('remote-as "0" should be an integer [%s:%s].' %
(bgp_speaker.MIN_AS_NUM, bgp_speaker.MAX_AS_NUM),
str(exc))
def test_create_bgp_peer_with_invalid_max_remote_asnum(self):
# Create BGP peer with invalid maximum remote-asnum.
resource = 'bgp_peer'
cmd = bgp_peer.CreatePeer(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
my_id = 'my-id'
peerip = '1.1.1.1'
remote_asnum = '4294967296'
args = [name,
'--peer-ip', peerip,
'--remote-as', remote_asnum, ]
position_names = ['name', 'peer_ip', 'remote_as',
'auth_type', 'password']
position_values = [name, peerip, remote_asnum, 'none', '']
exc = self.assertRaises(exceptions.CommandError,
self._test_create_resource,
resource, cmd, name, my_id, args,
position_names, position_values)
self.assertEqual('remote-as "4294967296" should be an '
'integer [%s:%s].' %
(bgp_speaker.MIN_AS_NUM, bgp_speaker.MAX_AS_NUM),
str(exc))
def test_create_authenticated_bgp_peer_without_authtype(self):
# Create authenticated BGP peer without auth-type.
resource = 'bgp_peer'
cmd = bgp_peer.CreatePeer(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
my_id = 'my-id'
peerip = '1.1.1.1'
remote_asnum = '2048'
password = 'abc'
args = [name,
'--peer-ip', peerip,
'--remote-as', remote_asnum,
'--password', password]
position_names = ['name', 'peer_ip', 'remote_as', 'password']
position_values = [name, peerip, remote_asnum, password]
exc = self.assertRaises(exceptions.CommandError,
self._test_create_resource,
resource, cmd, name, my_id, args,
position_names, position_values)
self.assertEqual('Must provide auth-type if password is specified.',
str(exc))
def test_create_authenticated_bgp_peer_without_password(self):
# Create authenticated BGP peer without password.
resource = 'bgp_peer'
cmd = bgp_peer.CreatePeer(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
my_id = 'my-id'
peerip = '1.1.1.1'
remote_asnum = '2048'
authType = 'md5'
args = [name,
'--peer-ip', peerip,
'--remote-as', remote_asnum,
'--auth-type', authType]
position_names = ['name', 'peer_ip', 'remote_as', 'auth_type']
position_values = [name, peerip, remote_asnum, authType]
exc = self.assertRaises(exceptions.CommandError,
self._test_create_resource,
resource, cmd, name, my_id, args,
position_names, position_values)
self.assertEqual('Must provide password if auth-type is specified.',
str(exc))
def test_update_bgp_peer(self):
# Update BGP peer:
# myid --advertise-tenant-networks True
# --advertise-floating-ip-host-routes False
resource = 'bgp_peer'
cmd = bgp_peer.UpdatePeer(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'new-name',
'--password', 'abc'],
{'name': 'new-name', 'password': 'abc'})
def test_update_bgp_peer_exception(self):
# Update BGP peer: myid.
resource = 'bgp_peer'
cmd = bgp_peer.UpdatePeer(test_cli20.MyApp(sys.stdout),
None)
self.assertRaises(exceptions.CommandError,
self._test_update_resource,
resource, cmd, 'myid', ['myid'], {})
def test_list_bgp_peer(self):
# List all BGP peers.
resources = "bgp_peers"
cmd = bgp_peer.ListPeers(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True)
# TODO(Vikram): Add test_list_bgp_peer_pagination
def test_list_bgp_peer_sort(self):
# sorted list: bgp-peer-list --sort-key name --sort-key id
# --sort-key asc --sort-key desc
resources = "bgp_peers"
cmd = bgp_peer.ListPeers(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_bgp_peer_limit(self):
# size (1000) limited list: bgp-peer-list -P.
resources = "bgp_peers"
cmd = bgp_peer.ListPeers(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_bgp_peer(self):
# Show BGP peer: --fields id --fields name myid.
resource = 'bgp_peer'
cmd = bgp_peer.ShowPeer(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args,
['id', 'name'])
def test_delete_bgp_peer(self):
# Delete BGP peer: bgp_peer_id.
resource = 'bgp_peer'
cmd = bgp_peer.DeletePeer(test_cli20.MyApp(sys.stdout),
None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)

View File

@ -1,273 +0,0 @@
# Copyright 2016 Huawei Technologies India Pvt. 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 sys
from unittest import mock
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0.bgp import speaker as bgp_speaker
from neutronclient.tests.unit import test_cli20
class CLITestV20BGPSpeakerJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['bgp_speaker']
def test_create_bgp_speaker_with_minimal_options(self):
# Create BGP Speaker with mandatory params.
resource = 'bgp_speaker'
cmd = bgp_speaker.CreateSpeaker(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
my_id = 'my-id'
local_asnum = '1'
args = [name, '--local-as', local_asnum, ]
position_names = ['name', 'local_as', 'ip_version']
position_values = [name, local_asnum, 4]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def test_create_ipv4_bgp_speaker_with_all_params(self):
# Create BGP Speaker with all params.
resource = 'bgp_speaker'
cmd = bgp_speaker.CreateSpeaker(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
my_id = 'my-id'
local_asnum = '1'
args = [name,
'--local-as', local_asnum,
'--ip-version', '4',
'--advertise-floating-ip-host-routes', 'True',
'--advertise-tenant-networks', 'True']
position_names = ['name', 'local_as', 'ip_version',
'advertise_floating_ip_host_routes',
'advertise_tenant_networks']
position_values = [name, local_asnum, 4, 'True', 'True']
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def test_create_ipv6_bgp_speaker_with_all_params(self):
# Create BGP Speaker with all params.
resource = 'bgp_speaker'
cmd = bgp_speaker.CreateSpeaker(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
my_id = 'my-id'
local_asnum = '65535'
args = [name,
'--local-as', local_asnum,
'--ip-version', '6',
'--advertise-floating-ip-host-routes', 'True',
'--advertise-tenant-networks', 'True']
position_names = ['name', 'local_as', 'ip_version',
'advertise_floating_ip_host_routes',
'advertise_tenant_networks']
position_values = [name, local_asnum, 6, 'True', 'True']
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def test_create_bgp_speaker_with_invalid_min_local_asnum(self):
# Create BGP Speaker with invalid minimum local-asnum.
resource = 'bgp_speaker'
cmd = bgp_speaker.CreateSpeaker(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
my_id = 'my-id'
local_asnum = '0'
args = [name,
'--local-as', local_asnum]
position_names = ['name', 'local_as']
position_values = [name, local_asnum]
exc = self.assertRaises(exceptions.CommandError,
self._test_create_resource,
resource, cmd, name, my_id, args,
position_names, position_values)
self.assertEqual('local-as "0" should be an integer [%s:%s].' %
(bgp_speaker.MIN_AS_NUM, bgp_speaker.MAX_AS_NUM),
str(exc))
def test_create_bgp_speaker_with_invalid_max_local_asnum(self):
# Create BGP Speaker with invalid maximum local-asnum.
resource = 'bgp_speaker'
cmd = bgp_speaker.CreateSpeaker(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
my_id = 'my-id'
local_asnum = '4294967296'
args = [name,
'--local-as', local_asnum]
position_names = ['name', 'local_as', ]
position_values = [name, local_asnum, ]
exc = self.assertRaises(exceptions.CommandError,
self._test_create_resource,
resource, cmd, name, my_id, args,
position_names, position_values)
self.assertEqual('local-as "4294967296" should be an '
'integer [%s:%s].' %
(bgp_speaker.MIN_AS_NUM, bgp_speaker.MAX_AS_NUM),
str(exc))
def test_update_bgp_speaker(self):
# Update BGP Speaker:
# myid --advertise-tenant-networks True
# --advertise-floating-ip-host-routes False
resource = 'bgp_speaker'
cmd = bgp_speaker.UpdateSpeaker(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(resource, cmd, 'myid',
['myid',
'--name', 'new-name',
'--advertise-tenant-networks', 'True',
'--advertise-floating-ip-host-routes',
'False'],
{'name': 'new-name',
'advertise_tenant_networks': 'True',
'advertise_floating_ip_host_routes':
'False'})
def test_update_bgp_speaker_exception(self):
# Update BGP Speaker: myid.
resource = 'bgp_speaker'
cmd = bgp_speaker.UpdateSpeaker(test_cli20.MyApp(sys.stdout),
None)
self.assertRaises(exceptions.CommandError,
self._test_update_resource,
resource, cmd, 'myid', ['myid'], {})
def test_list_bgp_speaker(self):
# List all BGP Speakers.
resources = "bgp_speakers"
cmd = bgp_speaker.ListSpeakers(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True)
@mock.patch.object(bgp_speaker.ListSpeakers, "extend_list")
def test_list_bgp_speaker_pagination(self, mock_extend_list):
# List all BGP Speakers with pagination support.
cmd = bgp_speaker.ListSpeakers(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources_with_pagination("bgp_speakers",
cmd)
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
def test_list_bgp_speaker_sort(self):
# sorted list: bgp-speaker-list --sort-key name --sort-key id
# --sort-key asc --sort-key desc
resources = "bgp_speakers"
cmd = bgp_speaker.ListSpeakers(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_bgp_speaker_limit(self):
# size (1000) limited list: bgp-speaker-list -P.
resources = "bgp_speakers"
cmd = bgp_speaker.ListSpeakers(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_bgp_speaker(self):
# Show BGP Speaker: --fields id --fields name myid.
resource = 'bgp_speaker'
cmd = bgp_speaker.ShowSpeaker(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args,
['id', 'name'])
def test_delete_bgp_speaker(self):
# Delete BGP Speaker: bgp_speaker_id.
resource = 'bgp_speaker'
cmd = bgp_speaker.DeleteSpeaker(test_cli20.MyApp(sys.stdout),
None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)
def _test_add_remove_peer(self, action, cmd, args):
"""Add or Remove BGP Peer to/from a BGP Speaker."""
resource = 'bgp_speaker'
subcmd = '%s_bgp_peer' % action
body = {'bgp_peer_id': 'peerid'}
if action == 'add':
retval = {'bgp_peer': 'peerid'}
retval = self.client.serialize(retval)
expected_code = 200
else:
retval = None
expected_code = 204
self._test_update_resource_action(resource, cmd, 'myid',
subcmd, args, body, expected_code,
retval)
def test_add_peer_to_bgp_speaker(self):
# Add peer to BGP speaker: myid peer_id=peerid
cmd = bgp_speaker.AddPeerToSpeaker(test_cli20.MyApp(sys.stdout),
None)
args = ['myid', 'peerid']
self._test_add_remove_peer('add', cmd, args)
def test_remove_peer_from_bgp_speaker(self):
# Remove peer from BGP speaker: myid peer_id=peerid
cmd = bgp_speaker.RemovePeerFromSpeaker(test_cli20.MyApp(sys.stdout),
None)
args = ['myid', 'peerid']
self._test_add_remove_peer('remove', cmd, args)
def _test_add_remove_network(self, action, cmd, args):
# Add or Remove network to/from a BGP Speaker.
resource = 'bgp_speaker'
subcmd = '%s_gateway_network' % action
body = {'network_id': 'netid'}
if action == 'add':
retval = {'network': 'netid'}
retval = self.client.serialize(retval)
expected_code = 200
else:
retval = None
expected_code = 204
self._test_update_resource_action(resource, cmd, 'myid',
subcmd, args, body, expected_code,
retval)
def test_add_network_to_bgp_speaker(self):
# Add peer to BGP speaker: myid network_id=netid
cmd = bgp_speaker.AddNetworkToSpeaker(test_cli20.MyApp(sys.stdout),
None)
args = ['myid', 'netid']
self._test_add_remove_network('add', cmd, args)
def test_remove_network_from_bgp_speaker(self):
# Remove network from BGP speaker: myid network_id=netid
cmd = bgp_speaker.RemoveNetworkFromSpeaker(
test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'netid']
self._test_add_remove_network('remove', cmd, args)
def test_list_routes_advertised_by_a_bgp_speaker(self):
# Retrieve advertised route list
resources = 'advertised_routes'
cmd = bgp_speaker.ListRoutesAdvertisedBySpeaker(
test_cli20.MyApp(sys.stdout), None)
bs_id = 'bgp_speaker_id1'
path = ((self.client.bgp_speaker_path + '/get_advertised_routes') %
bs_id)
self._test_list_resources(resources, cmd, base_args=[bs_id],
path=path)

View File

@ -1,154 +0,0 @@
# 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.
#
import sys
from neutronclient.neutron.v2_0.flavor import flavor
from neutronclient.tests.unit import test_cli20
class CLITestV20FlavorJSON(test_cli20.CLITestV20Base):
def setUp(self):
"""Prepare test environment."""
super(CLITestV20FlavorJSON, self).setUp(plurals={'flavors': 'flavor'})
self.register_non_admin_status_resource('flavor')
self.register_non_admin_status_resource('service_profile')
def test_create_flavor_with_missing_params(self):
"""Create test flavor with missing parameters."""
resource = 'flavor'
cmd = flavor.CreateFlavor(
test_cli20.MyApp(sys.stdout), None)
name = 'Test flavor'
myid = 'myid'
position_names = []
position_values = []
args = []
self.assertRaises(
SystemExit, self._test_create_resource,
resource, cmd, name, myid, args, position_names, position_values)
def test_create_flavor_with_mandatory_params(self):
"""Create test flavor with minimal parameters."""
resource = 'flavor'
cmd = flavor.CreateFlavor(
test_cli20.MyApp(sys.stdout), None)
name = 'Test flavor'
myid = 'myid'
service_type = 'DUMMY'
# Defaults are returned in body
position_names = ['name', 'service_type']
position_values = [name, service_type]
args = [name, service_type]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_flavor_with_optional_params(self):
"""Create test flavor including optional parameters."""
resource = 'flavor'
cmd = flavor.CreateFlavor(
test_cli20.MyApp(sys.stdout), None)
name = 'Test flavor'
myid = 'myid'
service_type = 'DUMMY'
description = 'Test description'
position_names = ['name', 'service_type', 'description', 'enabled']
position_values = [name, service_type, description, 'False']
args = [name, service_type,
'--description', description,
'--enabled=False']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_delete_flavor(self):
"""Delete flavor."""
resource = 'flavor'
cmd = flavor.DeleteFlavor(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)
def test_list_flavors(self):
"""List flavors test."""
resources = 'flavors'
cmd = flavor.ListFlavor(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_flavors_with_pagination(self):
"""List flavors test with pagination."""
resources = 'flavors'
cmd = flavor.ListFlavor(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_flavors_with_sort(self):
"""List flavors test with sorting by name and id."""
resources = 'flavors'
cmd = flavor.ListFlavor(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_show_flavor(self):
"""Show flavor test."""
resource = 'flavor'
cmd = flavor.ShowFlavor(
test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_update_flavor_with_name(self):
"""Update flavor test."""
resource = 'flavor'
cmd = flavor.UpdateFlavor(
test_cli20.MyApp(sys.stdout), None)
newname = 'Test New Name'
newdescription = 'New Description'
args = ['--name', newname,
'--description', newdescription,
'--enabled', 'False', self.test_id]
self._test_update_resource(resource, cmd, self.test_id, args,
{'name': newname,
'description': newdescription,
'enabled': 'False'})
def test_associate_flavor(self):
"""Associate flavor test."""
resource = 'service_profile'
cmd = flavor.AssociateFlavor(test_cli20.MyApp(sys.stdout), None)
flavor_id = 'flavor-id'
profile_id = 'profile-id'
name = ''
args = [flavor_id, profile_id]
position_names = ['id']
position_values = [profile_id]
self._test_create_resource(resource, cmd, name, profile_id, args,
position_names, position_values,
cmd_resource='flavor_profile_binding',
parent_id=flavor_id)
def test_disassociate_flavor(self):
"""Disassociate flavor test."""
resource = 'flavor_profile_binding'
cmd = flavor.DisassociateFlavor(test_cli20.MyApp(sys.stdout), None)
flavor_id = 'flavor-id'
profile_id = 'profile-id'
args = [flavor_id, profile_id]
self._test_delete_resource(resource, cmd, profile_id, args,
parent_id=flavor_id)

View File

@ -1,122 +0,0 @@
# 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.
#
import sys
from neutronclient.neutron.v2_0.flavor import flavor_profile
from neutronclient.tests.unit import test_cli20
class CLITestV20FlavorProfileJSON(test_cli20.CLITestV20Base):
def setUp(self):
"""Prepare test environment."""
super(CLITestV20FlavorProfileJSON, self).setUp(
plurals={'service_profiles': 'service_profile'})
self.register_non_admin_status_resource('service_profile')
def test_create_flavor_profile_with_mandatory_params(self):
"""Create test flavor profile test."""
resource = 'service_profile'
cmd = flavor_profile.CreateFlavorProfile(
test_cli20.MyApp(sys.stdout), None)
name = ''
description = 'Test flavor profile'
myid = 'myid'
metainfo = "{'a':'b'}"
# Defaults are returned in body
position_names = ['description', 'metainfo']
position_values = [description, metainfo]
args = ['--description', description, '--metainfo', metainfo]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_flavor_profile_with_optional_params(self):
"""Create test flavor profile disabled test."""
resource = 'service_profile'
cmd = flavor_profile.CreateFlavorProfile(
test_cli20.MyApp(sys.stdout), None)
name = ''
description = 'Test flavor profile - disabled'
myid = 'myid'
driver = 'mydriver'
metainfo = "{'a':'b'}"
position_names = ['description', 'driver', 'metainfo', 'enabled']
position_values = [description, driver, metainfo, 'False']
args = ['--description', description, '--driver', driver,
'--metainfo', metainfo, '--enabled=False']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_list_flavor_profiles(self):
"""List flavor profiles test."""
resources = 'service_profiles'
cmd = flavor_profile.ListFlavorProfile(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_flavor_profiles_with_pagination(self):
"""List flavor profiles test with pagination."""
resources = 'service_profiles'
cmd = flavor_profile.ListFlavorProfile(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_flavor_profiles_with_sort(self):
"""List flavor profiles test with sort by description."""
resources = 'service_profiles'
cmd = flavor_profile.ListFlavorProfile(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["description"],
sort_dir=["asc"])
def test_show_flavor_profile(self):
"""Show flavor profile test."""
resource = 'service_profile'
cmd = flavor_profile.ShowFlavorProfile(
test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_update_flavor_profile(self):
"""Update flavor profile test."""
resource = 'service_profile'
cmd = flavor_profile.UpdateFlavorProfile(
test_cli20.MyApp(sys.stdout), None)
newdescription = 'Test new description'
newdriver = 'NewDriver'
newmetainfo = "{'c':'d'}"
newenabled = "False"
args = ['--description', newdescription,
'--driver', newdriver,
'--metainfo', newmetainfo,
'--enabled', newenabled,
self.test_id]
self._test_update_resource(resource, cmd, self.test_id, args,
{'description': newdescription,
'driver': newdriver,
'metainfo': newmetainfo,
'enabled': newenabled})
def test_delete_flavor_profile(self):
"""Delete flavor profile."""
resource = 'service_profile'
cmd = flavor_profile.DeleteFlavorProfile(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)

View File

@ -1,170 +0,0 @@
# Copyright 2013 Big Switch Networks 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 sys
from neutronclient.neutron.v2_0.fw import firewall
from neutronclient.tests.unit import test_cli20
class CLITestV20FirewallJSON(test_cli20.CLITestV20Base):
def test_create_firewall_with_mandatory_params(self):
# firewall-create with mandatory (none) params.
resource = 'firewall'
cmd = firewall.CreateFirewall(test_cli20.MyApp(sys.stdout), None)
name = ''
tenant_id = 'my-tenant'
my_id = 'my-id'
policy_id = 'my-policy-id'
args = ['--tenant-id', tenant_id, policy_id, ]
position_names = ['firewall_policy_id', ]
position_values = [policy_id, ]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
admin_state_up=True, tenant_id=tenant_id)
def test_create_firewall_with_all_params(self):
# firewall-create with all params set.
resource = 'firewall'
cmd = firewall.CreateFirewall(test_cli20.MyApp(sys.stdout), None)
name = 'my-name'
description = 'my-desc'
policy_id = 'my-policy-id'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = ['--description', description,
'--admin-state-down',
'--tenant-id', tenant_id,
policy_id]
position_names = ['firewall_policy_id', ]
position_values = [policy_id, ]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
description=description,
admin_state_up=False,
tenant_id=tenant_id)
def test_create_firewall_with_routers(self):
resource = 'firewall'
cmd = firewall.CreateFirewall(test_cli20.MyApp(sys.stdout), None)
name = 'my-name'
policy_id = 'my-policy-id'
my_id = 'my-id'
args = ['--router', 'fake-id', '--router', 'fake-name', policy_id]
router_ids = ['fake-id', 'fake-name']
position_names = ['firewall_policy_id', 'router_ids']
position_values = [policy_id, router_ids]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def test_list_firewalls(self):
# firewall-list.
resources = "firewalls"
cmd = firewall.ListFirewall(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_firewalls_pagination(self):
# firewall-list with pagination.
resources = "firewalls"
cmd = firewall.ListFirewall(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_firewalls_sort(self):
# sorted list: firewall-list --sort-key name --sort-key id
# --sort-key asc --sort-key desc
resources = "firewalls"
cmd = firewall.ListFirewall(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_firewalls_limit(self):
# size (1000) limited list: firewall-list -P.
resources = "firewalls"
cmd = firewall.ListFirewall(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_firewall_id(self):
# firewall-show test_id.
resource = 'firewall'
cmd = firewall.ShowFirewall(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_show_firewall_id_name(self):
# firewall-show.
resource = 'firewall'
cmd = firewall.ShowFirewall(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_update_firewall(self):
# firewall-update myid --name newname --tags a b.
resource = 'firewall'
cmd = firewall.UpdateFirewall(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'newname'],
{'name': 'newname', })
def test_update_firewall_using_policy_name(self):
# firewall-update myid --policy newpolicy.
resource = 'firewall'
cmd = firewall.UpdateFirewall(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--policy', 'newpolicy'],
{'firewall_policy_id': 'newpolicy'})
def test_update_firewall_with_routers(self):
resource = 'firewall'
cmd = firewall.UpdateFirewall(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(
resource, cmd, 'myid',
['myid', '--router', 'fake-id', '--router', 'fake-name'],
{'router_ids': ['fake-id', 'fake-name']})
def test_update_firewall_with_no_routers(self):
resource = 'firewall'
cmd = firewall.UpdateFirewall(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(
resource, cmd, 'myid',
['myid', '--no-routers'], {'router_ids': []})
def test_update_firewall_with_bad_router_options(self):
resource = 'firewall'
cmd = firewall.UpdateFirewall(test_cli20.MyApp(sys.stdout), None)
self.assertRaises(
SystemExit,
self._test_update_resource,
resource, cmd, 'myid',
['myid', '--no-routers', '--router', 'fake-id'], {})
def test_delete_firewall(self):
# firewall-delete my-id.
resource = 'firewall'
cmd = firewall.DeleteFirewall(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)
def test_update_firewall_admin_state(self):
# firewall-update myid --admin-state-up True.
resource = 'firewall'
cmd = firewall.UpdateFirewall(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--admin-state-up', 'True'],
{'admin_state_up': 'True'})

View File

@ -1,228 +0,0 @@
# Copyright 2013 Big Switch Networks 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 sys
from unittest import mock
from neutronclient.neutron.v2_0.fw import firewallpolicy
from neutronclient import shell
from neutronclient.tests.unit import test_cli20
class CLITestV20FirewallPolicyJSON(test_cli20.CLITestV20Base):
def setUp(self):
super(CLITestV20FirewallPolicyJSON, self).setUp()
def test_create_firewall_policy_with_mandatory_params(self):
# firewall-policy-create with mandatory (none) params only.
resource = 'firewall_policy'
cmd = firewallpolicy.CreateFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
tenant_id = 'my-tenant'
name = 'my-name'
my_id = 'myid'
args = ['--tenant-id', tenant_id,
'--admin-state_up',
name, ]
position_names = ['name', ]
position_values = [name, ]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
admin_state_up=True, tenant_id=tenant_id)
def test_create_firewall_policy_with_all_params(self):
# firewall-policy-create with rule param of misc format.
resource = 'firewall_policy'
cmd = firewallpolicy.CreateFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
description = 'my-desc'
firewall_rules_res = ['rule_id1', 'rule_id2']
tenant_id = 'my-tenant'
my_id = 'myid'
position_names = ['name', ]
position_values = [name, ]
# check for both str and unicode format firewall_rules_arg
for firewall_rules_arg in ['rule_id1 rule_id2', u'rule_id1 rule_id2']:
args = ['--description', description,
'--shared',
'--firewall-rules', firewall_rules_arg,
'--audited',
'--tenant-id', tenant_id,
'--admin-state_up',
name]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
description=description, shared=True,
firewall_rules=firewall_rules_res,
audited=True, admin_state_up=True,
tenant_id=tenant_id)
def test_list_firewall_policies(self):
# firewall-policy-list.
resources = "firewall_policies"
cmd = firewallpolicy.ListFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True)
def test_list_firewall_policies_pagination(self):
# firewall-policy-list."""
resources = "firewall_policies"
cmd = firewallpolicy.ListFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_firewall_policies_sort(self):
# sorted list: firewall-policy-list --sort-key name --sort-key id
# --sort-key asc --sort-key desc
resources = "firewall_policies"
cmd = firewallpolicy.ListFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_firewall_policies_limit(self):
# size (1000) limited list: firewall-policy-list -P.
resources = "firewall_policies"
cmd = firewallpolicy.ListFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_firewall_policy_id(self):
# firewall-policy-show test_id.
resource = 'firewall_policy'
cmd = firewallpolicy.ShowFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_show_firewall_policy_id_name(self):
# firewall-policy-show.
resource = 'firewall_policy'
cmd = firewallpolicy.ShowFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_update_firewall_policy(self):
# firewall-policy-update myid --name newname.
resource = 'firewall_policy'
cmd = firewallpolicy.UpdateFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'newname'],
{'name': 'newname', })
def test_update_firewall_policy_with_rules(self):
# firewall-policy-update myid --firewall-rules "rule1 rule2".
resource = 'firewall_policy'
cmd = firewallpolicy.UpdateFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
firewall_rules_arg = u'rule_id3 rule_id4'
firewall_rules_res = ['rule_id3', 'rule_id4']
self._test_update_resource(
resource, cmd, 'myid',
['myid', '--firewall-rules', firewall_rules_arg],
{'firewall_rules': firewall_rules_res, })
def test_delete_firewall_policy(self):
# firewall-policy-delete my-id.
resource = 'firewall_policy'
cmd = firewallpolicy.DeleteFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
my_id = 'myid1'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)
def test_insert_firewall_rule(self):
# firewall-policy-insert-rule myid newruleid --insert-before ruleAid
# --insert-after ruleBid
resource = 'firewall_policy'
cmd = firewallpolicy.FirewallPolicyInsertRule(
test_cli20.MyApp(sys.stdout),
None)
myid = 'myid'
args = ['myid', 'newrule',
'--insert-before', 'rule2',
'--insert-after', 'rule1']
extrafields = {'firewall_rule_id': 'newrule',
'insert_before': 'rule2',
'insert_after': 'rule1'}
body = extrafields
path = getattr(self.client, resource + "_insert_path")
cmd_parser = cmd.get_parser(resource + "_insert_rule")
resp = (test_cli20.MyResp(204), None)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request:
shell.run_command(cmd, cmd_parser, args)
self.assert_mock_multiple_calls_with_same_arguments(
mock_get_client, mock.call(), 4)
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path % myid),
self.client),
'PUT', body=test_cli20.MyComparator(body, self.client),
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
def test_remove_firewall_rule(self):
# firewall-policy-remove-rule myid ruleid
resource = 'firewall_policy'
cmd = firewallpolicy.FirewallPolicyRemoveRule(
test_cli20.MyApp(sys.stdout),
None)
myid = 'myid'
args = ['myid', 'removerule']
extrafields = {'firewall_rule_id': 'removerule', }
body = extrafields
path = getattr(self.client, resource + "_remove_path")
cmd_parser = cmd.get_parser(resource + "_remove_rule")
resp = (test_cli20.MyResp(204), None)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request:
shell.run_command(cmd, cmd_parser, args)
self.assert_mock_multiple_calls_with_same_arguments(
mock_get_client, mock.call(), 2)
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path % myid),
self.client),
'PUT', body=test_cli20.MyComparator(body, self.client),
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
def test_update_firewall_policy_name_shared_audited(self):
# firewall-policy-update myid --name newname2 --shared --audited
resource = 'firewall_policy'
cmd = firewallpolicy.UpdateFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'newname2',
'--shared', 'True', '--audited', 'True'],
{'name': 'newname2',
'shared': 'True', 'audited': 'True'})

View File

@ -1,251 +0,0 @@
# Copyright 2013 Big Switch Networks 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 sys
from neutronclient.neutron.v2_0.fw import firewallrule
from neutronclient.tests.unit import test_cli20
class CLITestV20FirewallRuleJSON(test_cli20.CLITestV20Base):
def _test_create_firewall_rule_with_mandatory_params(self, enabled):
# firewall-rule-create with mandatory (none) params only.
resource = 'firewall_rule'
cmd = firewallrule.CreateFirewallRule(test_cli20.MyApp(sys.stdout),
None)
tenant_id = 'my-tenant'
name = ''
my_id = 'myid'
protocol = 'tcp'
action = 'allow'
ip_version = 4
args = ['--tenant-id', tenant_id,
'--admin-state-up',
'--protocol', protocol,
'--action', action,
'--enabled', enabled]
position_names = []
position_values = []
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
protocol=protocol, action=action,
enabled=enabled, tenant_id=tenant_id,
ip_version=ip_version)
def test_create_enabled_firewall_rule_with_mandatory_params_lcase(self):
self._test_create_firewall_rule_with_mandatory_params(enabled='true')
def test_create_disabled_firewall_rule_with_mandatory_params_lcase(self):
self._test_create_firewall_rule_with_mandatory_params(enabled='false')
def test_create_enabled_firewall_rule_with_mandatory_params(self):
self._test_create_firewall_rule_with_mandatory_params(enabled='True')
def test_create_disabled_firewall_rule_with_mandatory_params(self):
self._test_create_firewall_rule_with_mandatory_params(enabled='False')
def _setup_create_firewall_rule_with_all_params(
self, protocol='tcp', protocol_cli=None,
action='allow', action_cli=None, ip_version='4'):
# firewall-rule-create with all params set.
resource = 'firewall_rule'
cmd = firewallrule.CreateFirewallRule(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
description = 'my-desc'
source_ip = '192.168.1.0/24'
destination_ip = '192.168.2.0/24'
source_port = '0:65535'
destination_port = '0:65535'
tenant_id = 'my-tenant'
my_id = 'myid'
enabled = 'True'
args = ['--description', description,
'--shared',
'--protocol', protocol_cli or protocol,
'--ip-version', ip_version,
'--source-ip-address', source_ip,
'--destination-ip-address', destination_ip,
'--source-port', source_port,
'--destination-port', destination_port,
'--action', action_cli or action,
'--enabled', enabled,
'--admin-state-up',
'--tenant-id', tenant_id]
position_names = []
position_values = []
if protocol == 'any':
protocol = None
if ip_version == '4' or ip_version == '6':
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
description=description, shared=True,
protocol=protocol,
ip_version=int(ip_version),
source_ip_address=source_ip,
destination_ip_address=destination_ip,
source_port=source_port,
destination_port=destination_port,
action=action, enabled='True',
tenant_id=tenant_id)
else:
self.assertRaises(SystemExit, self._test_create_resource,
resource, cmd, name, my_id, args,
position_names, position_values,
ip_version=int(ip_version),
source_ip_address=source_ip,
destination_ip_address=destination_ip,
source_port=source_port,
destination_port=destination_port,
action=action, enabled='True',
tenant_id=tenant_id)
def test_create_firewall_rule_with_all_params(self):
self._setup_create_firewall_rule_with_all_params()
def test_create_firewall_rule_with_proto_any(self):
self._setup_create_firewall_rule_with_all_params(protocol='any')
def test_create_firewall_rule_with_IP_version_6(self):
self._setup_create_firewall_rule_with_all_params(ip_version='6')
def test_create_firewall_rule_with_invalid_IP_version(self):
self._setup_create_firewall_rule_with_all_params(ip_version='5')
def test_create_firewall_rule_with_proto_action_upper_capitalized(self):
for protocol in ('TCP', 'Tcp', 'ANY', 'AnY'):
self._setup_create_firewall_rule_with_all_params(
protocol=protocol.lower(),
protocol_cli=protocol)
for action in ('Allow', 'DENY', 'reject'):
self._setup_create_firewall_rule_with_all_params(
action=action.lower(),
action_cli=action)
def test_list_firewall_rules(self):
# firewall-rule-list.
resources = "firewall_rules"
cmd = firewallrule.ListFirewallRule(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True)
def test_list_firewall_rules_pagination(self):
# firewall-rule-list.
resources = "firewall_rules"
cmd = firewallrule.ListFirewallRule(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_firewall_rules_sort(self):
# firewall-rule-list --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = "firewall_rules"
cmd = firewallrule.ListFirewallRule(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_firewall_rules_limit(self):
# firewall-rule-list -P."""
resources = "firewall_rules"
cmd = firewallrule.ListFirewallRule(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_firewall_rule_id(self):
# firewall-rule-show test_id.
resource = 'firewall_rule'
cmd = firewallrule.ShowFirewallRule(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_show_firewall_rule_id_name(self):
# firewall-rule-show.
resource = 'firewall_rule'
cmd = firewallrule.ShowFirewallRule(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_update_firewall_rule(self):
# firewall-rule-update myid --name newname.
resource = 'firewall_rule'
cmd = firewallrule.UpdateFirewallRule(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'newname'],
{'name': 'newname', })
# firewall-rule-update myid --protocol any.
self._test_update_resource(resource, cmd, 'myid',
['myid', '--protocol', 'any'],
{'protocol': None, })
# firewall-rule-update myid --description any
self._test_update_resource(resource, cmd, 'myid',
['myid', '--description', 'any'],
{'description': 'any', })
# firewall-rule-update myid --source_ip_address 192.192.192.192
self._test_update_resource(resource, cmd, 'myid',
['myid', '--source_ip_address',
'192.192.192.192'],
{'source_ip_address': '192.192.192.192', })
# firewall-rule-update myid --source_port 32767
self._test_update_resource(resource, cmd, 'myid',
['myid', '--source_port', '32767'],
{'source_port': '32767', })
# firewall-rule-update myid --destination_ip_address 0.1.0.1
self._test_update_resource(resource, cmd, 'myid',
['myid', '--destination_ip_address',
'0.1.0.1'],
{'destination_ip_address': '0.1.0.1', })
# firewall-rule-update myid --destination_port 65432
self._test_update_resource(resource, cmd, 'myid',
['myid', '--destination_port',
'65432'],
{'destination_port': '65432', })
# firewall-rule-update myid --enabled False
self._test_update_resource(resource, cmd, 'myid',
['myid', '--enabled', 'False'],
{'enabled': 'False', })
# firewall-rule-update myid --action reject
self._test_update_resource(resource, cmd, 'myid',
['myid', '--action', 'reject'],
{'action': 'reject', })
# firewall-rule-update myid --shared false
self._test_update_resource(resource, cmd, 'myid',
['myid', '--shared', 'false'],
{'shared': 'false', })
def test_delete_firewall_rule(self):
# firewall-rule-delete my-id.
resource = 'firewall_rule'
cmd = firewallrule.DeleteFirewallRule(test_cli20.MyApp(sys.stdout),
None)
my_id = 'myid1'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)

View File

@ -1,202 +0,0 @@
# 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 sys
from unittest import mock
from neutronclient.neutron.v2_0.lb import healthmonitor
from neutronclient.tests.unit import test_cli20
class CLITestV20LbHealthmonitorJSON(test_cli20.CLITestV20Base):
def test_create_healthmonitor_with_mandatory_params(self):
# lb-healthmonitor-create with mandatory params only.
resource = 'health_monitor'
cmd = healthmonitor.CreateHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
admin_state_up = False
delay = '60'
max_retries = '2'
timeout = '10'
type = 'TCP'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = ['--admin-state-down',
'--delay', delay,
'--max-retries', max_retries,
'--timeout', timeout,
'--type', type,
'--tenant-id', tenant_id]
position_names = ['admin_state_up', 'delay', 'max_retries', 'timeout',
'type', 'tenant_id']
position_values = [admin_state_up, delay, max_retries, timeout, type,
tenant_id]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values)
def test_create_healthmonitor_with_all_params(self):
# lb-healthmonitor-create with all params set.
resource = 'health_monitor'
cmd = healthmonitor.CreateHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
admin_state_up = False
delay = '60'
expected_codes = '200-202,204'
http_method = 'HEAD'
max_retries = '2'
timeout = '10'
type = 'TCP'
tenant_id = 'my-tenant'
url_path = '/health'
my_id = 'my-id'
args = ['--admin-state-down',
'--delay', delay,
'--expected-codes', expected_codes,
'--http-method', http_method,
'--max-retries', max_retries,
'--timeout', timeout,
'--type', type,
'--tenant-id', tenant_id,
'--url-path', url_path]
position_names = ['admin_state_up', 'delay',
'expected_codes', 'http_method',
'max_retries', 'timeout',
'type', 'tenant_id', 'url_path']
position_values = [admin_state_up, delay,
expected_codes, http_method,
max_retries, timeout,
type, tenant_id, url_path]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values)
def test_list_healthmonitors(self):
# lb-healthmonitor-list.
resources = "health_monitors"
cmd = healthmonitor.ListHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True)
def test_list_healthmonitors_pagination(self):
# lb-healthmonitor-list.
resources = "health_monitors"
cmd = healthmonitor.ListHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_healthmonitors_sort(self):
# lb-healthmonitor-list --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = "health_monitors"
cmd = healthmonitor.ListHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_healthmonitors_limit(self):
# lb-healthmonitor-list -P.
resources = "health_monitors"
cmd = healthmonitor.ListHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_healthmonitor_id(self):
# lb-healthmonitor-show test_id.
resource = 'health_monitor'
cmd = healthmonitor.ShowHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_update_health_monitor(self):
# lb-healthmonitor-update myid --name myname --tags a b.
resource = 'health_monitor'
cmd = healthmonitor.UpdateHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--timeout', '5'],
{'timeout': '5', })
def test_delete_healthmonitor(self):
# lb-healthmonitor-delete my-id."""
resource = 'health_monitor'
cmd = healthmonitor.DeleteHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)
def test_associate_healthmonitor(self):
cmd = healthmonitor.AssociateHealthMonitor(
test_cli20.MyApp(sys.stdout),
None)
resource = 'health_monitor'
health_monitor_id = 'hm-id'
pool_id = 'p_id'
args = [health_monitor_id, pool_id]
body = {resource: {'id': health_monitor_id}}
result = {resource: {'id': health_monitor_id}, }
result_str = self.client.serialize(result)
path = getattr(self.client,
"associate_pool_health_monitors_path") % pool_id
return_tup = (test_cli20.MyResp(200), result_str)
cmd_parser = cmd.get_parser('test_' + resource)
parsed_args = cmd_parser.parse_args(args)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=return_tup) as mock_request:
cmd.run(parsed_args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.end_url(path), 'POST',
body=test_cli20.MyComparator(body, self.client),
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
def test_disassociate_healthmonitor(self):
cmd = healthmonitor.DisassociateHealthMonitor(
test_cli20.MyApp(sys.stdout),
None)
resource = 'health_monitor'
health_monitor_id = 'hm-id'
pool_id = 'p_id'
args = [health_monitor_id, pool_id]
path = (getattr(self.client,
"disassociate_pool_health_monitors_path") %
{'pool': pool_id, 'health_monitor': health_monitor_id})
return_tup = (test_cli20.MyResp(204), None)
cmd_parser = cmd.get_parser('test_' + resource)
parsed_args = cmd_parser.parse_args(args)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=return_tup) as mock_request:
cmd.run(parsed_args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.end_url(path), 'DELETE',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))

View File

@ -1,118 +0,0 @@
# 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 sys
from neutronclient.neutron.v2_0.lb import member
from neutronclient.tests.unit import test_cli20
class CLITestV20LbMemberJSON(test_cli20.CLITestV20Base):
def setUp(self):
super(CLITestV20LbMemberJSON, self).setUp(plurals={'tags': 'tag'})
def test_create_member(self):
# lb-member-create with mandatory params only.
resource = 'member'
cmd = member.CreateMember(test_cli20.MyApp(sys.stdout), None)
address = '10.0.0.1'
port = '8080'
tenant_id = 'my-tenant'
my_id = 'my-id'
pool_id = 'pool-id'
args = ['--address', address, '--protocol-port', port,
'--tenant-id', tenant_id, pool_id]
position_names = ['address', 'protocol_port', 'tenant_id', 'pool_id',
'admin_state_up']
position_values = [address, port, tenant_id, pool_id, True]
self._test_create_resource(resource, cmd, None, my_id, args,
position_names, position_values,
admin_state_up=None)
def test_create_member_all_params(self):
# lb-member-create with all available params.
resource = 'member'
cmd = member.CreateMember(test_cli20.MyApp(sys.stdout), None)
address = '10.0.0.1'
admin_state_up = False
port = '8080'
weight = '1'
tenant_id = 'my-tenant'
my_id = 'my-id'
pool_id = 'pool-id'
args = ['--address', address, '--admin-state-down',
'--protocol-port', port, '--weight', weight,
'--tenant-id', tenant_id, pool_id]
position_names = [
'address', 'admin_state_up', 'protocol_port', 'weight',
'tenant_id', 'pool_id'
]
position_values = [address, admin_state_up, port, weight,
tenant_id, pool_id]
self._test_create_resource(resource, cmd, None, my_id, args,
position_names, position_values,
admin_state_up=None)
def test_list_members(self):
# lb-member-list.
resources = "members"
cmd = member.ListMember(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_members_pagination(self):
# lb-member-list.
resources = "members"
cmd = member.ListMember(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_members_sort(self):
# lb-member-list --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = "members"
cmd = member.ListMember(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_members_limit(self):
# lb-member-list -P.
resources = "members"
cmd = member.ListMember(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_member_id(self):
# lb-member-show test_id.
resource = 'member'
cmd = member.ShowMember(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_update_member(self):
# lb-member-update myid --name myname --tags a b.
resource = 'member'
cmd = member.UpdateMember(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--tags', 'a', 'b'],
{'name': 'myname', 'tags': ['a', 'b'], })
def test_delete_member(self):
# lb-member-delete my-id.
resource = 'member'
cmd = member.DeleteMember(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)

View File

@ -1,166 +0,0 @@
# 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 sys
from unittest import mock
from neutronclient.neutron.v2_0.lb import pool
from neutronclient.tests.unit import test_cli20
class CLITestV20LbPoolJSON(test_cli20.CLITestV20Base):
def test_create_pool_with_mandatory_params(self):
# lb-pool-create with mandatory params only.
resource = 'pool'
cmd = pool.CreatePool(test_cli20.MyApp(sys.stdout), None)
name = 'my-name'
lb_method = 'ROUND_ROBIN'
protocol = 'HTTP'
subnet_id = 'subnet-id'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = ['--lb-method', lb_method,
'--name', name,
'--protocol', protocol,
'--subnet-id', subnet_id,
'--tenant-id', tenant_id]
position_names = ['admin_state_up', 'lb_method', 'name',
'protocol', 'subnet_id', 'tenant_id']
position_values = [True, lb_method, name,
protocol, subnet_id, tenant_id]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def test_create_pool_with_all_params(self):
# lb-pool-create with all params set.
resource = 'pool'
cmd = pool.CreatePool(test_cli20.MyApp(sys.stdout), None)
name = 'my-name'
description = 'my-desc'
lb_method = 'ROUND_ROBIN'
protocol = 'HTTP'
subnet_id = 'subnet-id'
tenant_id = 'my-tenant'
my_id = 'my-id'
provider = 'lbaas'
args = ['--admin-state-down',
'--description', description,
'--lb-method', lb_method,
'--name', name,
'--protocol', protocol,
'--subnet-id', subnet_id,
'--tenant-id', tenant_id,
'--provider', provider]
position_names = ['admin_state_up', 'description', 'lb_method', 'name',
'protocol', 'subnet_id', 'tenant_id', 'provider']
position_values = [False, description, lb_method, name,
protocol, subnet_id, tenant_id, provider]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def test_list_pools(self):
# lb-pool-list.
resources = "pools"
cmd = pool.ListPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_pools_pagination(self):
# lb-pool-list.
resources = "pools"
cmd = pool.ListPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_pools_sort(self):
# lb-pool-list --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = "pools"
cmd = pool.ListPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_pools_limit(self):
# lb-pool-list -P.
resources = "pools"
cmd = pool.ListPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_pool_id(self):
# lb-pool-show test_id.
resource = 'pool'
cmd = pool.ShowPool(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_show_pool_id_name(self):
# lb-pool-show.
resource = 'pool'
cmd = pool.ShowPool(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_update_pool(self):
# lb-pool-update myid --name newname --tags a b.
resource = 'pool'
cmd = pool.UpdatePool(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'newname'],
{'name': 'newname', })
def test_delete_pool(self):
# lb-pool-delete my-id.
resource = 'pool'
cmd = pool.DeletePool(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)
def test_retrieve_pool_stats(self):
# lb-pool-stats test_id.
resource = 'pool'
cmd = pool.RetrievePoolStats(test_cli20.MyApp(sys.stdout), None)
my_id = self.test_id
fields = ['bytes_in', 'bytes_out']
args = ['--fields', 'bytes_in', '--fields', 'bytes_out', my_id]
query = "&".join(["fields=%s" % field for field in fields])
expected_res = {'stats': {'bytes_in': '1234', 'bytes_out': '4321'}}
resstr = self.client.serialize(expected_res)
path = getattr(self.client, "pool_path_stats")
return_tup = (test_cli20.MyResp(200), resstr)
cmd_parser = cmd.get_parser("test_" + resource)
parsed_args = cmd_parser.parse_args(args)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=return_tup) as mock_request:
cmd.run(parsed_args)
self.assert_mock_multiple_calls_with_same_arguments(
mock_get_client, mock.call(), 2)
mock_request.assert_called_once_with(
test_cli20.end_url(path % my_id, query), 'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
_str = self.fake_stdout.make_string()
self.assertIn('bytes_in', _str)
self.assertIn('bytes_out', _str)

View File

@ -1,206 +0,0 @@
# 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 sys
from neutronclient.neutron.v2_0.lb import vip
from neutronclient.tests.unit import test_cli20
class CLITestV20LbVipJSON(test_cli20.CLITestV20Base):
def setUp(self):
super(CLITestV20LbVipJSON, self).setUp(plurals={'tags': 'tag'})
def test_create_vip_with_mandatory_params(self):
# lb-vip-create with all mandatory params.
resource = 'vip'
cmd = vip.CreateVip(test_cli20.MyApp(sys.stdout), None)
pool_id = 'my-pool-id'
name = 'my-name'
subnet_id = 'subnet-id'
protocol_port = '1000'
protocol = 'TCP'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = ['--name', name,
'--protocol-port', protocol_port,
'--protocol', protocol,
'--subnet-id', subnet_id,
'--tenant-id', tenant_id,
pool_id]
position_names = ['pool_id', 'name', 'protocol_port', 'protocol',
'subnet_id', 'tenant_id']
position_values = [pool_id, name, protocol_port, protocol,
subnet_id, tenant_id]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
admin_state_up=True)
def test_create_vip_with_all_params(self):
# lb-vip-create with all params.
resource = 'vip'
cmd = vip.CreateVip(test_cli20.MyApp(sys.stdout), None)
pool_id = 'my-pool-id'
name = 'my-name'
description = 'my-desc'
address = '10.0.0.2'
admin_state = False
connection_limit = '1000'
subnet_id = 'subnet-id'
protocol_port = '80'
protocol = 'TCP'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = ['--name', name,
'--description', description,
'--address', address,
'--admin-state-down',
'--connection-limit', connection_limit,
'--protocol-port', protocol_port,
'--protocol', protocol,
'--subnet-id', subnet_id,
'--tenant-id', tenant_id,
pool_id]
position_names = ['pool_id', 'name', 'description', 'address',
'admin_state_up', 'connection_limit',
'protocol_port', 'protocol', 'subnet_id',
'tenant_id']
position_values = [pool_id, name, description, address,
admin_state, connection_limit, protocol_port,
protocol, subnet_id,
tenant_id]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def test_create_vip_with_session_persistence_params(self):
# lb-vip-create with mandatory and session-persistence params.
resource = 'vip'
cmd = vip.CreateVip(test_cli20.MyApp(sys.stdout), None)
pool_id = 'my-pool-id'
name = 'my-name'
subnet_id = 'subnet-id'
protocol_port = '1000'
protocol = 'TCP'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = ['--name', name,
'--protocol-port', protocol_port,
'--protocol', protocol,
'--subnet-id', subnet_id,
'--tenant-id', tenant_id,
pool_id,
'--session-persistence', 'type=dict',
'type=cookie,cookie_name=pie',
'--optional-param', 'any']
position_names = ['pool_id', 'name', 'protocol_port', 'protocol',
'subnet_id', 'tenant_id', 'optional_param']
position_values = [pool_id, name, protocol_port, protocol,
subnet_id, tenant_id, 'any']
extra_body = {
'session_persistence': {
'type': 'cookie',
'cookie_name': 'pie',
},
}
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
admin_state_up=True, extra_body=extra_body)
def test_list_vips(self):
# lb-vip-list.
resources = "vips"
cmd = vip.ListVip(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_vips_pagination(self):
# lb-vip-list.
resources = "vips"
cmd = vip.ListVip(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_vips_sort(self):
# lb-vip-list --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = "vips"
cmd = vip.ListVip(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_vips_limit(self):
# lb-vip-list -P.
resources = "vips"
cmd = vip.ListVip(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_vip_id(self):
# lb-vip-show test_id.
resource = 'vip'
cmd = vip.ShowVip(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_show_vip_id_name(self):
# lb-vip-show.
resource = 'vip'
cmd = vip.ShowVip(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_update_vip(self):
# lb-vip-update myid --name myname --tags a b.
resource = 'vip'
cmd = vip.UpdateVip(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--tags', 'a', 'b'],
{'name': 'myname', 'tags': ['a', 'b'], })
def test_update_vip_with_session_persistence(self):
resource = 'vip'
cmd = vip.UpdateVip(test_cli20.MyApp(sys.stdout), None)
body = {
'session_persistence': {
'type': 'source',
},
}
args = ['myid', '--session-persistence', 'type=dict',
'type=source']
self._test_update_resource(resource, cmd, 'myid', args, body)
def test_update_vip_with_session_persistence_and_name(self):
resource = 'vip'
cmd = vip.UpdateVip(test_cli20.MyApp(sys.stdout), None)
body = {
'name': 'newname',
'session_persistence': {
'type': 'cookie',
'cookie_name': 'pie',
},
}
args = ['myid', '--name', 'newname',
'--session-persistence', 'type=dict',
'type=cookie,cookie_name=pie']
self._test_update_resource(resource, cmd, 'myid', args, body)
def test_delete_vip(self):
# lb-vip-delete my-id.
resource = 'vip'
cmd = vip.DeleteVip(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)

View File

@ -1,175 +0,0 @@
# Copyright 2014 Blue Box Group, 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 sys
from neutronclient.neutron.v2_0.lb.v2 import healthmonitor
from neutronclient.tests.unit import test_cli20
class CLITestV20LbHealthMonitorJSON(test_cli20.CLITestV20Base):
def test_create_healthmonitor_with_mandatory_params(self):
# lbaas-healthmonitor-create with mandatory params only.
resource = 'healthmonitor'
cmd_resource = 'lbaas_healthmonitor'
cmd = healthmonitor.CreateHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
type = 'PING'
max_retries = '3'
delay = '10'
timeout = '60'
pool = 'pool1'
args = ['--type', type, '--max-retries', max_retries,
'--delay', delay, '--timeout', timeout, '--pool', pool]
position_names = ['type', 'max_retries', 'delay', 'timeout', 'pool_id']
position_values = [type, max_retries, delay, timeout, pool]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=cmd_resource)
def test_create_healthmonitor_with_all_params(self):
# lbaas-healthmonitor-create with all params set.
resource = 'healthmonitor'
cmd_resource = 'lbaas_healthmonitor'
cmd = healthmonitor.CreateHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
type = 'PING'
max_retries = '3'
delay = '10'
timeout = '60'
http_method = 'GET'
expected_codes = '201'
url_path = '/somepath'
pool = 'pool1'
name = 'healthmonitor1'
args = ['--admin-state-down', '--http-method', http_method,
'--expected-codes', expected_codes, '--url-path', url_path,
'--type', type, '--max-retries', max_retries,
'--delay', delay, '--timeout', timeout, '--pool', pool,
'--name', name]
position_names = ['admin_state_up', 'http_method', 'expected_codes',
'url_path', 'type', 'max_retries', 'delay',
'timeout', 'pool_id', 'name']
position_values = [False, http_method, expected_codes, url_path,
type, max_retries, delay, timeout, pool, name]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=cmd_resource)
def test_list_healthmonitors(self):
# lbaas-healthmonitor-list.
resources = 'healthmonitors'
cmd_resources = 'lbaas_healthmonitors'
cmd = healthmonitor.ListHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True,
cmd_resources=cmd_resources)
def test_list_healthmonitors_pagination(self):
# lbaas-healthmonitor-list with pagination.
resources = 'healthmonitors'
cmd_resources = 'lbaas_healthmonitors'
cmd = healthmonitor.ListHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources_with_pagination(resources, cmd,
cmd_resources=cmd_resources)
def test_list_healthmonitors_sort(self):
# lbaas-healthmonitor-list --sort-key id --sort-key asc.
resources = 'healthmonitors'
cmd_resources = 'lbaas_healthmonitors'
cmd = healthmonitor.ListHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True,
cmd_resources=cmd_resources)
def test_list_healthmonitors_limit(self):
# lbaas-healthmonitor-list -P.
resources = 'healthmonitors'
cmd_resources = 'lbaas_healthmonitors'
cmd = healthmonitor.ListHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, page_size=1000,
cmd_resources=cmd_resources)
def test_show_healthmonitor_id(self):
# lbaas-healthmonitor-show test_id.
resource = 'healthmonitor'
cmd_resource = 'lbaas_healthmonitor'
cmd = healthmonitor.ShowHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'],
cmd_resource=cmd_resource)
def test_show_healthmonitor_id_name(self):
# lbaas-healthmonitor-show.
resource = 'healthmonitor'
cmd_resource = 'lbaas_healthmonitor'
cmd = healthmonitor.ShowHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'],
cmd_resource=cmd_resource)
def _test_update_hm(self, args, expected_values):
resource = 'healthmonitor'
cmd_resource = 'lbaas_healthmonitor'
my_id = 'myid'
cmd = healthmonitor.UpdateHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
args.insert(0, my_id)
self._test_update_resource(resource, cmd, my_id,
args,
expected_values,
cmd_resource=cmd_resource)
def test_update_healthmonitor(self):
# lbaas-healthmonitor-update myid --name newname.
self._test_update_hm(['--name', 'newname'], {'name': 'newname', })
# lbaas-healthmonitor-update myid --delay 10.
self._test_update_hm(['--delay', '10'], {'delay': '10'})
# lbaas-healthmonitor-update myid --timeout 5.
self._test_update_hm(['--timeout', '5'], {'timeout': '5', })
# lbaas-healthmonitor-update myid --delay 10.
self._test_update_hm(['--http-method', 'OPTIONS'],
{'http_method': 'OPTIONS'})
# lbaas-healthmonitor-update myid --url-path /test/string .
self._test_update_hm(['--url-path', '/test/string'],
{'url_path': '/test/string', })
# lbaas-healthmonitor-update myid --max-retries 5
self._test_update_hm(['--max-retries', '5'], {'max_retries': '5'})
# lbaas-healthmonitor-update myid --expected-codes 201
self._test_update_hm(['--expected-codes', '201'],
{'expected_codes': '201'})
# lbaas-healthmonitor-update myid --admin-state-up False
self._test_update_hm(['--admin-state-up', 'False'],
{'admin_state_up': 'False'})
def test_delete_healthmonitor(self):
# lbaas-healthmonitor-delete my-id.
resource = 'healthmonitor'
cmd_resource = 'lbaas_healthmonitor'
cmd = healthmonitor.DeleteHealthMonitor(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args,
cmd_resource=cmd_resource)

View File

@ -1,260 +0,0 @@
# Copyright 2016 Radware 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 sys
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0.lb.v2 import l7policy
from neutronclient.tests.unit import test_cli20
"""Structure for mapping cli and api arguments
The structure maps cli arguments and a list of its
api argument name, default cli value and default api value.
It helps to make tests more general for different argument types.
"""
args_conf = {
'name': ['name', 'test_policy', 'test_policy'],
'description': ['description', 'test policy', 'test policy'],
'listener': ['listener_id', 'test_listener', 'test_listener'],
'admin-state-up': ['admin_state_up', True, True],
'admin-state-down': ['admin_state_up', None, False],
'action': ['action', 'REJECT', 'REJECT'],
'redirect-url': ['redirect_url', 'http://url', 'http://url'],
'redirect-pool': ['redirect_pool_id', 'test_pool', 'test_pool'],
'position': ['position', '1', 1]}
class CLITestV20LbL7PolicyJSON(test_cli20.CLITestV20Base):
def _get_test_args(self, *args, **kwargs):
"""Function for generically building testing arguments"""
cli_args = []
api_args = {}
for arg in args:
cli_args.append('--' + arg)
if not args_conf[arg][1]:
pass
elif arg in kwargs:
cli_args.append(str(kwargs[arg]))
else:
cli_args.append(args_conf[arg][1])
if arg in kwargs:
api_args[args_conf[arg][0]] = kwargs[arg]
else:
api_args[args_conf[arg][0]] = args_conf[arg][2]
return cli_args, api_args
def _test_create_policy(self, *args, **kwargs):
resource = 'l7policy'
cmd_resource = 'lbaas_l7policy'
cmd = l7policy.CreateL7Policy(test_cli20.MyApp(sys.stdout), None)
cli_args, api_args = self._get_test_args(*args, **kwargs)
position_names = list(api_args.keys())
position_values = list(api_args.values())
self._test_create_resource(resource, cmd, None, 'test_id',
cli_args, position_names, position_values,
cmd_resource=cmd_resource)
def _test_update_policy(self, *args, **kwargs):
resource = 'l7policy'
cmd_resource = 'lbaas_l7policy'
cmd = l7policy.UpdateL7Policy(test_cli20.MyApp(sys.stdout), None)
cli_args, api_args = self._get_test_args(*args, **kwargs)
cli_args.append('test_id')
self._test_update_resource(resource, cmd, 'test_id',
cli_args, api_args,
cmd_resource=cmd_resource)
def test_create_policy_with_mandatory_params(self):
# lbaas-l7policy-create with mandatory params only.
self._test_create_policy('action', 'listener')
def test_create_policy_with_all_params(self):
# lbaas-l7policy-create REJECT policy.
self._test_create_policy('name', 'description',
'action', 'listener',
'position')
def test_create_disabled_policy(self):
# lbaas-l7policy-create disabled REJECT policy.
self._test_create_policy('action', 'listener', 'admin-state-down')
def test_create_url_redirect_policy(self):
# lbaas-l7policy-create REDIRECT_TO_URL policy.
self._test_create_policy('name', 'description',
'action', 'listener',
'redirect-url',
action='REDIRECT_TO_URL')
def test_create_url_redirect_policy_no_url(self):
# lbaas-l7policy-create REDIRECT_TO_URL policy without url argument.
self.assertRaises(exceptions.CommandError,
self._test_create_policy,
'name', 'description',
'action', 'listener',
action='REDIRECT_TO_URL')
def test_create_pool_redirect_policy(self):
# lbaas-l7policy-create REDIRECT_TO_POOL policy.
self._test_create_policy('name', 'description',
'action', 'listener',
'redirect-pool',
action='REDIRECT_TO_POOL')
def test_create_pool_redirect_policy_no_pool(self):
# lbaas-l7policy-create REDIRECT_TO_POOL policy without pool argument.
self.assertRaises(exceptions.CommandError,
self._test_create_policy,
'name', 'description',
'action', 'listener',
action='REDIRECT_TO_POOL')
def test_create_reject_policy_with_url(self):
# lbaas-l7policy-create REJECT policy while specifying url argument.
self.assertRaises(exceptions.CommandError,
self._test_create_policy,
'action', 'listener',
'redirect-url')
def test_create_reject_policy_with_pool(self):
# lbaas-l7policy-create REJECT policy while specifying pool argument.
self.assertRaises(exceptions.CommandError,
self._test_create_policy,
'action', 'listener',
'redirect-pool')
def test_create_pool_redirect_policy_with_url(self):
# lbaas-l7policy-create REDIRECT_TO_POOL policy with url argument.
self.assertRaises(exceptions.CommandError,
self._test_create_policy,
'action', 'listener',
'redirect-pool', 'redirect-url',
action='REDIRECT_TO_POOL')
def test_create_url_redirect_policy_with_pool(self):
# lbaas-l7policy-create REDIRECT_TO_URL policy with pool argument.
self.assertRaises(exceptions.CommandError,
self._test_create_policy,
'action', 'listener',
'redirect-pool', 'redirect-url',
action='REDIRECT_TO_URL')
def test_list_policies(self):
# lbaas-l7policy-list.
resources = 'l7policies'
cmd_resources = 'lbaas_l7policies'
cmd = l7policy.ListL7Policy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True,
cmd_resources=cmd_resources)
def test_list_policies_pagination(self):
# lbaas-l7policy-list with pagination.
resources = 'l7policies'
cmd_resources = 'lbaas_l7policies'
cmd = l7policy.ListL7Policy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(
resources, cmd, cmd_resources=cmd_resources)
def test_list_policies_sort(self):
# lbaas-l7policy-list --sort-key id --sort-key asc.
resources = 'l7policies'
cmd_resources = 'lbaas_l7policies'
cmd = l7policy.ListL7Policy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(
resources, cmd, True, cmd_resources=cmd_resources)
def test_list_policies_limit(self):
# lbaas-l7policy-list -P.
resources = 'l7policies'
cmd_resources = 'lbaas_l7policies'
cmd = l7policy.ListL7Policy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(
resources, cmd, page_size=1000, cmd_resources=cmd_resources)
def test_show_policy_id(self):
# lbaas-l7policy-show test_id.
resource = 'l7policy'
cmd_resource = 'lbaas_l7policy'
cmd = l7policy.ShowL7Policy(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'test_id', self.test_id]
self._test_show_resource(
resource, cmd, self.test_id, args,
['test_id'], cmd_resource=cmd_resource)
def test_show_policy_id_name(self):
# lbaas-l7policy-show.
resource = 'l7policy'
cmd_resource = 'lbaas_l7policy'
cmd = l7policy.ShowL7Policy(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'test_id', '--fields', 'name', self.test_id]
self._test_show_resource(
resource, cmd, self.test_id, args,
['test_id', 'name'], cmd_resource=cmd_resource)
def test_disable_policy(self):
# lbaas-l7policy-update test_id --admin-state-up False.
self._test_update_policy('admin-state-up',
**{'admin-state-up': 'False'})
def test_update_policy_name_and_description(self):
# lbaas-l7policy-update test_id --name other --description other_desc.
self._test_update_policy('name', 'description',
name='name',
description='other desc')
def test_update_pool_redirect_policy(self):
# lbaas-l7policy-update test_id --action REDIRECT_TO_POOL
# --redirect-pool id.
self._test_update_policy('action', 'redirect-pool',
**{'action': 'REDIRECT_TO_POOL',
'redirect-pool': 'id'})
def test_update_url_redirect_policy(self):
# lbaas-l7policy-update test_id --action REDIRECT_TO_URL
# --redirect-url http://other_url.
self._test_update_policy('action', 'redirect-url',
**{'action': 'REDIRECT_TO_URL',
'redirect-url': 'http://other_url'})
def test_update_policy_position(self):
# lbaas-l7policy-update test_id --position 2.
self._test_update_policy('position',
position=2)
def test_delete_policy(self):
# lbaas-l7policy-delete test_id.
resource = 'l7policy'
cmd_resource = 'lbaas_l7policy'
cmd = l7policy.DeleteL7Policy(test_cli20.MyApp(sys.stdout), None)
test_id = 'test_id'
args = [test_id]
self._test_delete_resource(resource, cmd, test_id, args,
cmd_resource=cmd_resource)

View File

@ -1,210 +0,0 @@
# Copyright 2016 Radware 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 sys
from neutronclient.neutron.v2_0.lb.v2 import l7rule
from neutronclient.tests.unit import test_cli20
"""Structure for mapping cli and api arguments
The structure maps cli arguments and a list of its
api argument name, default cli value and default api value.
It helps to make tests more general for different argument types.
"""
args_conf = {
'admin-state-up': ['admin_state_up', True, True],
'admin-state-down': ['admin_state_up', None, False],
'type': ['type', 'HOST_NAME', 'HOST_NAME'],
'compare-type': ['compare_type', 'EQUAL_TO', 'EQUAL_TO'],
'invert-compare': ['invert', None, True],
'key': ['key', 'key', 'key'],
'value': ['value', 'value', 'value']}
class CLITestV20LbL7RuleJSON(test_cli20.CLITestV20Base):
def _get_test_args(self, *args, **kwargs):
"""Function for generically building testing arguments"""
cli_args = []
api_args = {}
for arg in args:
cli_args.append('--' + arg)
if not args_conf[arg][1]:
pass
elif arg in kwargs:
cli_args.append(str(kwargs[arg]))
else:
cli_args.append(args_conf[arg][1])
if arg in kwargs:
api_args[args_conf[arg][0]] = kwargs[arg]
else:
api_args[args_conf[arg][0]] = args_conf[arg][2]
if 'invert' not in api_args:
api_args['invert'] = False
return cli_args, api_args
def _test_create_rule(self, *args, **kwargs):
resource = 'rule'
cmd_resource = 'lbaas_l7rule'
cmd = l7rule.CreateL7Rule(test_cli20.MyApp(sys.stdout), None)
cli_args, api_args = self._get_test_args(*args, **kwargs)
position_names = list(api_args.keys())
position_values = list(api_args.values())
cli_args.append('test_policy')
self._test_create_resource(resource, cmd, None, 'test_id',
cli_args, position_names, position_values,
cmd_resource=cmd_resource,
parent_id='test_policy')
def _test_update_rule(self, *args, **kwargs):
resource = 'rule'
cmd_resource = 'lbaas_l7rule'
cmd = l7rule.UpdateL7Rule(test_cli20.MyApp(sys.stdout), None)
cli_args, api_args = self._get_test_args(*args, **kwargs)
cli_args.append('test_id')
cli_args.append('test_policy')
self._test_update_resource(resource, cmd, 'test_id',
cli_args, api_args,
cmd_resource=cmd_resource,
parent_id='test_policy')
def test_create_rule_with_mandatory_params(self):
# lbaas-l7rule-create with mandatory params only.
self._test_create_rule('type', 'compare-type',
'value')
def test_create_disabled_rule(self):
# lbaas-l7rule-create disabled rule.
self._test_create_rule('type', 'compare-type',
'value', 'admin-state-down')
def test_create_rule_with_all_params(self):
# lbaas-l7rule-create with all params set.
self._test_create_rule('type', 'compare-type',
'invert-compare', 'key', 'value',
type='HEADER', compare_type='CONTAINS',
key='other_key', value='other_value')
def test_create_rule_with_inverted_compare(self):
# lbaas-l7rule-create with invertted compare type.
self._test_create_rule('type', 'compare-type',
'invert-compare', 'value')
def test_list_rules(self):
# lbaas-l7rule-list.
resources = 'rules'
cmd_resources = 'lbaas_l7rules'
cmd = l7rule.ListL7Rule(test_cli20.MyApp(sys.stdout), None)
policy_id = 'policy_id'
self._test_list_resources(resources, cmd, True,
base_args=[policy_id],
cmd_resources=cmd_resources,
parent_id=policy_id,
query="l7policy_id=%s" % policy_id)
def test_list_rules_pagination(self):
# lbaas-l7rule-list with pagination.
resources = 'rules'
cmd_resources = 'lbaas_l7rules'
cmd = l7rule.ListL7Rule(test_cli20.MyApp(sys.stdout), None)
policy_id = 'policy_id'
self._test_list_resources_with_pagination(
resources, cmd, base_args=[policy_id],
cmd_resources=cmd_resources, parent_id=policy_id,
query="l7policy_id=%s" % policy_id)
def test_list_rules_sort(self):
# lbaas-l7rule-list --sort-key id --sort-key asc.
resources = 'rules'
cmd_resources = 'lbaas_l7rules'
cmd = l7rule.ListL7Rule(test_cli20.MyApp(sys.stdout), None)
policy_id = 'policy_id'
self._test_list_resources(
resources, cmd, True, base_args=[policy_id],
cmd_resources=cmd_resources, parent_id=policy_id,
query="l7policy_id=%s" % policy_id)
def test_list_rules_limit(self):
# lbaas-l7rule-list -P.
resources = 'rules'
cmd_resources = 'lbaas_l7rules'
cmd = l7rule.ListL7Rule(test_cli20.MyApp(sys.stdout), None)
policy_id = 'policy_id'
self._test_list_resources(resources, cmd, page_size=1000,
base_args=[policy_id],
cmd_resources=cmd_resources,
parent_id=policy_id,
query="l7policy_id=%s" % policy_id)
def test_show_rule_id(self):
# lbaas-l7rule-show test_id.
resource = 'rule'
cmd_resource = 'lbaas_l7rule'
policy_id = 'policy_id'
cmd = l7rule.ShowL7Rule(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id, policy_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'],
cmd_resource=cmd_resource,
parent_id=policy_id)
def test_update_rule_type(self):
# lbaas-l7rule-update test_id --type HEADER test_policy
self._test_update_rule('type', type='HEADER')
def test_update_rule_compare_type(self):
# lbaas-l7rule-update test_id --compare-type CONTAINS test_policy.
self._test_update_rule('compare-type',
**{'compare-type': 'CONTAINS'})
def test_update_rule_inverted_compare_type(self):
# lbaas-l7rule-update test_id --invert-compare test_policy.
self._test_update_rule('invert-compare')
def test_update_rule_key_value(self):
# lbaas-l7rule-update test_id --key other --value other test_policy.
self._test_update_rule('key', 'value',
key='other', value='other')
def test_delete_rule(self):
# lbaas-l7rule-delete test_id policy_id.
resource = 'rule'
cmd_resource = 'lbaas_l7rule'
policy_id = 'policy_id'
test_id = 'test_id'
cmd = l7rule.DeleteL7Rule(test_cli20.MyApp(sys.stdout), None)
args = [test_id, policy_id]
self._test_delete_resource(resource, cmd, test_id, args,
cmd_resource=cmd_resource,
parent_id=policy_id)

View File

@ -1,194 +0,0 @@
# Copyright 2014 Blue Box Group, 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 sys
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0.lb.v2 import listener
from neutronclient.tests.unit import test_cli20
class CLITestV20LbListenerJSON(test_cli20.CLITestV20Base):
def test_create_listener_with_loadbalancer(self):
# lbaas-listener-create with --loadbalancer
resource = 'listener'
cmd_resource = 'lbaas_listener'
cmd = listener.CreateListener(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
loadbalancer_id = 'loadbalancer'
protocol = 'TCP'
protocol_port = '80'
args = ['--protocol', protocol, '--protocol-port', protocol_port,
'--loadbalancer', loadbalancer_id]
position_names = ['protocol', 'protocol_port', 'loadbalancer_id']
position_values = [protocol, protocol_port, loadbalancer_id,
True]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=cmd_resource)
def test_create_listener_with_default_pool(self):
# lbaas-listener-create with --default-pool and no --loadbalancer.
resource = 'listener'
cmd_resource = 'lbaas_listener'
cmd = listener.CreateListener(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
default_pool_id = 'default-pool'
protocol = 'TCP'
protocol_port = '80'
args = ['--protocol', protocol, '--protocol-port', protocol_port,
'--default-pool', default_pool_id]
position_names = ['protocol', 'protocol_port', 'default_pool_id']
position_values = [protocol, protocol_port, default_pool_id,
True]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=cmd_resource)
def test_create_listener_with_no_loadbalancer_or_default_pool(self):
# lbaas-listener-create without --default-pool or --loadbalancer.
resource = 'listener'
cmd_resource = 'lbaas_listener'
cmd = listener.CreateListener(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
protocol = 'TCP'
protocol_port = '80'
args = ['--protocol', protocol, '--protocol-port', protocol_port]
position_names = ['protocol', 'protocol_port']
position_values = [protocol, protocol_port, True]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=cmd_resource,
no_api_call=True,
expected_exception=exceptions.CommandError)
def test_create_listener_with_all_params(self):
# lbaas-listener-create with all params set.
resource = 'listener'
cmd_resource = 'lbaas_listener'
cmd = listener.CreateListener(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
loadbalancer = 'loadbalancer'
default_pool_id = 'default-pool'
protocol = 'TCP'
protocol_port = '80'
connection_limit = 10
def_tls_cont_ref = '11111'
args = ['--admin-state-down',
'--protocol', protocol, '--protocol-port', protocol_port,
'--loadbalancer', loadbalancer,
'--default-pool', default_pool_id,
'--default-tls-container-ref', def_tls_cont_ref,
'--sni-container-refs', '1111', '2222', '3333',
'--connection-limit', '10']
position_names = ['admin_state_up',
'protocol', 'protocol_port', 'loadbalancer_id',
'default_pool_id',
'default_tls_container_ref', 'sni_container_refs',
'connection_limit']
position_values = [False, protocol, protocol_port, loadbalancer,
default_pool_id,
def_tls_cont_ref, ['1111', '2222', '3333'],
connection_limit]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=cmd_resource)
def test_list_listeners(self):
# lbaas-listener-list.
resources = 'listeners'
cmd_resources = 'lbaas_listeners'
cmd = listener.ListListener(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True,
cmd_resources=cmd_resources)
def test_list_listeners_pagination(self):
# lbaas-listener-list with pagination.
resources = 'listeners'
cmd_resources = 'lbaas_listeners'
cmd = listener.ListListener(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd,
cmd_resources=cmd_resources)
def test_list_listeners_sort(self):
# lbaas-listener-list --sort-key id --sort-key asc.
resources = 'listeners'
cmd_resources = 'lbaas_listeners'
cmd = listener.ListListener(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True,
cmd_resources=cmd_resources)
def test_list_listeners_limit(self):
# lbaas-listener-list -P.
resources = 'listeners'
cmd_resources = 'lbaas_listeners'
cmd = listener.ListListener(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000,
cmd_resources=cmd_resources)
def test_show_listener_id(self):
# lbaas-listener-show test_id.
resource = 'listener'
cmd_resource = 'lbaas_listener'
cmd = listener.ShowListener(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'],
cmd_resource=cmd_resource)
def test_show_listener_id_name(self):
# lbaas-listener-show.
resource = 'listener'
cmd_resource = 'lbaas_listener'
cmd = listener.ShowListener(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'],
cmd_resource=cmd_resource)
def _test_update_listener(self, args, expected_values):
resource = 'listener'
cmd_resource = 'lbaas_listener'
my_id = 'myid'
args.insert(0, my_id)
cmd = listener.UpdateListener(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, my_id,
args, expected_values,
cmd_resource=cmd_resource)
def test_update_listener(self):
# lbaas-listener-update myid --name newname.
self._test_update_listener(['--name', 'newname'],
{'name': 'newname', })
# lbaas-listener-update myid --description check.
self._test_update_listener(['--description', 'check'],
{'description': 'check', })
# lbaas-listener-update myid --connection-limit -1
self._test_update_listener(['--connection-limit', '-1'],
{'connection_limit': -1, })
# lbaas-listener-update myid --admin-state-up False.
self._test_update_listener(['--admin-state-up', 'False'],
{'admin_state_up': 'False', })
def test_delete_listener(self):
# lbaas-listener-delete my-id.
resource = 'listener'
cmd_resource = 'lbaas_listener'
cmd = listener.DeleteListener(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args,
cmd_resource=cmd_resource)

View File

@ -1,213 +0,0 @@
# Copyright 2014 Blue Box Group, 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 sys
from unittest import mock
from neutronclient.neutron.v2_0.lb.v2 import loadbalancer as lb
from neutronclient.tests.unit import test_cli20
class CLITestV20LbLoadBalancerJSON(test_cli20.CLITestV20Base):
def test_create_loadbalancer_with_mandatory_params(self):
# lbaas-loadbalancer-create with mandatory params only.
resource = 'loadbalancer'
cmd_resource = 'lbaas_loadbalancer'
cmd = lb.CreateLoadBalancer(test_cli20.MyApp(sys.stdout), None)
name = 'lbaas-loadbalancer-name'
vip_subnet_id = 'vip-subnet'
my_id = 'my-id'
args = [vip_subnet_id]
position_names = ['vip_subnet_id']
position_values = [vip_subnet_id]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
cmd_resource=cmd_resource)
def test_create_loadbalancer_with_all_params(self):
# lbaas-loadbalancer-create with all params set.
resource = 'loadbalancer'
cmd_resource = 'lbaas_loadbalancer'
cmd = lb.CreateLoadBalancer(test_cli20.MyApp(sys.stdout), None)
name = 'lbaas-loadbalancer-name'
description = 'lbaas-loadbalancer-desc'
flavor_id = 'lbaas-loadbalancer-flavor'
vip_subnet_id = 'vip-subnet'
my_id = 'my-id'
args = ['--admin-state-down', '--description', description,
'--name', name, '--flavor', flavor_id, vip_subnet_id]
position_names = ['admin_state_up', 'description', 'name',
'flavor_id', 'vip_subnet_id']
position_values = [False, description, name, flavor_id, vip_subnet_id]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
cmd_resource=cmd_resource)
def test_list_loadbalancers(self):
# lbaas-loadbalancer-list.
resources = 'loadbalancers'
cmd_resources = 'lbaas_loadbalancers'
cmd = lb.ListLoadBalancer(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True,
cmd_resources=cmd_resources)
def test_list_loadbalancers_pagination(self):
# lbaas-loadbalancer-list with pagination.
resources = 'loadbalancers'
cmd_resources = 'lbaas_loadbalancers'
cmd = lb.ListLoadBalancer(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd,
cmd_resources=cmd_resources)
def test_list_loadbalancers_sort(self):
# lbaas-loadbalancer-list --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = 'loadbalancers'
cmd_resources = 'lbaas_loadbalancers'
cmd = lb.ListLoadBalancer(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"],
cmd_resources=cmd_resources)
def test_list_loadbalancers_limit(self):
# lbaas-loadbalancer-list -P.
resources = 'loadbalancers'
cmd_resources = 'lbaas_loadbalancers'
cmd = lb.ListLoadBalancer(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000,
cmd_resources=cmd_resources)
def test_show_loadbalancer_id(self):
# lbaas-loadbalancer-loadbalancer-show test_id.
resource = 'loadbalancer'
cmd_resource = 'lbaas_loadbalancer'
cmd = lb.ShowLoadBalancer(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'],
cmd_resource=cmd_resource)
def test_show_loadbalancer_id_name(self):
# lbaas-loadbalancer-loadbalancer-show.
resource = 'loadbalancer'
cmd_resource = 'lbaas_loadbalancer'
cmd = lb.ShowLoadBalancer(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'],
cmd_resource=cmd_resource)
def _test_update_lb(self, args, expected_values):
resource = 'loadbalancer'
cmd_resource = 'lbaas_loadbalancer'
my_id = 'myid'
args.insert(0, my_id)
cmd = lb.UpdateLoadBalancer(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, my_id,
args, expected_values,
cmd_resource=cmd_resource)
def test_update_loadbalancer(self):
# lbaas-loadbalancer-update myid --name newname.
self._test_update_lb(['--name', 'newname'], {'name': 'newname', })
# lbaas-loadbalancer-update myid --description check.
self._test_update_lb(['--description', 'check'],
{'description': 'check', })
# lbaas-loadbalancer-update myid --admin-state-up False.
self._test_update_lb(['--admin-state-up', 'False'],
{'admin_state_up': 'False', })
def test_delete_loadbalancer(self):
# lbaas-loadbalancer-loadbalancer-delete my-id.
resource = 'loadbalancer'
cmd_resource = 'lbaas_loadbalancer'
cmd = lb.DeleteLoadBalancer(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args,
cmd_resource=cmd_resource)
def test_retrieve_loadbalancer_stats(self):
# lbaas-loadbalancer-stats test_id.
resource = 'loadbalancer'
cmd = lb.RetrieveLoadBalancerStats(test_cli20.MyApp(sys.stdout), None)
my_id = self.test_id
fields = ['bytes_in', 'bytes_out']
args = ['--fields', 'bytes_in', '--fields', 'bytes_out', my_id]
query = "&".join(["fields=%s" % field for field in fields])
expected_res = {'stats': {'bytes_in': '1234', 'bytes_out': '4321'}}
resstr = self.client.serialize(expected_res)
path = getattr(self.client, "lbaas_loadbalancer_path_stats")
return_tup = (test_cli20.MyResp(200), resstr)
cmd_parser = cmd.get_parser("test_" + resource)
parsed_args = cmd_parser.parse_args(args)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=return_tup) as mock_request:
cmd.run(parsed_args)
self.assert_mock_multiple_calls_with_same_arguments(
mock_get_client, mock.call(), 2)
mock_request.assert_called_once_with(
test_cli20.end_url(path % my_id, query), 'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
_str = self.fake_stdout.make_string()
self.assertIn('bytes_in', _str)
self.assertIn('1234', _str)
self.assertIn('bytes_out', _str)
self.assertIn('4321', _str)
def test_get_loadbalancer_statuses(self):
# lbaas-loadbalancer-status test_id.
resource = 'loadbalancer'
cmd = lb.RetrieveLoadBalancerStatus(test_cli20.MyApp(sys.stdout), None)
my_id = self.test_id
args = [my_id]
expected_res = {'statuses': {'operating_status': 'ONLINE',
'provisioning_status': 'ACTIVE'}}
resstr = self.client.serialize(expected_res)
path = getattr(self.client, "lbaas_loadbalancer_path_status")
return_tup = (test_cli20.MyResp(200), resstr)
cmd_parser = cmd.get_parser("test_" + resource)
parsed_args = cmd_parser.parse_args(args)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=return_tup) as mock_request:
cmd.run(parsed_args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.end_url(path % my_id), 'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
_str = self.fake_stdout.make_string()
self.assertIn('operating_status', _str)
self.assertIn('ONLINE', _str)
self.assertIn('provisioning_status', _str)
self.assertIn('ACTIVE', _str)

View File

@ -1,171 +0,0 @@
# Copyright 2014 Blue Box Group, 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 sys
from neutronclient.neutron.v2_0.lb.v2 import member
from neutronclient.tests.unit import test_cli20
class CLITestV20LbMemberJSON(test_cli20.CLITestV20Base):
def test_create_member_with_mandatory_params(self):
# lbaas-member-create with mandatory params only.
resource = 'member'
cmd_resource = 'lbaas_member'
cmd = member.CreateMember(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
address = '10.1.1.1'
protocol_port = '80'
pool_id = 'pool-id'
subnet_id = 'subnet-id'
args = ['--address', address, '--protocol-port', protocol_port,
'--subnet', subnet_id, pool_id]
position_names = ['admin_state_up', 'address',
'protocol_port', 'subnet_id']
position_values = [True, address, protocol_port, subnet_id]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=cmd_resource,
parent_id=pool_id)
def test_create_member_with_all_params(self):
# lbaas-member-create with all params set.
resource = 'member'
cmd_resource = 'lbaas_member'
cmd = member.CreateMember(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
address = '10.1.1.1'
protocol_port = '80'
pool_id = 'pool-id'
subnet_id = 'subnet-id'
weight = '100'
name = 'member1'
args = ['--address', address, '--protocol-port', protocol_port,
'--subnet', subnet_id, pool_id, '--weight', weight,
'--admin-state-down', '--name', name]
position_names = ['admin_state_up', 'address', 'protocol_port',
'subnet_id', 'weight', 'name']
position_values = [False, address, protocol_port,
subnet_id, weight, name]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
cmd_resource=cmd_resource,
parent_id=pool_id)
def test_list_members(self):
# lbaas-member-list.
resources = 'members'
cmd_resources = 'lbaas_members'
pool_id = 'pool-id'
cmd = member.ListMember(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True, base_args=[pool_id],
cmd_resources=cmd_resources,
parent_id=pool_id,
query="pool_id=%s" % pool_id)
def test_list_members_pagination(self):
# lbaas-member-list with pagination.
resources = 'members'
cmd_resources = 'lbaas_members'
pool_id = 'pool-id'
cmd = member.ListMember(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd,
base_args=[pool_id],
cmd_resources=cmd_resources,
parent_id=pool_id,
query="pool_id=%s" % pool_id)
def test_list_members_sort(self):
# lbaas-member-list --sort-key id --sort-key asc.
resources = 'members'
cmd_resources = 'lbaas_members'
pool_id = 'pool-id'
cmd = member.ListMember(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True, base_args=[pool_id],
cmd_resources=cmd_resources,
parent_id=pool_id,
query="pool_id=%s" % pool_id)
def test_list_members_limit(self):
# lbaas-member-list -P.
resources = 'members'
cmd_resources = 'lbaas_members'
pool_id = 'pool-id'
cmd = member.ListMember(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000,
base_args=[pool_id],
cmd_resources=cmd_resources,
parent_id=pool_id,
query="pool_id=%s" % pool_id)
def test_show_member_id(self):
# lbaas-member-show test_id.
resource = 'member'
cmd_resource = 'lbaas_member'
pool_id = 'pool-id'
cmd = member.ShowMember(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id, pool_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'],
cmd_resource=cmd_resource, parent_id=pool_id)
def test_show_member_id_name(self):
# lbaas-member-show.
resource = 'member'
cmd_resource = 'lbaas_member'
pool_id = 'pool-id'
cmd = member.ShowMember(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id, pool_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'],
cmd_resource=cmd_resource, parent_id=pool_id)
def test_update_member(self):
# lbaas-member-update myid --name newname.
resource = 'member'
cmd_resource = 'lbaas_member'
my_id = 'my-id'
pool_id = 'pool-id'
args = [my_id, pool_id, '--name', 'newname']
cmd = member.UpdateMember(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, my_id, args,
{'name': 'newname', },
cmd_resource=cmd_resource,
parent_id=pool_id)
# lbaas-member-update myid --weight 100.
args = [my_id, pool_id, '--weight', '100']
self._test_update_resource(resource, cmd, my_id, args,
{'weight': '100', },
cmd_resource=cmd_resource,
parent_id=pool_id)
# lbaas-member-update myid --admin-state-up False
args = [my_id, pool_id, '--admin-state-up', 'False']
self._test_update_resource(resource, cmd, my_id, args,
{'admin_state_up': 'False', },
cmd_resource=cmd_resource,
parent_id=pool_id)
def test_delete_member(self):
# lbaas-member-delete my-id.
resource = 'member'
cmd_resource = 'lbaas_member'
cmd = member.DeleteMember(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
pool_id = 'pool-id'
args = [my_id, pool_id]
self._test_delete_resource(resource, cmd, my_id, args,
cmd_resource=cmd_resource,
parent_id=pool_id)

View File

@ -1,202 +0,0 @@
# Copyright 2014 Blue Box Group, 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 sys
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0.lb.v2 import pool
from neutronclient.tests.unit import test_cli20
class CLITestV20LbPoolJSON(test_cli20.CLITestV20Base):
def test_create_pool_with_listener(self):
# lbaas-pool-create with listener
resource = 'pool'
cmd_resource = 'lbaas_pool'
cmd = pool.CreatePool(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
lb_algorithm = 'ROUND_ROBIN'
listener = 'listener'
protocol = 'TCP'
args = ['--lb-algorithm', lb_algorithm, '--protocol', protocol,
'--listener', listener]
position_names = ['admin_state_up', 'lb_algorithm', 'protocol',
'listener_id']
position_values = [True, lb_algorithm, protocol, listener]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=cmd_resource)
def test_create_pool_with_loadbalancer_no_listener(self):
"""lbaas-pool-create with loadbalancer, no listener."""
resource = 'pool'
cmd_resource = 'lbaas_pool'
cmd = pool.CreatePool(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
lb_algorithm = 'ROUND_ROBIN'
loadbalancer = 'loadbalancer'
protocol = 'TCP'
args = ['--lb-algorithm', lb_algorithm, '--protocol', protocol,
'--loadbalancer', loadbalancer]
position_names = ['admin_state_up', 'lb_algorithm', 'protocol',
'loadbalancer_id']
position_values = [True, lb_algorithm, protocol, loadbalancer]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=cmd_resource)
def test_create_pool_with_no_listener_or_loadbalancer(self):
"""lbaas-pool-create with no listener or loadbalancer."""
resource = 'pool'
cmd_resource = 'lbaas_pool'
cmd = pool.CreatePool(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
lb_algorithm = 'ROUND_ROBIN'
protocol = 'TCP'
args = ['--lb-algorithm', lb_algorithm, '--protocol', protocol]
position_names = ['admin_state_up', 'lb_algorithm', 'protocol']
position_values = [True, lb_algorithm, protocol]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=cmd_resource,
no_api_call=True,
expected_exception=exceptions.CommandError)
def test_create_pool_with_all_params(self):
# lbaas-pool-create with all params set.
resource = 'pool'
cmd_resource = 'lbaas_pool'
cmd = pool.CreatePool(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
lb_algorithm = 'ROUND_ROBIN'
listener = 'listener'
loadbalancer = 'loadbalancer'
protocol = 'TCP'
description = 'description'
session_persistence_str = 'type=APP_COOKIE,cookie_name=1234'
session_persistence = {'type': 'APP_COOKIE',
'cookie_name': '1234'}
name = 'my-pool'
args = ['--lb-algorithm', lb_algorithm, '--protocol', protocol,
'--description', description, '--session-persistence',
session_persistence_str, '--admin-state-down', '--name', name,
'--listener', listener, '--loadbalancer', loadbalancer]
position_names = ['lb_algorithm', 'protocol', 'description',
'session_persistence', 'admin_state_up', 'name',
'listener_id', 'loadbalancer_id']
position_values = [lb_algorithm, protocol, description,
session_persistence, False, name, listener,
loadbalancer]
self._test_create_resource(resource, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=cmd_resource)
def test_list_pools(self):
# lbaas-pool-list.
resources = 'pools'
cmd_resources = 'lbaas_pools'
cmd = pool.ListPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True,
cmd_resources=cmd_resources)
def test_list_pools_pagination(self):
# lbaas-pool-list with pagination.
resources = 'pools'
cmd_resources = 'lbaas_pools'
cmd = pool.ListPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd,
cmd_resources=cmd_resources)
def test_list_pools_sort(self):
# lbaas-pool-list --sort-key id --sort-key asc.
resources = 'pools'
cmd_resources = 'lbaas_pools'
cmd = pool.ListPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True,
cmd_resources=cmd_resources)
def test_list_pools_limit(self):
# lbaas-pool-list -P.
resources = 'pools'
cmd_resources = 'lbaas_pools'
cmd = pool.ListPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000,
cmd_resources=cmd_resources)
def test_show_pool_id(self):
# lbaas-pool-show test_id.
resource = 'pool'
cmd_resource = 'lbaas_pool'
cmd = pool.ShowPool(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'],
cmd_resource=cmd_resource)
def test_show_pool_id_name(self):
# lbaas-pool-show.
resource = 'pool'
cmd_resource = 'lbaas_pool'
cmd = pool.ShowPool(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'],
cmd_resource=cmd_resource)
def test_update_pool(self):
# lbaas-pool-update myid --name newname --description SuperPool
# --lb-algorithm SOURCE_IP --admin-state-up
# --session-persistence type=dict,type=HTTP_COOKIE,cookie_name=pie
resource = 'pool'
cmd_resource = 'lbaas_pool'
cmd = pool.UpdatePool(test_cli20.MyApp(sys.stdout), None)
args = ['myid', '--name', 'newname',
'--description', 'SuperPool', '--lb-algorithm', "SOURCE_IP",
'--admin-state-up', 'True',
'--session-persistence', 'type=dict,'
'type=HTTP_COOKIE,cookie_name=pie']
body = {'name': 'newname',
"description": "SuperPool",
"lb_algorithm": "SOURCE_IP",
"admin_state_up": 'True',
'session_persistence': {
'type': 'HTTP_COOKIE',
'cookie_name': 'pie',
}, }
self._test_update_resource(resource, cmd, 'myid', args, body,
cmd_resource=cmd_resource)
# lbaas-pool-update myid --name Name
# --no-session-persistence
resource = 'pool'
cmd_resource = 'lbaas_pool'
cmd = pool.UpdatePool(test_cli20.MyApp(sys.stdout), None)
args = ['myid', '--name', 'Name', '--no-session-persistence']
body = {'name': "Name",
"session_persistence": None, }
self._test_update_resource(resource, cmd, 'myid', args, body,
cmd_resource=cmd_resource)
def test_delete_pool(self):
# lbaas-pool-delete my-id.
resource = 'pool'
cmd_resource = 'lbaas_pool'
cmd = pool.DeletePool(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args,
cmd_resource=cmd_resource)

View File

@ -1,137 +0,0 @@
# Copyright 2015 Huawei Technologies India Pvt 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 sys
from neutronclient.neutron.v2_0.qos import bandwidth_limit_rule as bw_rule
from neutronclient.tests.unit import test_cli20
class CLITestV20QoSBandwidthLimitRuleJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['bandwidth_limit_rule']
def setUp(self):
super(CLITestV20QoSBandwidthLimitRuleJSON, self).setUp()
self.res = 'bandwidth_limit_rule'
self.cmd_res = 'qos_bandwidth_limit_rule'
self.ress = self.res + 's'
self.cmd_ress = self.cmd_res + 's'
def test_create_bandwidth_limit_rule_with_max_kbps(self):
cmd = bw_rule.CreateQoSBandwidthLimitRule(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
max_kbps = '1337'
policy_id = 'policy_id'
args = ['--max-kbps', max_kbps, policy_id]
position_names = ['max_kbps']
position_values = [max_kbps]
self._test_create_resource(self.res, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=self.cmd_res,
parent_id=policy_id)
def test_create_bandwidth_limit_rule_with_max_burst_kbps(self):
cmd = bw_rule.CreateQoSBandwidthLimitRule(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
max_burst_kbps = '1337'
policy_id = 'policy_id'
args = ['--max-burst-kbps', max_burst_kbps, policy_id]
position_names = ['max_burst_kbps']
position_values = [max_burst_kbps]
self._test_create_resource(self.res, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=self.cmd_res,
parent_id=policy_id)
def test_create_bandwidth_limit_rule_with_all_params(self):
cmd = bw_rule.CreateQoSBandwidthLimitRule(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
max_kbps = '1337'
max_burst_kbps = '1337'
policy_id = 'policy_id'
args = ['--max-kbps', max_kbps,
'--max-burst-kbps', max_burst_kbps,
policy_id]
position_names = ['max_kbps', 'max_burst_kbps']
position_values = [max_kbps, max_burst_kbps]
self._test_create_resource(self.res, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=self.cmd_res,
parent_id=policy_id)
def test_update_bandwidth_limit_rule_with_max_kbps(self):
cmd = bw_rule.UpdateQoSBandwidthLimitRule(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
max_kbps = '1337'
policy_id = 'policy_id'
args = ['--max-kbps', max_kbps, my_id, policy_id]
self._test_update_resource(self.res, cmd, my_id, args,
{'max_kbps': max_kbps, },
cmd_resource=self.cmd_res,
parent_id=policy_id)
def test_update_bandwidth_limit_rule_with_max_burst_kbps(self):
cmd = bw_rule.UpdateQoSBandwidthLimitRule(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
max_burst_kbps = '1337'
policy_id = 'policy_id'
args = ['--max-burst-kbps', max_burst_kbps,
my_id, policy_id]
self._test_update_resource(self.res, cmd, my_id, args,
{'max_burst_kbps': max_burst_kbps},
cmd_resource=self.cmd_res,
parent_id=policy_id)
def test_update_bandwidth_limit_rule_with_all_params(self):
cmd = bw_rule.UpdateQoSBandwidthLimitRule(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
max_kbps = '1337'
max_burst_kbps = '1337'
policy_id = 'policy_id'
args = ['--max-kbps', max_kbps,
'--max-burst-kbps', max_burst_kbps,
my_id, policy_id]
self._test_update_resource(self.res, cmd, my_id, args,
{'max_kbps': max_kbps,
'max_burst_kbps': max_burst_kbps},
cmd_resource=self.cmd_res,
parent_id=policy_id)
def test_delete_bandwidth_limit_rule(self):
cmd = bw_rule.DeleteQoSBandwidthLimitRule(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
policy_id = 'policy_id'
args = [my_id, policy_id]
self._test_delete_resource(self.res, cmd, my_id, args,
cmd_resource=self.cmd_res,
parent_id=policy_id)
def test_show_bandwidth_limit_rule(self):
cmd = bw_rule.ShowQoSBandwidthLimitRule(test_cli20.MyApp(sys.stdout),
None)
policy_id = 'policy_id'
args = ['--fields', 'id', self.test_id, policy_id]
self._test_show_resource(self.res, cmd, self.test_id, args,
['id'], cmd_resource=self.cmd_res,
parent_id=policy_id)

View File

@ -1,91 +0,0 @@
# Copyright 2016 Comcast 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 sys
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0.qos import dscp_marking_rule as dscp_rule
from neutronclient.tests.unit import test_cli20
class CLITestV20QoSDscpMarkingRuleJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['dscp_marking_rule']
def setUp(self):
super(CLITestV20QoSDscpMarkingRuleJSON, self).setUp()
self.dscp_res = 'dscp_marking_rule'
self.dscp_cmd_res = 'qos_dscp_marking_rule'
self.dscp_ress = self.dscp_res + 's'
self.dscp_cmd_ress = self.dscp_cmd_res + 's'
def test_create_dscp_marking_rule_with_dscp_mark(self):
cmd = dscp_rule.CreateQoSDscpMarkingRule(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
policy_id = 'policy_id'
position_names = ['dscp_mark']
valid_dscp_marks = ['0', '56']
invalid_dscp_marks = ['-1', '19', '42', '44', '57', '58']
for dscp_mark in valid_dscp_marks:
args = ['--dscp-mark', dscp_mark, policy_id]
position_values = [dscp_mark]
self._test_create_resource(self.dscp_res, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=self.dscp_cmd_res,
parent_id=policy_id)
for dscp_mark in invalid_dscp_marks:
args = ['--dscp-mark', dscp_mark, policy_id]
position_values = [dscp_mark]
self._test_create_resource(
self.dscp_res, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=self.dscp_cmd_res,
parent_id=policy_id,
no_api_call=True,
expected_exception=exceptions.CommandError)
def test_update_dscp_marking_rule_with_dscp_mark(self):
cmd = dscp_rule.UpdateQoSDscpMarkingRule(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
dscp_mark = '56'
policy_id = 'policy_id'
args = ['--dscp-mark', dscp_mark,
my_id, policy_id]
self._test_update_resource(self.dscp_res, cmd, my_id, args,
{'dscp_mark': dscp_mark},
cmd_resource=self.dscp_cmd_res,
parent_id=policy_id)
def test_delete_dscp_marking_rule(self):
cmd = dscp_rule.DeleteQoSDscpMarkingRule(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
policy_id = 'policy_id'
args = [my_id, policy_id]
self._test_delete_resource(self.dscp_res, cmd, my_id, args,
cmd_resource=self.dscp_cmd_res,
parent_id=policy_id)
def test_show_dscp_marking_rule(self):
cmd = dscp_rule.ShowQoSDscpMarkingRule(test_cli20.MyApp(sys.stdout),
None)
policy_id = 'policy_id'
args = ['--fields', 'id', self.test_id, policy_id]
self._test_show_resource(self.dscp_res, cmd, self.test_id, args,
['id'], cmd_resource=self.dscp_cmd_res,
parent_id=policy_id)

View File

@ -1,143 +0,0 @@
# Copyright (c) 2016 Intel Corporation.
# 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 sys
from neutronclient.neutron.v2_0.qos import minimum_bandwidth_rule as bw_rule
from neutronclient.tests.unit import test_cli20
class CLITestV20QoSMinimumBandwidthRuleJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['minimum_bandwidth_rule']
def setUp(self):
super(CLITestV20QoSMinimumBandwidthRuleJSON, self).setUp()
self.res = 'minimum_bandwidth_rule'
self.cmd_res = 'qos_minimum_bandwidth_rule'
self.ress = self.res + 's'
self.cmd_ress = self.cmd_res + 's'
def test_create_minimum_bandwidth_rule_min_kbps_only(self):
cmd = bw_rule.CreateQoSMinimumBandwidthRule(
test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
min_kbps = '1500'
policy_id = 'policy_id'
args = ['--min-kbps', min_kbps,
policy_id]
position_names = ['min_kbps']
position_values = [min_kbps]
self.assertRaises(SystemExit, self._test_create_resource,
self.res, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=self.cmd_res,
parent_id=policy_id,
no_api_call=True)
def test_create_minimum_bandwidth_rule_direction_only(self):
cmd = bw_rule.CreateQoSMinimumBandwidthRule(
test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
direction = 'egress'
policy_id = 'policy_id'
args = ['--direction', direction,
policy_id]
position_names = ['direction']
position_values = [direction]
self.assertRaises(SystemExit, self._test_create_resource,
self.res, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=self.cmd_res,
parent_id=policy_id,
no_api_call=True)
def test_create_minimum_bandwidth_rule_none(self):
cmd = bw_rule.CreateQoSMinimumBandwidthRule(
test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
policy_id = 'policy_id'
args = [policy_id]
position_names = []
position_values = []
self.assertRaises(SystemExit, self._test_create_resource,
self.res, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=self.cmd_res,
parent_id=policy_id,
no_api_call=True)
def test_create_minimum_bandwidth_rule_all(self):
cmd = bw_rule.CreateQoSMinimumBandwidthRule(
test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
min_kbps = '1500'
direction = 'egress'
policy_id = 'policy_id'
args = ['--min-kbps', min_kbps,
'--direction', direction,
policy_id]
position_names = ['direction', 'min_kbps']
position_values = [direction, min_kbps]
self._test_create_resource(self.res, cmd, '', my_id, args,
position_names, position_values,
cmd_resource=self.cmd_res,
parent_id=policy_id)
def test_update_minimum_bandwidth_rule(self):
cmd = bw_rule.UpdateQoSMinimumBandwidthRule(
test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
min_kbps = '1200'
direction = 'egress'
policy_id = 'policy_id'
args = ['--min-kbps', min_kbps,
'--direction', direction,
my_id, policy_id]
self._test_update_resource(self.res, cmd, my_id, args,
{'min_kbps': min_kbps,
'direction': direction},
cmd_resource=self.cmd_res,
parent_id=policy_id)
def test_delete_minimum_bandwidth_rule(self):
cmd = bw_rule.DeleteQoSMinimumBandwidthRule(
test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
policy_id = 'policy_id'
args = [my_id, policy_id]
self._test_delete_resource(self.res, cmd, my_id, args,
cmd_resource=self.cmd_res,
parent_id=policy_id)
def test_show_minimum_bandwidth_rule(self):
cmd = bw_rule.ShowQoSMinimumBandwidthRule(
test_cli20.MyApp(sys.stdout), None)
policy_id = 'policy_id'
args = [self.test_id, policy_id]
self._test_show_resource(self.res, cmd, self.test_id, args,
[], cmd_resource=self.cmd_res,
parent_id=policy_id)
def test_list_minimum_bandwidth_rule(self):
cmd = bw_rule.ListQoSMinimumBandwidthRules(
test_cli20.MyApp(sys.stdout), None)
policy_id = 'policy_id'
args = [policy_id]
contents = [{'name': 'rule1', 'min-kbps': 1000, 'direction': 'egress'}]
self._test_list_resources(self.ress, cmd, parent_id=policy_id,
cmd_resources=self.cmd_ress,
base_args=args, response_contents=contents)

View File

@ -1,192 +0,0 @@
# Copyright 2015 Huawei Technologies India Pvt 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 sys
from neutronclient.neutron.v2_0.qos import policy as policy
from neutronclient.tests.unit import test_cli20
class CLITestV20QoSPolicyJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['policy']
def setUp(self):
super(CLITestV20QoSPolicyJSON, self).setUp()
self.res = 'policy'
self.cmd_res = 'qos_policy'
self.ress = "policies"
self.cmd_ress = 'qos_policies'
def test_create_policy_with_only_keyattributes(self):
# Create qos policy abc.
cmd = policy.CreateQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
myid = 'myid'
name = 'abc'
args = [name]
position_names = ['name']
position_values = [name]
self._test_create_resource(self.res, cmd, name, myid, args,
position_names, position_values,
cmd_resource=self.cmd_res)
def test_create_policy_with_description(self):
# Create qos policy xyz --description abc.
cmd = policy.CreateQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
myid = 'myid'
name = 'abc'
description = 'policy_abc'
args = [name, '--description', description]
position_names = ['name', 'description']
position_values = [name, description]
self._test_create_resource(self.res, cmd, name, myid, args,
position_names, position_values,
cmd_resource=self.cmd_res)
def test_create_policy_with_shared(self):
# Create qos policy abc shared across tenants
cmd = policy.CreateQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
myid = 'myid'
name = 'abc'
description = 'policy_abc'
args = [name, '--description', description, '--shared']
position_names = ['name', 'description', 'shared']
position_values = [name, description, True]
self._test_create_resource(self.res, cmd, name, myid, args,
position_names, position_values,
cmd_resource=self.cmd_res)
def test_create_policy_with_unicode(self):
# Create qos policy u'\u7f51\u7edc'.
cmd = policy.CreateQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
myid = 'myid'
name = u'\u7f51\u7edc'
description = u'\u7f51\u7edc'
args = [name, '--description', description]
position_names = ['name', 'description']
position_values = [name, description]
self._test_create_resource(self.res, cmd, name, myid, args,
position_names, position_values,
cmd_resource=self.cmd_res)
def test_update_policy(self):
# policy-update myid --name newname.
cmd = policy.UpdateQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(self.res, cmd, 'myid',
['myid', '--name', 'newname'],
{'name': 'newname', },
cmd_resource=self.cmd_res)
def test_update_policy_description(self):
# policy-update myid --name newname --description newdesc
cmd = policy.UpdateQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(self.res, cmd, 'myid',
['myid', '--description', 'newdesc'],
{'description': 'newdesc', },
cmd_resource=self.cmd_res)
def test_update_policy_to_shared(self):
# policy-update myid --shared
cmd = policy.UpdateQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(self.res, cmd, 'myid',
['myid', '--shared'],
{'shared': True, },
cmd_resource=self.cmd_res)
def test_update_policy_to_no_shared(self):
# policy-update myid --no-shared
cmd = policy.UpdateQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(self.res, cmd, 'myid',
['myid', '--no-shared'],
{'shared': False, },
cmd_resource=self.cmd_res)
def test_update_policy_to_shared_no_shared_together(self):
# policy-update myid --shared --no-shared
cmd = policy.UpdateQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
self.assertRaises(
SystemExit,
self._test_update_resource,
self.res, cmd, 'myid',
['myid', '--shared', '--no-shared'], {},
cmd_resource=self.cmd_res
)
def test_list_policies(self):
# qos-policy-list.
cmd = policy.ListQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(self.ress, cmd, True,
cmd_resources=self.cmd_ress)
def test_list_policies_pagination(self):
# qos-policy-list for pagination.
cmd = policy.ListQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources_with_pagination(self.ress, cmd,
cmd_resources=self.cmd_ress)
def test_list_policies_sort(self):
# sorted list: qos-policy-list --sort-key name --sort-key id
# --sort-key asc --sort-key desc
cmd = policy.ListQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(self.ress, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"],
cmd_resources=self.cmd_ress)
def test_list_policies_limit(self):
# size (1000) limited list: qos-policy-list -P.
cmd = policy.ListQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(self.ress, cmd, page_size=1000,
cmd_resources=self.cmd_ress)
def test_show_policy_id(self):
# qos-policy-show test_id.
cmd = policy.ShowQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(self.res, cmd, self.test_id, args,
['id'], cmd_resource=self.cmd_res)
def test_show_policy_name(self):
# qos-policy-show.
cmd = policy.ShowQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(self.res, cmd, self.test_id,
args, ['id', 'name'],
cmd_resource=self.cmd_res)
def test_delete_policy(self):
# qos-policy-delete my-id.
cmd = policy.DeleteQoSPolicy(test_cli20.MyApp(sys.stdout),
None)
my_id = 'myid1'
args = [my_id]
self._test_delete_resource(self.res, cmd, my_id, args,
cmd_resource=self.cmd_res)

View File

@ -1,44 +0,0 @@
# Copyright 2015 Huawei Technologies India Pvt 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 sys
from neutronclient.neutron.v2_0.qos import rule as qos_rule
from neutronclient.tests.unit import test_cli20
class CLITestV20QoSRuleJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['bandwidth_limit_rule',
'dscp_marking_rule',
'minimum_bandwidth_rule']
def setUp(self):
super(CLITestV20QoSRuleJSON, self).setUp()
def test_list_qos_rule_types(self):
# qos_rule_types.
resources = 'rule_types'
cmd_resources = 'qos_rule_types'
response_contents = [{'type': 'bandwidth_limit'},
{'type': 'dscp_marking'},
{'type': 'minimum_bandwidth'}]
cmd = qos_rule.ListQoSRuleTypes(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True,
response_contents=response_contents,
cmd_resources=cmd_resources)

View File

@ -1,76 +0,0 @@
# Copyright 2016 IBM
# 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 sys
from neutronclient.neutron.v2_0 import auto_allocated_topology as aat
from neutronclient.tests.unit import test_cli20
class TestAutoAllocatedTopologyJSON(test_cli20.CLITestV20Base):
def test_show_auto_allocated_topology_arg(self):
resource = 'auto_allocated_topology'
cmd = aat.ShowAutoAllocatedTopology(test_cli20.MyApp(sys.stdout), None)
args = ['--tenant-id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args)
def test_show_auto_allocated_topology_posarg(self):
resource = 'auto_allocated_topology'
cmd = aat.ShowAutoAllocatedTopology(test_cli20.MyApp(sys.stdout), None)
args = ['some-tenant']
self._test_show_resource(resource, cmd, "some-tenant", args)
def test_show_auto_allocated_topology_no_arg(self):
resource = 'auto_allocated_topology'
cmd = aat.ShowAutoAllocatedTopology(test_cli20.MyApp(sys.stdout), None)
args = []
self._test_show_resource(resource, cmd, "None", args)
def test_show_auto_allocated_topology_dry_run_as_tenant(self):
resource = 'auto_allocated_topology'
cmd = aat.ShowAutoAllocatedTopology(test_cli20.MyApp(sys.stdout), None)
args = ['--dry-run']
self._test_show_resource(resource, cmd, "None", args,
fields=('dry-run',))
def test_show_auto_allocated_topology_dry_run_as_admin(self):
resource = 'auto_allocated_topology'
cmd = aat.ShowAutoAllocatedTopology(test_cli20.MyApp(sys.stdout), None)
args = ['--dry-run', 'some-tenant']
self._test_show_resource(resource, cmd, "some-tenant", args,
fields=('dry-run',))
def test_delete_auto_allocated_topology_arg(self):
resource = 'auto_allocated_topology'
cmd = aat.DeleteAutoAllocatedTopology(test_cli20.MyApp(sys.stdout),
None)
args = ['--tenant-id', self.test_id]
self._test_delete_resource(resource, cmd, self.test_id, args)
def test_delete_auto_allocated_topology_posarg(self):
resource = 'auto_allocated_topology'
cmd = aat.DeleteAutoAllocatedTopology(test_cli20.MyApp(sys.stdout),
None)
args = ['some-tenant']
self._test_delete_resource(resource, cmd, "some-tenant", args)
def test_delete_auto_allocated_topology_no_arg(self):
resource = 'auto_allocated_topology'
cmd = aat.DeleteAutoAllocatedTopology(test_cli20.MyApp(sys.stdout),
None)
args = []
self._test_delete_resource(resource, cmd, "None", args)

File diff suppressed because it is too large Load Diff

View File

@ -1,175 +0,0 @@
# Copyright 2015 Huawei Technologies India Pvt. 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 sys
from unittest import mock
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0 import address_scope
from neutronclient.tests.unit import test_cli20
class CLITestV20AddressScopeJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['address_scope']
def setUp(self):
super(CLITestV20AddressScopeJSON, self).setUp(plurals={'tags': 'tag'})
def test_create_address_scope_with_minimum_option_ipv4(self):
"""Create address_scope: foo-address-scope with minimum option."""
resource = 'address_scope'
cmd = address_scope.CreateAddressScope(
test_cli20.MyApp(sys.stdout), None)
name = 'foo-address-scope'
myid = 'myid'
args = [name, '4']
position_names = ['name', 'ip_version']
position_values = [name, 4]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_address_scope_with_minimum_option_ipv6(self):
"""Create address_scope: foo-address-scope with minimum option."""
resource = 'address_scope'
cmd = address_scope.CreateAddressScope(
test_cli20.MyApp(sys.stdout), None)
name = 'foo-address-scope'
myid = 'myid'
args = [name, '6']
position_names = ['name', 'ip_version']
position_values = [name, 6]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_address_scope_with_minimum_option_bad_ip_version(self):
"""Create address_scope: foo-address-scope with minimum option."""
resource = 'address_scope'
cmd = address_scope.CreateAddressScope(
test_cli20.MyApp(sys.stdout), None)
name = 'foo-address-scope'
myid = 'myid'
args = [name, '5']
position_names = ['name', 'ip_version']
position_values = [name, 5]
self.assertRaises(SystemExit, self._test_create_resource,
resource, cmd, name, myid, args, position_names,
position_values)
def test_create_address_scope_with_all_option(self):
# Create address_scope: foo-address-scope with all options.
resource = 'address_scope'
cmd = address_scope.CreateAddressScope(
test_cli20.MyApp(sys.stdout), None)
name = 'foo-address-scope'
myid = 'myid'
args = [name, '4', '--shared']
position_names = ['name', 'ip_version', 'shared']
position_values = [name, 4, True]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_address_scope_with_unicode(self):
# Create address_scope: u'\u7f51\u7edc'.
resource = 'address_scope'
cmd = address_scope.CreateAddressScope(
test_cli20.MyApp(sys.stdout), None)
name = u'\u7f51\u7edc'
ip_version = u'4'
myid = 'myid'
args = [name, ip_version]
position_names = ['name', 'ip_version']
position_values = [name, 4]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_update_address_scope_exception(self):
# Update address_scope (Negative) : myid.
resource = 'address_scope'
cmd = address_scope.UpdateAddressScope(
test_cli20.MyApp(sys.stdout), None)
self.assertRaises(exceptions.CommandError, self._test_update_resource,
resource, cmd, 'myid', ['myid'], {})
def test_update_address_scope(self):
# Update address_scope: myid --name newname-address-scope.
resource = 'address_scope'
cmd = address_scope.UpdateAddressScope(
test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'newname-address-scope'],
{'name': 'newname-address-scope'}
)
# Update address_scope: myid --shared
self._test_update_resource(resource, cmd, 'myid',
['myid', '--shared', 'True'],
{'shared': "True"}
)
def test_list_address_scope(self):
# address_scope-list.
resources = "address_scopes"
cmd = address_scope.ListAddressScope(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True)
@mock.patch.object(address_scope.ListAddressScope, "extend_list")
def test_list_address_scope_pagination(self, mock_extend_list):
# address_scope-list.
cmd = address_scope.ListAddressScope(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources_with_pagination("address_scopes",
cmd)
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
def test_list_address_scope_sort(self):
# sorted list:
# address_scope-list --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = "address_scopes"
cmd = address_scope.ListAddressScope(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id", "ip_version"],
sort_dir=["asc", "desc"])
def test_list_address_scope_limit(self):
# size (1000) limited list: address_scope-list -P.
resources = "address_scopes"
cmd = address_scope.ListAddressScope(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_address_scope(self):
# Show address_scope: --fields id --fields name myid.
resource = 'address_scope'
cmd = address_scope.ShowAddressScope(
test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id,
'--fields', 'ip_version', '6']
self._test_show_resource(resource, cmd, self.test_id, args,
['id', 'name', 'ip_version'])
def test_delete_address_scope(self):
# Delete address_scope: address_scope_id.
resource = 'address_scope'
cmd = address_scope.DeleteAddressScope(
test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)

View File

@ -1,97 +0,0 @@
# 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 sys
from oslo_serialization import jsonutils
from neutronclient.neutron.v2_0 import agent
from neutronclient.tests.unit import test_cli20
class CLITestV20Agent(test_cli20.CLITestV20Base):
def test_list_agents(self):
contents = {'agents': [{'id': 'myname', 'agent_type': 'mytype',
'alive': True}]}
args = ['-f', 'json']
resources = "agents"
cmd = agent.ListAgent(test_cli20.MyApp(sys.stdout), None)
self._test_list_columns(cmd, resources, contents, args)
_str = self.fake_stdout.make_string()
returned_agents = jsonutils.loads(_str)
self.assertEqual(1, len(returned_agents))
ag = returned_agents[0]
self.assertEqual(3, len(ag))
self.assertIn("alive", ag.keys())
def test_list_agents_field(self):
contents = {'agents': [{'alive': True}]}
args = ['-f', 'json']
resources = "agents"
smile = ':-)'
cmd = agent.ListAgent(test_cli20.MyApp(sys.stdout), None)
self._test_list_columns(cmd, resources, contents, args)
_str = self.fake_stdout.make_string()
returned_agents = jsonutils.loads(_str)
self.assertEqual(1, len(returned_agents))
ag = returned_agents[0]
self.assertEqual(1, len(ag))
self.assertIn("alive", ag.keys())
self.assertIn(smile, ag.values())
def test_list_agents_zone_field(self):
contents = {'agents': [{'availability_zone': 'myzone'}]}
args = ['-f', 'json']
resources = "agents"
cmd = agent.ListAgent(test_cli20.MyApp(sys.stdout), None)
self._test_list_columns(cmd, resources, contents, args)
_str = self.fake_stdout.make_string()
returned_agents = jsonutils.loads(_str)
self.assertEqual(1, len(returned_agents))
ag = returned_agents[0]
self.assertEqual(1, len(ag))
self.assertIn("availability_zone", ag.keys())
self.assertIn('myzone', ag.values())
def test_update_agent(self):
# agent-update myid --admin-state-down --description mydescr.
resource = 'agent'
cmd = agent.UpdateAgent(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(
resource, cmd, 'myid',
['myid', '--admin-state-down', '--description', 'mydescr'],
{'description': 'mydescr', 'admin_state_up': False}
)
def test_show_agent(self):
# Show agent: --field id --field binary myid.
resource = 'agent'
cmd = agent.ShowAgent(test_cli20.MyApp(sys.stdout), None)
args = ['--field', 'id', '--field', 'binary', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'binary'])
def test_delete_agent(self):
# Delete agent: myid.
resource = 'agent'
cmd = agent.DeleteAgent(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)

View File

@ -1,209 +0,0 @@
# 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 sys
from unittest import mock
from neutronclient.neutron.v2_0 import agentscheduler
from neutronclient.neutron.v2_0 import network
from neutronclient.tests.unit import test_cli20
AGENT_ID = 'agent_id1'
NETWORK_ID = 'net_id1'
ROUTER_ID = 'router_id1'
class CLITestV20AgentScheduler(test_cli20.CLITestV20Base):
def _test_add_to_agent(self, resource, cmd, cmd_args, destination,
body, result):
path = ((self.client.agent_path + destination) %
cmd_args[0])
result_str = self.client.serialize(result)
return_tup = (test_cli20.MyResp(200), result_str)
cmd_parser = cmd.get_parser('test_' + resource)
parsed_args = cmd_parser.parse_args(cmd_args)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=return_tup) as mock_request:
cmd.run(parsed_args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.end_url(path), 'POST',
body=test_cli20.MyComparator(body, self.client),
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
def _test_remove_from_agent(self, resource, cmd, cmd_args, destination):
path = ((self.client.agent_path + destination + '/%s') %
cmd_args)
return_tup = (test_cli20.MyResp(204), None)
cmd_parser = cmd.get_parser('test_' + resource)
parsed_args = cmd_parser.parse_args(cmd_args)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=return_tup) as mock_request:
cmd.run(parsed_args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.end_url(path), 'DELETE',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
class CLITestV20DHCPAgentScheduler(CLITestV20AgentScheduler):
def test_add_network_to_agent(self):
resource = 'agent'
cmd = agentscheduler.AddNetworkToDhcpAgent(
test_cli20.MyApp(sys.stdout), None)
args = (AGENT_ID, NETWORK_ID)
body = {'network_id': NETWORK_ID}
result = {'network_id': 'net_id', }
self._test_add_to_agent(resource, cmd, args, self.client.DHCP_NETS,
body, result)
def test_remove_network_from_agent(self):
resource = 'agent'
cmd = agentscheduler.RemoveNetworkFromDhcpAgent(
test_cli20.MyApp(sys.stdout), None)
args = (AGENT_ID, NETWORK_ID)
self._test_remove_from_agent(resource, cmd, args,
self.client.DHCP_NETS)
@mock.patch.object(network.ListNetwork, "extend_list")
def test_list_networks_on_agent(self, mock_extend_list):
resources = 'networks'
cmd = agentscheduler.ListNetworksOnDhcpAgent(
test_cli20.MyApp(sys.stdout), None)
agent_id = 'agent_id1'
path = ((self.client.agent_path + self.client.DHCP_NETS) %
agent_id)
self._test_list_resources(resources, cmd, base_args=[agent_id],
path=path)
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
def test_list_agents_hosting_network(self):
resources = 'agent'
cmd = agentscheduler.ListDhcpAgentsHostingNetwork(
test_cli20.MyApp(sys.stdout), None)
agent_id = 'agent_id1'
path = ((self.client.network_path + self.client.DHCP_AGENTS) %
agent_id)
contents = {self.id_field: 'myid1', 'alive': True}
self._test_list_resources(resources, cmd, base_args=[agent_id],
path=path, response_contents=contents)
class CLITestV20L3AgentScheduler(CLITestV20AgentScheduler):
def test_add_router_to_agent(self):
resource = 'agent'
cmd = agentscheduler.AddRouterToL3Agent(
test_cli20.MyApp(sys.stdout), None)
args = (AGENT_ID, ROUTER_ID)
body = {'router_id': ROUTER_ID}
result = {'network_id': 'net_id', }
self._test_add_to_agent(resource, cmd, args, self.client.L3_ROUTERS,
body, result)
def test_remove_router_from_agent(self):
resource = 'agent'
cmd = agentscheduler.RemoveRouterFromL3Agent(
test_cli20.MyApp(sys.stdout), None)
args = (AGENT_ID, ROUTER_ID)
self._test_remove_from_agent(resource, cmd, args,
self.client.L3_ROUTERS)
def test_list_routers_on_agent(self):
resources = 'router'
cmd = agentscheduler.ListRoutersOnL3Agent(
test_cli20.MyApp(sys.stdout), None)
agent_id = 'agent_id1'
path = ((self.client.agent_path + self.client.L3_ROUTERS) %
agent_id)
contents = {self.id_field: 'myid1', 'name': 'my_name'}
self._test_list_resources(resources, cmd, base_args=[agent_id],
path=path, response_contents=contents)
def test_list_agents_hosting_router(self):
resources = 'agent'
cmd = agentscheduler.ListL3AgentsHostingRouter(
test_cli20.MyApp(sys.stdout), None)
agent_id = 'agent_id1'
path = ((self.client.router_path + self.client.L3_AGENTS) %
agent_id)
contents = {self.id_field: 'myid1', 'alive': True}
self._test_list_resources(resources, cmd, base_args=[agent_id],
path=path, response_contents=contents)
class CLITestV20LBaaSAgentScheduler(test_cli20.CLITestV20Base):
def test_list_pools_on_agent(self):
resources = 'pools'
cmd = agentscheduler.ListPoolsOnLbaasAgent(
test_cli20.MyApp(sys.stdout), None)
agent_id = 'agent_id1'
path = ((self.client.agent_path + self.client.LOADBALANCER_POOLS) %
agent_id)
self._test_list_resources(resources, cmd, base_args=[agent_id],
path=path)
def test_get_lbaas_agent_hosting_pool(self):
resources = 'agent'
cmd = agentscheduler.GetLbaasAgentHostingPool(
test_cli20.MyApp(sys.stdout), None)
pool_id = 'pool_id1'
path = ((self.client.pool_path + self.client.LOADBALANCER_AGENT) %
pool_id)
contents = {self.id_field: 'myid1', 'alive': True}
self._test_list_resources(resources, cmd, base_args=[pool_id],
path=path, response_contents=contents)
class CLITestV20LBaaSV2AgentScheduler(test_cli20.CLITestV20Base):
def test_list_loadbalancers_on_agent(self):
resources = 'loadbalancers'
cmd = agentscheduler.ListLoadBalancersOnLbaasAgent(
test_cli20.MyApp(sys.stdout), None)
agent_id = 'agent_id1'
path = ((self.client.agent_path + self.client.AGENT_LOADBALANCERS) %
agent_id)
self._test_list_resources(resources, cmd, base_args=[agent_id],
path=path)
def test_get_lbaas_agent_hosting_pool(self):
resources = 'agent'
cmd = agentscheduler.GetLbaasAgentHostingLoadBalancer(
test_cli20.MyApp(sys.stdout), None)
lb_id = 'lb_id1'
path = ((self.client.lbaas_loadbalancer_path +
self.client.LOADBALANCER_HOSTING_AGENT) % lb_id)
contents = {self.id_field: 'myid1', 'alive': True}
self._test_list_resources(resources, cmd, base_args=[lb_id],
path=path, response_contents=contents)

View File

@ -1,31 +0,0 @@
# 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 sys
from neutronclient.neutron.v2_0 import availability_zone as az
from neutronclient.tests.unit import test_cli20
class CLITestV20Agent(test_cli20.CLITestV20Base):
def test_list_agents(self):
contents = {'availability_zones': [{'name': 'zone1',
'resource': 'network',
'state': 'available'},
{'name': 'zone2',
'resource': 'router',
'state': 'unavailable'}]}
args = ['-f', 'json']
resources = "availability_zones"
cmd = az.ListAvailabilityZone(test_cli20.MyApp(sys.stdout), None)
self._test_list_columns(cmd, resources, contents, args)

View File

@ -1,45 +0,0 @@
# Copyright 2013 NEC Corporation
# 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 sys
from neutronclient.neutron.v2_0 import extension
from neutronclient.tests.unit import test_cli20
class CLITestV20Extension(test_cli20.CLITestV20Base):
id_field = 'alias'
def test_list_extensions(self):
resources = 'extensions'
cmd = extension.ListExt(test_cli20.MyApp(sys.stdout), None)
contents = [{'alias': 'ext1', 'name': 'name1', 'other': 'other1'},
{'alias': 'ext2', 'name': 'name2', 'other': 'other2'}]
ret = self._test_list_resources(resources, cmd,
response_contents=contents)
ret_words = set(ret.split())
# Check only the default columns are shown.
self.assertIn('name', ret_words)
self.assertIn('alias', ret_words)
self.assertNotIn('other', ret_words)
def test_show_extension(self):
# -F option does not work for ext-show at the moment, so -F option
# is not passed in the commandline args as other tests do.
resource = 'extension'
cmd = extension.ShowExt(test_cli20.MyApp(sys.stdout), None)
args = [self.test_id]
ext_alias = self.test_id
self._test_show_resource(resource, cmd, ext_alias, args, fields=[])

View File

@ -1,193 +0,0 @@
# Copyright 2012 Red Hat
# 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 sys
from neutronclient.neutron.v2_0 import floatingip as fip
from neutronclient.tests.unit import test_cli20
class CLITestV20FloatingIpsJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['floatingip']
def test_create_floatingip(self):
# Create floatingip: fip1.
resource = 'floatingip'
cmd = fip.CreateFloatingIP(test_cli20.MyApp(sys.stdout), None)
name = 'fip1'
myid = 'myid'
args = [name, '--description', 'floats like a butterfly']
position_names = ['floating_network_id']
position_values = [name]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
description='floats like a butterfly')
def test_create_floatingip_and_port(self):
# Create floatingip: fip1.
resource = 'floatingip'
cmd = fip.CreateFloatingIP(test_cli20.MyApp(sys.stdout), None)
name = 'fip1'
myid = 'myid'
pid = 'mypid'
args = [name, '--port_id', pid]
position_names = ['floating_network_id', 'port_id']
position_values = [name, pid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = [name, '--port-id', pid]
position_names = ['floating_network_id', 'port_id']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_floatingip_and_port_and_address(self):
# Create floatingip: fip1 with a given port and address.
resource = 'floatingip'
cmd = fip.CreateFloatingIP(test_cli20.MyApp(sys.stdout), None)
name = 'fip1'
myid = 'myid'
pid = 'mypid'
addr = '10.0.0.99'
args = [name, '--port_id', pid, '--fixed_ip_address', addr]
position_names = ['floating_network_id', 'port_id', 'fixed_ip_address']
position_values = [name, pid, addr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = [name, '--port-id', pid, '--fixed-ip-address', addr]
position_names = ['floating_network_id', 'port_id', 'fixed_ip_address']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_floatingip_with_ip_address_of_floating_ip(self):
# Create floatingip: fip1 with a given IP address of floating IP.
resource = 'floatingip'
cmd = fip.CreateFloatingIP(test_cli20.MyApp(sys.stdout), None)
name = 'fip1'
myid = 'myid'
addr = '10.0.0.99'
args = [name, '--floating-ip-address', addr]
position_values = [name, addr]
position_names = ['floating_network_id', 'floating_ip_address']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_floatingip_with_subnet_id(self):
# Create floatingip: fip1 on a given subnet id.
resource = 'floatingip'
cmd = fip.CreateFloatingIP(test_cli20.MyApp(sys.stdout), None)
name = 'fip1'
myid = 'myid'
subnet_id = 'mysubnetid'
args = [name, '--subnet', subnet_id]
position_values = [name, subnet_id]
position_names = ['floating_network_id', 'subnet_id']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_floatingip_with_subnet_id_and_port(self):
# Create floatingip: fip1 on a given subnet id and port.
resource = 'floatingip'
cmd = fip.CreateFloatingIP(test_cli20.MyApp(sys.stdout), None)
name = 'fip1'
myid = 'myid'
pid = 'mypid'
subnet_id = 'mysubnetid'
args = [name, '--subnet', subnet_id, '--port-id', pid]
position_values = [name, subnet_id, pid]
position_names = ['floating_network_id', 'subnet_id', 'port_id']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_floatingip_with_dns_name_and_dns_domain(self):
# Create floatingip: fip1 with dns name and dns domain.
resource = 'floatingip'
cmd = fip.CreateFloatingIP(test_cli20.MyApp(sys.stdout), None)
name = 'fip1'
myid = 'myid'
dns_name_name = 'my-floatingip'
dns_domain_name = 'my-domain.org.'
args = [name, '--dns-name', dns_name_name, '--dns-domain',
dns_domain_name]
position_names = ['floating_network_id', 'dns_name', 'dns_domain']
position_values = [name, dns_name_name, dns_domain_name]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_list_floatingips(self):
# list floatingips: -D.
resources = 'floatingips'
cmd = fip.ListFloatingIP(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_floatingips_pagination(self):
resources = 'floatingips'
cmd = fip.ListFloatingIP(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_floatingips_sort(self):
# list floatingips:
# --sort-key name --sort-key id --sort-key asc --sort-key desc
resources = 'floatingips'
cmd = fip.ListFloatingIP(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_floatingips_limit(self):
# list floatingips: -P.
resources = 'floatingips'
cmd = fip.ListFloatingIP(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_delete_floatingip(self):
# Delete floatingip: fip1.
resource = 'floatingip'
cmd = fip.DeleteFloatingIP(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)
def test_show_floatingip(self):
# Show floatingip: --fields id.
resource = 'floatingip'
cmd = fip.ShowFloatingIP(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id'])
def test_disassociate_ip(self):
# Disassociate floating IP: myid.
resource = 'floatingip'
cmd = fip.DisassociateFloatingIP(test_cli20.MyApp(sys.stdout), None)
args = ['myid']
self._test_update_resource(resource, cmd, 'myid',
args, {"port_id": None}
)
def test_associate_ip(self):
# Associate floating IP: myid portid.
resource = 'floatingip'
cmd = fip.AssociateFloatingIP(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'portid']
self._test_update_resource(resource, cmd, 'myid',
args, {"port_id": "portid"}
)

View File

@ -1,99 +0,0 @@
# Copyright (C) 2013 eNovance SAS <licensing@enovance.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 sys
from neutronclient.neutron.v2_0 import metering
from neutronclient.tests.unit import test_cli20
class CLITestV20MeteringJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['metering_label', 'metering_label_rule']
def test_create_metering_label(self):
# Create a metering label.
resource = 'metering_label'
cmd = metering.CreateMeteringLabel(
test_cli20.MyApp(sys.stdout), None)
name = 'my label'
myid = 'myid'
description = 'my description'
args = [name, '--description', description, '--shared']
position_names = ['name', 'description', 'shared']
position_values = [name, description, True]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_list_metering_labels(self):
resources = "metering_labels"
cmd = metering.ListMeteringLabel(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd)
def test_delete_metering_label(self):
# Delete a metering label.
resource = 'metering_label'
cmd = metering.DeleteMeteringLabel(
test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)
def test_show_metering_label(self):
resource = 'metering_label'
cmd = metering.ShowMeteringLabel(
test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id'])
def test_create_metering_label_rule(self):
resource = 'metering_label_rule'
cmd = metering.CreateMeteringLabelRule(
test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
metering_label_id = 'aaa'
remote_ip_prefix = '10.0.0.0/24'
direction = 'ingress'
args = [metering_label_id, remote_ip_prefix, '--direction', direction,
'--excluded']
position_names = ['metering_label_id', 'remote_ip_prefix', 'direction',
'excluded']
position_values = [metering_label_id, remote_ip_prefix,
direction, True]
self._test_create_resource(resource, cmd, metering_label_id,
myid, args, position_names, position_values)
def test_list_metering_label_rules(self):
resources = "metering_label_rules"
cmd = metering.ListMeteringLabelRule(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd)
def test_delete_metering_label_rule(self):
resource = 'metering_label_rule'
cmd = metering.DeleteMeteringLabelRule(
test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)
def test_show_metering_label_rule(self):
resource = 'metering_label_rule'
cmd = metering.ShowMeteringLabelRule(
test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id'])

View File

@ -1,698 +0,0 @@
# 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 itertools
import sys
from unittest import mock
from oslo_serialization import jsonutils
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0 import network
from neutronclient import shell
from neutronclient.tests.unit import test_cli20
class CLITestV20CreateNetworkJSON(test_cli20.CLITestV20Base):
def setUp(self):
super(CLITestV20CreateNetworkJSON, self).setUp(plurals={'tags': 'tag'})
def _test_create_network(self, **kwargs):
cmd = network.CreateNetwork(test_cli20.MyApp(sys.stdout), None)
resource = kwargs.pop('resource', 'network')
name = kwargs.pop('name', 'myname')
myid = kwargs.pop('myid', 'myid')
args = kwargs.pop('args', [name, ])
position_names = kwargs.pop('position_names', ['name', ])
position_values = kwargs.pop('position_values', [name, ])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
**kwargs)
def test_create_network(self):
# Create net: myname.
self._test_create_network()
def test_create_network_with_unicode(self):
# Create net: u'\u7f51\u7edc'.
self._test_create_network(name=u'\u7f51\u7edc')
def test_create_network_description(self):
# Create net: --tenant_id tenantid myname.
name = 'myname'
args = ['--description', 'Nice network', name]
self._test_create_network(name=name,
args=args,
description='Nice network')
def test_create_network_tenant_underscore(self):
# Create net: --tenant_id tenantid myname.
name = 'myname'
args = ['--tenant_id', 'tenantid', name]
self._test_create_network(name=name, args=args, tenant_id="tenantid")
def test_create_network_tenant_dash(self):
# Test dashed options
# Create net: --tenant_id tenantid myname.
name = 'myname'
args = ['--tenant-id', 'tenantid', name]
self._test_create_network(name=name, args=args, tenant_id="tenantid")
def test_create_network_provider_args(self):
# Create net: with --provider arguments.
# Test --provider attributes before network name
name = 'myname'
args = ['--provider:network_type', 'vlan',
'--provider:physical_network', 'physnet1',
'--provider:segmentation_id', '400', name]
position_names = ['provider:network_type',
'provider:physical_network',
'provider:segmentation_id', 'name']
position_values = ['vlan', 'physnet1', '400', name]
self._test_create_network(name=name,
args=args,
position_names=position_names,
position_values=position_values)
def test_create_network_tags(self):
# Create net: myname --tags a b.
name = 'myname'
args = [name, '--tags', 'a', 'b']
self._test_create_network(name=name, args=args, tags=['a', 'b'])
def test_create_network_state_underscore(self):
# Create net: --admin_state_down myname.
name = 'myname'
args = ['--admin_state_down', name, ]
self._test_create_network(name=name, args=args, admin_state_up=False)
def test_create_network_state_dash(self):
# Test dashed options
name = 'myname'
args = ['--admin-state-down', name, ]
self._test_create_network(name=name, args=args, admin_state_up=False)
def test_create_network_vlan_transparent(self):
# Create net: myname --vlan-transparent True.
name = 'myname'
args = ['--vlan-transparent', 'True', name]
self._test_create_network(name=name,
args=args,
vlan_transparent='True')
def test_create_network_with_qos_policy(self):
# Create net: --qos-policy mypolicy.
name = 'myname'
qos_policy_name = 'mypolicy'
args = [name, '--qos-policy', qos_policy_name]
position_names = ['name', 'qos_policy_id']
position_values = [name, qos_policy_name]
self._test_create_network(name=name,
args=args,
position_names=position_names,
position_values=position_values)
def test_create_network_with_az_hint(self):
# Create net: --availability-zone-hint zone1
# --availability-zone-hint zone2.
name = 'myname'
args = ['--availability-zone-hint', 'zone1',
'--availability-zone-hint', 'zone2', name]
position_names = ['availability_zone_hints', 'name']
position_values = [['zone1', 'zone2'], name]
self._test_create_network(name=name,
args=args,
position_names=position_names,
position_values=position_values)
def test_create_network_with_dns_domain(self):
# Create net: --dns-domain my-domain.org.
name = 'myname'
dns_domain_name = 'my-domain.org.'
args = [name, '--dns-domain', dns_domain_name]
position_names = ['name', 'dns_domain']
position_values = [name, dns_domain_name]
self._test_create_network(name=name,
args=args,
position_names=position_names,
position_values=position_values)
class CLITestV20ListNetworkJSON(test_cli20.CLITestV20Base):
def setUp(self):
super(CLITestV20ListNetworkJSON, self).setUp(plurals={'tags': 'tag'})
def test_list_nets_empty_with_column(self):
resources = "networks"
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
reses = {resources: []}
resstr = self.client.serialize(reses)
resp = (test_cli20.MyResp(200), resstr)
# url method body
query = "id=myfakeid"
args = ['-c', 'id', '--', '--id', 'myfakeid']
path = getattr(self.client, resources + "_path")
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request, \
mock.patch.object(network.ListNetwork, "extend_list",
return_value=None) as mock_extend_list:
cmd_parser = cmd.get_parser("list_" + resources)
shell.run_command(cmd, cmd_parser, args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(test_cli20.end_url(path, query),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
_str = self.fake_stdout.make_string()
self.assertEqual('\n', _str)
def _test_list_networks(self, cmd, detail=False, tags=(),
fields_1=(), fields_2=(), page_size=None,
sort_key=(), sort_dir=(), base_args=None,
query=''):
resources = "networks"
with mock.patch.object(network.ListNetwork, "extend_list",
return_value=None) as mock_extend_list:
self._test_list_resources(resources, cmd, detail, tags,
fields_1, fields_2, page_size=page_size,
sort_key=sort_key, sort_dir=sort_dir,
base_args=base_args, query=query)
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
def test_list_nets_pagination(self):
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
with mock.patch.object(network.ListNetwork, "extend_list",
return_value=None) as mock_extend_list:
self._test_list_resources_with_pagination("networks", cmd)
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
def test_list_nets_sort(self):
# list nets:
# --sort-key name --sort-key id --sort-dir asc --sort-dir desc
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_networks(cmd, sort_key=['name', 'id'],
sort_dir=['asc', 'desc'])
def test_list_nets_sort_with_keys_more_than_dirs(self):
# list nets: --sort-key name --sort-key id --sort-dir desc
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_networks(cmd, sort_key=['name', 'id'],
sort_dir=['desc'])
def test_list_nets_sort_with_dirs_more_than_keys(self):
# list nets: --sort-key name --sort-dir desc --sort-dir asc
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_networks(cmd, sort_key=['name'],
sort_dir=['desc', 'asc'])
def test_list_nets_limit(self):
# list nets: -P.
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_networks(cmd, page_size=1000)
def test_list_nets_detail(self):
# list nets: -D.
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_networks(cmd, True)
def test_list_nets_tags(self):
# List nets: -- --tags a b.
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_networks(cmd, tags=['a', 'b'])
def test_list_nets_tags_with_unicode(self):
# List nets: -- --tags u'\u7f51\u7edc'.
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_networks(cmd, tags=[u'\u7f51\u7edc'])
def test_list_nets_detail_tags(self):
# List nets: -D -- --tags a b.
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_networks(cmd, detail=True, tags=['a', 'b'])
def _test_list_nets_extend_subnets(self, data, expected):
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
nets_path = getattr(self.client, 'networks_path')
subnets_path = getattr(self.client, 'subnets_path')
nets_query = ''
filters = ''
for n in data:
for s in n['subnets']:
filters = filters + "&id=%s" % s
subnets_query = 'fields=id&fields=cidr' + filters
with mock.patch.object(cmd, 'get_client',
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient,
"request") as mock_request:
resp1 = (test_cli20.MyResp(200),
self.client.serialize({'networks': data}))
resp2 = (test_cli20.MyResp(200),
self.client.serialize({'subnets': [
{'id': 'mysubid1', 'cidr': '192.168.1.0/24'},
{'id': 'mysubid2', 'cidr': '172.16.0.0/24'},
{'id': 'mysubid3', 'cidr': '10.1.1.0/24'}]}))
mock_request.side_effect = [resp1, resp2]
args = []
cmd_parser = cmd.get_parser('list_networks')
parsed_args = cmd_parser.parse_args(args)
result = cmd.take_action(parsed_args)
mock_get_client.assert_called_with()
self.assertEqual(2, mock_request.call_count)
mock_request.assert_has_calls([
mock.call(
test_cli20.MyUrlComparator(
test_cli20.end_url(nets_path, nets_query),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN})),
mock.call(
test_cli20.MyUrlComparator(
test_cli20.end_url(subnets_path, subnets_query),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))])
_result = [x for x in result[1]]
self.assertEqual(len(expected), len(_result))
for res, exp in zip(_result, expected):
self.assertEqual(len(exp), len(res))
for obsrvd, expctd in zip(res, exp):
self.assertEqual(expctd, obsrvd)
def test_list_nets_extend_subnets(self):
data = [{'id': 'netid1', 'name': 'net1', 'subnets': ['mysubid1']},
{'id': 'netid2', 'name': 'net2', 'subnets': ['mysubid2',
'mysubid3']}]
# id, name, subnets
expected = [('netid1', 'net1', 'mysubid1 192.168.1.0/24'),
('netid2', 'net2',
'mysubid2 172.16.0.0/24\nmysubid3 10.1.1.0/24')]
self._test_list_nets_extend_subnets(data, expected)
def test_list_nets_extend_subnets_no_subnet(self):
data = [{'id': 'netid1', 'name': 'net1', 'subnets': ['mysubid1']},
{'id': 'netid2', 'name': 'net2', 'subnets': ['mysubid4']}]
# id, name, subnets
expected = [('netid1', 'net1', 'mysubid1 192.168.1.0/24'),
('netid2', 'net2', 'mysubid4 ')]
self._test_list_nets_extend_subnets(data, expected)
def test_list_nets_fields(self):
# List nets: --fields a --fields b -- --fields c d.
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_networks(cmd,
fields_1=['a', 'b'], fields_2=['c', 'd'])
def _test_list_nets_columns(self, cmd, returned_body,
args=('-f', 'json')):
resources = 'networks'
with mock.patch.object(network.ListNetwork, "extend_list",
return_value=None) as mock_extend_list:
self._test_list_columns(cmd, resources, returned_body, args=args)
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
def test_list_nets_defined_column(self):
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
returned_body = {"networks": [{"name": "buildname3",
"id": "id3",
"tenant_id": "tenant_3",
"subnets": []}]}
self._test_list_nets_columns(cmd, returned_body,
args=['-f', 'json', '-c', 'id'])
_str = self.fake_stdout.make_string()
returned_networks = jsonutils.loads(_str)
self.assertEqual(1, len(returned_networks))
net = returned_networks[0]
self.assertEqual(1, len(net))
self.assertIn("id", net.keys())
def test_list_nets_with_default_column(self):
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
returned_body = {"networks": [{"name": "buildname3",
"id": "id3",
"tenant_id": "tenant_3",
"subnets": []}]}
self._test_list_nets_columns(cmd, returned_body)
_str = self.fake_stdout.make_string()
returned_networks = jsonutils.loads(_str)
self.assertEqual(1, len(returned_networks))
net = returned_networks[0]
self.assertEqual(3, len(net))
self.assertEqual(0, len(set(net) ^ set(cmd.list_columns)))
def test_list_external_nets_empty_with_column(self):
resources = "networks"
cmd = network.ListExternalNetwork(test_cli20.MyApp(sys.stdout), None)
reses = {resources: []}
resstr = self.client.serialize(reses)
# url method body
query = "router%3Aexternal=True&id=myfakeid"
args = ['-c', 'id', '--', '--id', 'myfakeid']
path = getattr(self.client, resources + "_path")
resp = (test_cli20.MyResp(200), resstr)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request, \
mock.patch.object(network.ListNetwork, "extend_list",
return_value=None) as mock_extend_list:
cmd_parser = cmd.get_parser("list_" + resources)
shell.run_command(cmd, cmd_parser, args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, query), self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
_str = self.fake_stdout.make_string()
self.assertEqual('\n', _str)
def _test_list_external_nets(self, resources, cmd,
detail=False, tags=(),
fields_1=(), fields_2=()):
reses = {resources: [{'id': 'myid1', },
{'id': 'myid2', }, ], }
resstr = self.client.serialize(reses)
resp = (test_cli20.MyResp(200), resstr)
# url method body
query = ""
args = detail and ['-D', ] or []
if fields_1:
for field in fields_1:
args.append('--fields')
args.append(field)
if tags:
args.append('--')
args.append("--tag")
for tag in tags:
args.append(tag)
if (not tags) and fields_2:
args.append('--')
if fields_2:
args.append("--fields")
for field in fields_2:
args.append(field)
for field in itertools.chain(fields_1, fields_2):
if query:
query += "&fields=" + field
else:
query = "fields=" + field
if query:
query += '&router%3Aexternal=True'
else:
query += 'router%3Aexternal=True'
for tag in tags:
if query:
query += "&tag=" + tag
else:
query = "tag=" + tag
if detail:
query = query and query + '&verbose=True' or 'verbose=True'
path = getattr(self.client, resources + "_path")
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request, \
mock.patch.object(network.ListNetwork, "extend_list",
return_value=None) as mock_extend_list:
cmd_parser = cmd.get_parser("list_" + resources)
shell.run_command(cmd, cmd_parser, args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, query), self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
_str = self.fake_stdout.make_string()
self.assertIn('myid1', _str)
def test_list_external_nets_detail(self):
# list external nets: -D.
resources = "networks"
cmd = network.ListExternalNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_external_nets(resources, cmd, True)
def test_list_external_nets_tags(self):
# List external nets: -- --tags a b.
resources = "networks"
cmd = network.ListExternalNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_external_nets(resources,
cmd, tags=['a', 'b'])
def test_list_external_nets_detail_tags(self):
# List external nets: -D -- --tags a b.
resources = "networks"
cmd = network.ListExternalNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_external_nets(resources, cmd,
detail=True, tags=['a', 'b'])
def test_list_external_nets_fields(self):
# List external nets: --fields a --fields b -- --fields c d.
resources = "networks"
cmd = network.ListExternalNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_external_nets(resources, cmd,
fields_1=['a', 'b'],
fields_2=['c', 'd'])
def test_list_shared_networks(self):
# list nets : --shared False
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_list_networks(cmd, base_args='--shared False'.split(),
query='shared=False')
class CLITestV20UpdateNetworkJSON(test_cli20.CLITestV20Base):
def test_update_network_exception(self):
# Update net: myid.
resource = 'network'
cmd = network.UpdateNetwork(test_cli20.MyApp(sys.stdout), None)
self.assertRaises(exceptions.CommandError, self._test_update_resource,
resource, cmd, 'myid', ['myid'], {})
def test_update_network(self):
# Update net: myid --name myname --tags a b.
resource = 'network'
cmd = network.UpdateNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--tags', 'a', 'b', '--description',
'This network takes the scenic route'],
{'name': 'myname', 'tags': ['a', 'b'],
'description': 'This network takes the '
'scenic route'})
def test_update_network_with_unicode(self):
# Update net: myid --name u'\u7f51\u7edc' --tags a b.
resource = 'network'
cmd = network.UpdateNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', u'\u7f51\u7edc',
'--tags', 'a', 'b'],
{'name': u'\u7f51\u7edc',
'tags': ['a', 'b'], }
)
def test_update_network_with_qos_policy(self):
# Update net: myid --qos-policy mypolicy.
resource = 'network'
cmd = network.UpdateNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--qos-policy', 'mypolicy'],
{'qos_policy_id': 'mypolicy', })
def test_update_network_with_no_qos_policy(self):
# Update net: myid --no-qos-policy.
resource = 'network'
cmd = network.UpdateNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--no-qos-policy'],
{'qos_policy_id': None, })
def test_update_network_with_dns_domain(self):
# Update net: myid --dns-domain my-domain.org.
resource = 'network'
cmd = network.UpdateNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--dns-domain', 'my-domain.org.'],
{'dns_domain': 'my-domain.org.', })
def test_update_network_with_no_dns_domain(self):
# Update net: myid --no-dns-domain
resource = 'network'
cmd = network.UpdateNetwork(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--no-dns-domain'],
{'dns_domain': "", })
class CLITestV20ShowNetworkJSON(test_cli20.CLITestV20Base):
def test_show_network(self):
# Show net: --fields id --fields name myid.
resource = 'network'
cmd = network.ShowNetwork(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args,
['id', 'name'])
class CLITestV20DeleteNetworkJSON(test_cli20.CLITestV20Base):
def test_delete_network(self):
# Delete net: myid.
resource = 'network'
cmd = network.DeleteNetwork(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)
def test_bulk_delete_network(self):
# Delete net: myid1 myid2.
resource = 'network'
cmd = network.DeleteNetwork(test_cli20.MyApp(sys.stdout), None)
myid1 = 'myid1'
myid2 = 'myid2'
args = [myid1, myid2]
self._test_delete_resource(resource, cmd, myid1, args, extra_id=myid2)
def test_bulk_delete_network_fail(self):
# Delete net: myid1 myid2.
resource = 'network'
cmd = network.DeleteNetwork(test_cli20.MyApp(sys.stdout), None)
myid1 = 'myid1'
myid2 = 'myid2'
args = [myid1, myid2]
self.assertRaises(exceptions.NeutronCLIError,
self._test_delete_resource,
resource, cmd, myid1, args, extra_id=myid2,
delete_fail=True)
class CLITestV20ExtendListNetworkJSON(test_cli20.CLITestV20Base):
def _build_test_data(self, data):
subnet_ids = []
response = []
filters = ""
for n in data:
if 'subnets' in n:
subnet_ids.extend(n['subnets'])
for subnet_id in n['subnets']:
filters = "%s&id=%s" % (filters, subnet_id)
response.append({'id': subnet_id,
'cidr': '192.168.0.0/16'})
resp_str = self.client.serialize({'subnets': response})
resp = (test_cli20.MyResp(200), resp_str)
return filters, resp
def test_extend_list(self):
data = [{'id': 'netid%d' % i, 'name': 'net%d' % i,
'subnets': ['mysubid%d' % i]}
for i in range(10)]
filters, response = self._build_test_data(data)
path = getattr(self.client, 'subnets_path')
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=response) as mock_request:
known_args, _vs = cmd.get_parser('create_subnets')\
.parse_known_args()
cmd.extend_list(data, known_args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(test_cli20.end_url(
path, 'fields=id&fields=cidr' + filters), self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
def test_extend_list_exceed_max_uri_len(self):
data = [{'id': 'netid%d' % i, 'name': 'net%d' % i,
'subnets': ['mysubid%d' % i]}
for i in range(10)]
# Since in pagination we add &marker=<uuid> (44 symbols), total change
# is 45 symbols. Single subnet takes 40 symbols (id=<uuid>&).
# Because of it marker will take more space than single subnet filter,
# and we expect neutron to send last 2 subnets in separate response.
filters1, response1 = self._build_test_data(data[:len(data) - 2])
filters2, response2 = self._build_test_data(data[len(data) - 2:])
path = getattr(self.client, 'subnets_path')
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient,
"request") as mock_request, \
mock.patch.object(self.client.httpclient, "_check_uri_length",
return_value=None) as mock_check_uri_length:
# 1 char of extra URI len will cause a split in 2 requests
mock_check_uri_length.side_effect = [
exceptions.RequestURITooLong(excess=1), None, None]
mock_request.side_effect = [response1, response2]
known_args, _vs = cmd.get_parser('create_subnets')\
.parse_known_args()
cmd.extend_list(data, known_args)
mock_get_client.assert_called_once_with()
self.assertEqual(2, mock_request.call_count)
mock_request.assert_has_calls([
mock.call(
test_cli20.MyUrlComparator(
test_cli20.end_url(
path, 'fields=id&fields=cidr%s' % filters1),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN})),
mock.call(
test_cli20.MyUrlComparator(
test_cli20.end_url(
path, 'fields=id&fields=cidr%s' % filters2),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))])

View File

@ -1,54 +0,0 @@
# 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 sys
from neutronclient.neutron.v2_0 import network_ip_availability
from neutronclient.tests.unit import test_cli20
class CLITestV20NetworkIPAvailability(test_cli20.CLITestV20Base):
id_field = 'network_id'
def _test_list_network_ip_availability(self, args, query):
resources = "network_ip_availabilities"
cmd = network_ip_availability.ListIpAvailability(test_cli20.MyApp
(sys.stdout), None)
self._test_list_resources(resources, cmd,
base_args=args,
query=query)
def test_list_network_ip_availability(self):
self._test_list_network_ip_availability(args=None,
query='ip_version=4')
def test_list_network_ip_availability_ipv6(self):
self._test_list_network_ip_availability(
args=['--ip-version', '6'], query='ip_version=6')
def test_list_network_ip_availability_net_id_and_ipv4(self):
self._test_list_network_ip_availability(
args=['--ip-version', '4', '--network-id', 'myid'],
query='ip_version=4&network_id=myid')
def test_list_network_ip_availability_net_name_and_tenant_id(self):
self._test_list_network_ip_availability(
args=['--network-name', 'foo', '--tenant-id', 'mytenant'],
query='network_name=foo&tenant_id=mytenant&ip_version=4')
def test_show_network_ip_availability(self):
resource = "network_ip_availability"
cmd = network_ip_availability.ShowIpAvailability(
test_cli20.MyApp(sys.stdout), None)
self._test_show_resource(resource, cmd, self.test_id,
args=[self.test_id])

View File

@ -1,794 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# 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 itertools
import sys
from unittest import mock
from neutronclient.neutron.v2_0 import port
from neutronclient import shell
from neutronclient.tests.unit import test_cli20
class CLITestV20PortJSON(test_cli20.CLITestV20Base):
def setUp(self):
super(CLITestV20PortJSON, self).setUp(plurals={'tags': 'tag'})
def test_create_port(self):
# Create port: netid.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = [netid, '--description', 'DESC']
position_names = ['network_id']
position_values = []
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
description='DESC')
def test_create_port_extra_dhcp_opts_args(self):
# Create port: netid --extra_dhcp_opt.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
extra_dhcp_opts = [{'opt_name': 'bootfile-name',
'opt_value': 'pxelinux.0'},
{'opt_name': 'tftp-server',
'opt_value': '123.123.123.123'},
{'opt_name': 'server-ip-address',
'opt_value': '123.123.123.45'}]
args = [netid]
for dhcp_opt in extra_dhcp_opts:
args += ['--extra-dhcp-opt',
('opt_name=%(opt_name)s,opt_value=%(opt_value)s' %
dhcp_opt)]
position_names = ['network_id', 'extra_dhcp_opts']
position_values = [netid, extra_dhcp_opts]
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_extra_dhcp_opts_args_ip_version(self):
# Create port: netid --extra_dhcp_opt.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
extra_dhcp_opts = [{'opt_name': 'bootfile-name',
'opt_value': 'pxelinux.0',
'ip_version': "4"},
{'opt_name': 'tftp-server',
'opt_value': '2001:192:168::1',
'ip_version': "6"},
{'opt_name': 'server-ip-address',
'opt_value': '123.123.123.45',
'ip_version': "4"}]
args = [netid]
for dhcp_opt in extra_dhcp_opts:
args += ['--extra-dhcp-opt',
('opt_name=%(opt_name)s,opt_value=%(opt_value)s,'
'ip_version=%(ip_version)s' %
dhcp_opt)]
position_names = ['network_id', 'extra_dhcp_opts']
position_values = [netid, extra_dhcp_opts]
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_full(self):
# Create port: --mac_address mac --device_id deviceid netid.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--mac_address', 'mac', '--device_id', 'deviceid', netid]
position_names = ['network_id', 'mac_address', 'device_id']
position_values = [netid, 'mac', 'deviceid']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--mac-address', 'mac', '--device-id', 'deviceid', netid]
position_names = ['network_id', 'mac_address', 'device_id']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_vnic_type_normal(self):
# Create port: --vnic_type normal netid.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--vnic_type', 'normal', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['normal', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--vnic-type', 'normal', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['normal', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_vnic_type_direct(self):
# Create port: --vnic_type direct netid.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--vnic_type', 'direct', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['direct', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--vnic-type', 'direct', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['direct', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_vnic_type_direct_physical(self):
# Create port: --vnic_type direct-physical netid.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--vnic_type', 'direct-physical', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['direct-physical', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--vnic-type', 'direct-physical', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['direct-physical', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_vnic_type_macvtap(self):
# Create port: --vnic_type macvtap netid.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--vnic_type', 'macvtap', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['macvtap', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--vnic-type', 'macvtap', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['macvtap', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_vnic_type_baremetal(self):
# Create port: --vnic_type baremetal netid.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--vnic_type', 'baremetal', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['baremetal', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--vnic-type', 'baremetal', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['baremetal', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_vnic_type_smart_nic(self):
# Create port: --vnic_type smart-nic netid.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--vnic_type', 'smart-nic', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['smart-nic', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--vnic-type', 'smart-nic', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['smart-nic', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_with_binding_profile(self):
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--binding_profile', '{"foo":"bar"}', netid]
position_names = ['binding:profile', 'network_id']
position_values = [{'foo': 'bar'}, netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--binding-profile', '{"foo":"bar"}', netid]
position_names = ['binding:profile', 'network_id']
position_values = [{'foo': 'bar'}, netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_tenant(self):
# Create port: --tenant_id tenantid netid.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--tenant_id', 'tenantid', netid, ]
position_names = ['network_id']
position_values = []
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
# Test dashed options
args = ['--tenant-id', 'tenantid', netid, ]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_port_tags(self):
# Create port: netid mac_address device_id --tags a b.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = [netid, '--tags', 'a', 'b']
position_names = ['network_id']
position_values = []
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tags=['a', 'b'])
def test_create_port_secgroup(self):
# Create port: --security-group sg1_id netid.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--security-group', 'sg1_id', netid]
position_names = ['network_id', 'security_groups']
position_values = [netid, ['sg1_id']]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_secgroups(self):
# Create port: <security_groups> netid
# The <security_groups> are --security-group sg1_id
# --security-group sg2_id
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--security-group', 'sg1_id',
'--security-group', 'sg2_id',
netid]
position_names = ['network_id', 'security_groups']
position_values = [netid, ['sg1_id', 'sg2_id']]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_secgroup_off(self):
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--no-security-groups', netid]
position_names = ['network_id', 'security_groups']
position_values = [netid, []]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_secgroups_list(self):
# Create port: netid <security_groups>
# The <security_groups> are --security-groups list=true sg_id1 sg_id2
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = [netid, '--security-groups', 'list=true', 'sg_id1', 'sg_id2']
position_names = ['network_id', 'security_groups']
position_values = [netid, ['sg_id1', 'sg_id2']]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_with_qos_policy(self):
# Create port: --qos-policy mypolicy.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
qos_policy_name = 'mypolicy'
args = [netid, '--qos-policy', qos_policy_name]
position_names = ['network_id', 'qos_policy_id']
position_values = [netid, qos_policy_name]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_with_dns_name(self):
# Create port: --dns-name my-port.
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
dns_name_name = 'my-port'
args = [netid, '--dns-name', dns_name_name]
position_names = ['network_id', 'dns_name']
position_values = [netid, dns_name_name]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_with_allowed_address_pair_ipaddr(self):
# Create port:
# --allowed-address-pair ip_address=addr0
# --allowed-address-pair ip_address=addr1
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
pairs = [{'ip_address': '123.123.123.123'},
{'ip_address': '123.123.123.45'}]
args = [netid,
'--allowed-address-pair',
'ip_address=123.123.123.123',
'--allowed-address-pair',
'ip_address=123.123.123.45']
position_names = ['network_id', 'allowed_address_pairs']
position_values = [netid, pairs]
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_with_allowed_address_pair(self):
# Create port:
# --allowed-address-pair ip_address=addr0,mac_address=mac0
# --allowed-address-pair ip_address=addr1,mac_address=mac1
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
pairs = [{'ip_address': '123.123.123.123',
'mac_address': '10:00:00:00:00:00'},
{'ip_address': '123.123.123.45',
'mac_address': '10:00:00:00:00:01'}]
args = [netid,
'--allowed-address-pair',
'ip_address=123.123.123.123,mac_address=10:00:00:00:00:00',
'--allowed-address-pair',
'ip_address=123.123.123.45,mac_address=10:00:00:00:00:01']
position_names = ['network_id', 'allowed_address_pairs']
position_values = [netid, pairs]
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_list_ports(self):
# List ports: -D.
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_ports_pagination(self):
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_ports_sort(self):
# list ports:
# --sort-key name --sort-key id --sort-key asc --sort-key desc
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_ports_limit(self):
# list ports: -P.
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_list_ports_tags(self):
# List ports: -- --tags a b.
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, tags=['a', 'b'])
def test_list_ports_detail_tags(self):
# List ports: -D -- --tags a b.
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, detail=True, tags=['a', 'b'])
def test_list_ports_fields(self):
# List ports: --fields a --fields b -- --fields c d.
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
fields_1=['a', 'b'], fields_2=['c', 'd'])
def test_list_ports_with_fixed_ips_in_csv(self):
# List ports: -f csv.
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
fixed_ips = [{"subnet_id": "30422057-d6df-4c90-8314-aefb5e326666",
"ip_address": "10.0.0.12"},
{"subnet_id": "30422057-d6df-4c90-8314-aefb5e326666",
"ip_address": "10.0.0.4"}]
contents = [{'name': 'name1', 'fixed_ips': fixed_ips}]
self._test_list_resources(resources, cmd, True,
response_contents=contents,
output_format='csv')
def _test_list_router_port(self, resources, cmd,
myid, detail=False, tags=(),
fields_1=(), fields_2=()):
reses = {resources: [{'id': 'myid1', },
{'id': 'myid2', }, ], }
resstr = self.client.serialize(reses)
# url method body
query = ""
args = detail and ['-D', ] or []
if fields_1:
for field in fields_1:
args.append('--fields')
args.append(field)
args.append(myid)
if tags:
args.append('--')
args.append("--tag")
for tag in tags:
args.append(tag)
if (not tags) and fields_2:
args.append('--')
if fields_2:
args.append("--fields")
for field in fields_2:
args.append(field)
for field in itertools.chain(fields_1, fields_2):
if query:
query += "&fields=" + field
else:
query = "fields=" + field
for tag in tags:
if query:
query += "&tag=" + tag
else:
query = "tag=" + tag
if detail:
query = query and query + '&verbose=True' or 'verbose=True'
query = query and query + '&device_id=%s' or 'device_id=%s'
path = getattr(self.client, resources + "_path")
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=(test_cli20.MyResp(200),
resstr)) as mock_request:
cmd_parser = cmd.get_parser("list_" + resources)
shell.run_command(cmd, cmd_parser, args)
self.assert_mock_multiple_calls_with_same_arguments(
mock_get_client, mock.call(), 2)
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, query % myid), self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
_str = self.fake_stdout.make_string()
self.assertIn('myid1', _str)
def test_list_router_ports(self):
# List router ports: -D.
resources = "ports"
cmd = port.ListRouterPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_router_port(resources, cmd,
self.test_id, True)
def test_list_router_ports_tags(self):
# List router ports: -- --tags a b.
resources = "ports"
cmd = port.ListRouterPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_router_port(resources, cmd,
self.test_id, tags=['a', 'b'])
def test_list_router_ports_detail_tags(self):
# List router ports: -D -- --tags a b.
resources = "ports"
cmd = port.ListRouterPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_router_port(resources, cmd, self.test_id,
detail=True, tags=['a', 'b'])
def test_list_router_ports_fields(self):
# List ports: --fields a --fields b -- --fields c d.
resources = "ports"
cmd = port.ListRouterPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_router_port(resources, cmd, self.test_id,
fields_1=['a', 'b'],
fields_2=['c', 'd'])
def test_update_port(self):
# Update port: myid --name myname --admin-state-up False --tags a b.
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--admin-state-up', 'False',
'--description', 'garbage',
'--tags', 'a', 'b'],
{'name': 'myname',
'admin_state_up': 'False',
'description': 'garbage',
'tags': ['a', 'b'], })
def test_update_port_secgroup(self):
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = ['--security-group', 'sg1_id', myid]
updatefields = {'security_groups': ['sg1_id']}
self._test_update_resource(resource, cmd, myid, args, updatefields)
def test_update_port_secgroups(self):
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = ['--security-group', 'sg1_id',
'--security-group', 'sg2_id',
myid]
updatefields = {'security_groups': ['sg1_id', 'sg2_id']}
self._test_update_resource(resource, cmd, myid, args, updatefields)
def test_update_port_extra_dhcp_opts(self):
# Update port: myid --extra_dhcp_opt.
resource = 'port'
myid = 'myid'
args = [myid,
'--extra-dhcp-opt',
"opt_name=bootfile-name,opt_value=pxelinux.0",
'--extra-dhcp-opt',
"opt_name=tftp-server,opt_value=123.123.123.123",
'--extra-dhcp-opt',
"opt_name=server-ip-address,opt_value=123.123.123.45"
]
updatedfields = {'extra_dhcp_opts': [{'opt_name': 'bootfile-name',
'opt_value': 'pxelinux.0'},
{'opt_name': 'tftp-server',
'opt_value': '123.123.123.123'},
{'opt_name': 'server-ip-address',
'opt_value': '123.123.123.45'}]}
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, myid, args, updatedfields)
def test_update_port_fixed_ip(self):
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
subnet_id = 'subnet_id'
ip_addr = '123.123.123.123'
args = [myid,
'--fixed-ip',
"subnet_id=%(subnet_id)s,ip_address=%(ip_addr)s" %
{'subnet_id': subnet_id,
'ip_addr': ip_addr}]
updated_fields = {"fixed_ips": [{'subnet_id': subnet_id,
'ip_address': ip_addr}]}
self._test_update_resource(resource, cmd, myid, args, updated_fields)
def test_update_port_device_id_device_owner(self):
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = ['--device-id', 'dev_id', '--device-owner', 'fake', myid]
updatefields = {'device_id': 'dev_id',
'device_owner': 'fake'}
self._test_update_resource(resource, cmd, myid, args, updatefields)
def test_update_port_extra_dhcp_opts_ip_version(self):
# Update port: myid --extra_dhcp_opt.
resource = 'port'
myid = 'myid'
args = [myid,
'--extra-dhcp-opt',
"opt_name=bootfile-name,opt_value=pxelinux.0,ip_version=4",
'--extra-dhcp-opt',
"opt_name=tftp-server,opt_value=2001:192:168::1,ip_version=6",
'--extra-dhcp-opt',
"opt_name=server-ip-address,opt_value=null,ip_version=4"
]
updatedfields = {'extra_dhcp_opts': [{'opt_name': 'bootfile-name',
'opt_value': 'pxelinux.0',
'ip_version': '4'},
{'opt_name': 'tftp-server',
'opt_value': '2001:192:168::1',
'ip_version': '6'},
{'opt_name': 'server-ip-address',
'opt_value': None,
'ip_version': '4'}]}
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, myid, args, updatedfields)
def test_update_port_with_qos_policy(self):
# Update port: myid --qos-policy mypolicy.
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--qos-policy', 'mypolicy'],
{'qos_policy_id': 'mypolicy', })
def test_update_port_with_no_qos_policy(self):
# Update port: myid --no-qos-policy.
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--no-qos-policy'],
{'qos_policy_id': None, })
def test_update_port_with_dns_name(self):
# Update port: myid --dns-name my-port.
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--dns-name', 'my-port'],
{'dns_name': 'my-port', })
def test_update_port_with_no_dns_name(self):
# Update port: myid --no-dns-name
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--no-dns-name'],
{'dns_name': "", })
def test_delete_extra_dhcp_opts_from_port(self):
resource = 'port'
myid = 'myid'
args = [myid,
'--extra-dhcp-opt',
"opt_name=bootfile-name,opt_value=null",
'--extra-dhcp-opt',
"opt_name=tftp-server,opt_value=123.123.123.123",
'--extra-dhcp-opt',
"opt_name=server-ip-address,opt_value=123.123.123.45"
]
# the client code will change the null to None and send to server,
# where its interpreted as delete the DHCP option on the port.
updatedfields = {'extra_dhcp_opts': [{'opt_name': 'bootfile-name',
'opt_value': None},
{'opt_name': 'tftp-server',
'opt_value': '123.123.123.123'},
{'opt_name': 'server-ip-address',
'opt_value': '123.123.123.45'}]}
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, myid, args, updatedfields)
def test_update_port_security_group_off(self):
# Update port: --no-security-groups myid.
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['--no-security-groups', 'myid'],
{'security_groups': []})
def test_update_port_allowed_address_pair_ipaddr(self):
# Update port(ip_address only):
# --allowed-address-pairs ip_address=addr0
# --allowed-address-pairs ip_address=addr1
import sys
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
pairs = [{'ip_address': '123.123.123.123'},
{'ip_address': '123.123.123.45'}]
args = [myid,
'--allowed-address-pair',
'ip_address=123.123.123.123',
'--allowed-address-pair',
'ip_address=123.123.123.45']
updatefields = {'allowed_address_pairs': pairs}
self._test_update_resource(resource, cmd, myid, args, updatefields)
def test_update_port_allowed_address_pair(self):
# Update port:
# --allowed-address-pair ip_address=addr0,mac_address=mac0
# --allowed-address-pair ip_address_addr1,mac_address=mac1
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
pairs = [{'ip_address': '123.123.123.123',
'mac_address': '10:00:00:00:00:00'},
{'ip_address': '123.123.123.45',
'mac_address': '10:00:00:00:00:01'}]
args = [myid,
'--allowed-address-pair',
'ip_address=123.123.123.123,mac_address=10:00:00:00:00:00',
'--allowed-address-pair',
'ip_address=123.123.123.45,mac_address=10:00:00:00:00:01']
updatefields = {'allowed_address_pairs': pairs}
self._test_update_resource(resource, cmd, myid, args, updatefields)
def test_update_port_allowed_address_pairs_off(self):
# Update port: --no-allowed-address-pairs.
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['--no-allowed-address-pairs', 'myid'],
{'allowed_address_pairs': []})
def test_show_port(self):
# Show port: --fields id --fields name myid.
resource = 'port'
cmd = port.ShowPort(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_delete_port(self):
# Delete port: myid.
resource = 'port'
cmd = port.DeletePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)

View File

@ -1,100 +0,0 @@
# Copyright 2016 Cisco Systems
# 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 sys
from neutronclient.neutron.v2_0 import purge
from neutronclient.tests.unit import test_cli20
class CLITestV20Purge(test_cli20.CLITestV20Base):
def setUp(self):
super(CLITestV20Purge, self).setUp()
self.resource_types = ['floatingip', 'port', 'router',
'network', 'security_group']
def _generate_resources_dict(self, value=0):
resources_dict = {}
resources_dict['true'] = value
for resource_type in self.resource_types:
resources_dict[resource_type] = value
return resources_dict
def _verify_suffix(self, resources, message):
for resource, value in resources.items():
if value > 0:
suffix = list('%(value)d %(resource)s' %
{'value': value, 'resource': resource})
if value != 1:
suffix.append('s')
suffix = ''.join(suffix)
self.assertIn(suffix, message)
else:
self.assertNotIn(resource, message)
def _verify_message(self, message, deleted, failed):
message = message.split('.')
success_prefix = "Deleted "
failure_prefix = "The following resources could not be deleted: "
if not deleted['true']:
for msg in message:
self.assertNotIn(success_prefix, msg)
message = message[0]
if not failed['true']:
expected = 'Tenant has no supported resources'
self.assertEqual(expected, message)
else:
self.assertIn(failure_prefix, message)
self._verify_suffix(failed, message)
else:
resources_deleted = message[0]
self.assertIn(success_prefix, resources_deleted)
self._verify_suffix(deleted, resources_deleted)
if failed['true']:
resources_failed = message[1]
self.assertIn(failure_prefix, resources_failed)
self._verify_suffix(failed, resources_failed)
else:
for msg in message:
self.assertNotIn(failure_prefix, msg)
def _verify_result(self, my_purge, deleted, failed):
message = my_purge._build_message(deleted, failed, failed['true'])
self._verify_message(message, deleted, failed)
def test_build_message(self):
my_purge = purge.Purge(test_cli20.MyApp(sys.stdout), None)
# Verify message when tenant has no supported resources
deleted = self._generate_resources_dict()
failed = self._generate_resources_dict()
self._verify_result(my_purge, deleted, failed)
# Verify message when tenant has supported resources,
# and they are all deleteable
deleted = self._generate_resources_dict(1)
self._verify_result(my_purge, deleted, failed)
# Verify message when tenant has supported resources,
# and some are not deleteable
failed = self._generate_resources_dict(1)
self._verify_result(my_purge, deleted, failed)
# Verify message when tenant has supported resources,
# and all are not deleteable
deleted = self._generate_resources_dict()
self._verify_result(my_purge, deleted, failed)

View File

@ -1,134 +0,0 @@
# Copyright 2015 Huawei Technologies India Pvt 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 sys
import testscenarios
from neutronclient.neutron.v2_0 import rbac
from neutronclient.tests.unit import test_cli20
load_tests = testscenarios.load_tests_apply_scenarios
class CLITestV20RBACBaseJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['rbac_policy']
scenarios = [
('network rbac objects',
{'object_type_name': 'network', 'object_type_val': 'network'}),
('qos policy rbac objects',
{'object_type_name': 'qos-policy', 'object_type_val': 'qos_policy'}),
]
def test_create_rbac_policy_with_mandatory_params(self):
# Create rbac: rbac_object --type <object_type_name> --action
# access_as_shared
resource = 'rbac_policy'
cmd = rbac.CreateRBACPolicy(test_cli20.MyApp(sys.stdout), None)
name = 'rbac_object'
myid = 'myid'
args = [name, '--type', self.object_type_name,
'--action', 'access_as_shared']
position_names = ['object_id', 'object_type',
'target_tenant', 'action']
position_values = [name, self.object_type_val, '*',
'access_as_shared']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_rbac_policy_with_all_params(self):
# Create rbac: rbac_object --type <object_type_name>
# --target-tenant tenant_id --action access_as_external
resource = 'rbac_policy'
cmd = rbac.CreateRBACPolicy(test_cli20.MyApp(sys.stdout), None)
name = 'rbac_object'
myid = 'myid'
args = [name, '--type', self.object_type_name,
'--target-tenant', 'tenant_id',
'--action', 'access_as_external']
position_names = ['object_id', 'object_type',
'target_tenant', 'action']
position_values = [name, self.object_type_val, 'tenant_id',
'access_as_external']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_rbac_policy_with_unicode(self):
# Create rbac policy u'\u7f51\u7edc'.
resource = 'rbac_policy'
cmd = rbac.CreateRBACPolicy(test_cli20.MyApp(sys.stdout), None)
name = u'\u7f51\u7edc'
myid = 'myid'
args = [name, '--type', self.object_type_name,
'--target-tenant', 'tenant_id',
'--action', 'access_as_external']
position_names = ['object_id', 'object_type',
'target_tenant', 'action']
position_values = [name, self.object_type_val, 'tenant_id',
'access_as_external']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_update_rbac_policy(self):
# rbac-update <rbac-uuid> --target-tenant <other-tenant-uuid>.
resource = 'rbac_policy'
cmd = rbac.UpdateRBACPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--target-tenant', 'tenant_id'],
{'target_tenant': 'tenant_id', })
def test_delete_rbac_policy(self):
# rbac-delete my-id.
resource = 'rbac_policy'
cmd = rbac.DeleteRBACPolicy(test_cli20.MyApp(sys.stdout), None)
my_id = 'myid1'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)
def test_list_rbac_policies(self):
# rbac-list.
resources = "rbac_policies"
cmd = rbac.ListRBACPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_rbac_policies_pagination(self):
# rbac-list with pagination.
resources = "rbac_policies"
cmd = rbac.ListRBACPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_rbac_policies_sort(self):
# sorted list:
# rbac-list --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = "rbac_policies"
cmd = rbac.ListRBACPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_rbac_policies_limit(self):
# size (1000) limited list: rbac-list -P.
resources = "rbac_policies"
cmd = rbac.ListRBACPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_rbac_policy(self):
# rbac-show test_id.
resource = 'rbac_policy'
cmd = rbac.ShowRBACPolicy(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])

View File

@ -1,434 +0,0 @@
# Copyright 2012 VMware, 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 sys
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0 import router
from neutronclient.tests.unit import test_cli20
class CLITestV20RouterJSON(test_cli20.CLITestV20Base):
def test_create_router(self):
# Create router: router1.
resource = 'router'
cmd = router.CreateRouter(test_cli20.MyApp(sys.stdout), None)
name = 'router1'
myid = 'myid'
args = [name, '--description', 'rooter']
position_names = ['name', ]
position_values = [name, ]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
description='rooter')
def test_create_router_flavor(self):
resource = 'router'
cmd = router.CreateRouter(test_cli20.MyApp(sys.stdout), None)
name = 'router1'
myid = 'myid'
flavor = 'router-flavor'
args = [name, '--flavor', flavor]
position_names = ['name', ]
position_values = [name, flavor]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
flavor_id='router-flavor')
def test_create_router_tenant(self):
# Create router: --tenant_id tenantid myname.
resource = 'router'
cmd = router.CreateRouter(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
args = ['--tenant_id', 'tenantid', name]
position_names = ['name', ]
position_values = [name, ]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_router_admin_state(self):
# Create router: --admin_state_down myname.
resource = 'router'
cmd = router.CreateRouter(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
args = ['--admin_state_down', name, ]
position_names = ['name', ]
position_values = [name, ]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
admin_state_up=False)
def _create_router_distributed_or_ha(self, distributed=None, ha=None):
# Create router: --distributed distributed --ha ha myname.
resource = 'router'
cmd = router.CreateRouter(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
args = []
if distributed is not None:
args += ['--distributed', str(distributed)]
if ha is not None:
args += ['--ha', str(ha)]
args.append(name)
position_names = ['name', ]
position_values = [name, ]
expected = {}
if distributed is not None:
expected['distributed'] = str(distributed)
if ha is not None:
expected['ha'] = str(ha)
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
**expected)
def test_create_router_distributed_True(self):
# Create router: --distributed=True.
self._create_router_distributed_or_ha(distributed='True')
def test_create_router_ha_with_True(self):
self._create_router_distributed_or_ha(ha='True')
def test_create_router_ha_with_true(self):
self._create_router_distributed_or_ha(ha='true')
def test_create_router_ha_with_False(self):
self._create_router_distributed_or_ha(ha='False')
def test_create_router_ha_with_false(self):
self._create_router_distributed_or_ha(ha='false')
def test_create_router_distributed_False(self):
# Create router: --distributed=False.
self._create_router_distributed_or_ha(distributed='False')
def test_create_router_distributed_true(self):
# Create router: --distributed=true.
self._create_router_distributed_or_ha(distributed='true')
def test_create_router_distributed_false(self):
# Create router: --distributed=false.
self._create_router_distributed_or_ha(distributed='false')
def test_create_router_with_az_hint(self):
# Create router: --availability-zone-hint zone1
# --availability-zone-hint zone2.
resource = 'router'
cmd = router.CreateRouter(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
args = ['--availability-zone-hint', 'zone1',
'--availability-zone-hint', 'zone2', name]
position_names = ['availability_zone_hints', 'name']
position_values = [['zone1', 'zone2'], name]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_list_routers_detail(self):
# list routers: -D.
resources = "routers"
cmd = router.ListRouter(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_routers_pagination(self):
resources = "routers"
cmd = router.ListRouter(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_routers_sort(self):
# list routers:
# --sort-key name --sort-key id --sort-key asc --sort-key desc
resources = "routers"
cmd = router.ListRouter(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_routers_limit(self):
# list routers: -P.
resources = "routers"
cmd = router.ListRouter(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_update_router_exception(self):
# Update router: myid.
resource = 'router'
cmd = router.UpdateRouter(test_cli20.MyApp(sys.stdout), None)
self.assertRaises(exceptions.CommandError, self._test_update_resource,
resource, cmd, 'myid', ['myid'], {})
def test_update_router(self):
# Update router: myid --name myname --tags a b.
resource = 'router'
cmd = router.UpdateRouter(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--description', ':D'],
{'name': 'myname', 'description': ':D'})
def test_update_router_admin_state(self):
# Update router: myid --admin-state-up <True|False>.
resource = 'router'
cmd = router.UpdateRouter(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--admin-state-up', 'True'],
{'admin_state_up': 'True'}
)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--admin-state-up', 'true'],
{'admin_state_up': 'true'}
)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--admin-state-up', 'False'],
{'admin_state_up': 'False'}
)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--admin-state-up', 'false'],
{'admin_state_up': 'false'}
)
def test_update_router_distributed(self):
# Update router: myid --distributed <True|False>.
resource = 'router'
cmd = router.UpdateRouter(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--distributed', 'True'],
{'distributed': 'True'}
)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--distributed', 'true'],
{'distributed': 'true'}
)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--distributed', 'False'],
{'distributed': 'False'}
)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--distributed', 'false'],
{'distributed': 'false'}
)
def test_update_router_no_routes(self):
# Update router: myid --no-routes
resource = 'router'
cmd = router.UpdateRouter(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--no-routes'],
{'routes': None})
def test_update_router_add_route(self):
# Update router: myid --route destination=10.0.3.0/24,nexthop=10.0.0.10
resource = 'router'
cmd = router.UpdateRouter(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid,
'--route',
'destination=10.0.3.0/24,nexthop=10.0.0.10']
routes = [{'destination': '10.0.3.0/24',
'nexthop': '10.0.0.10'}]
updatefields = {'routes': routes}
self._test_update_resource(resource, cmd, myid, args, updatefields)
def test_update_router_add_routes(self):
# Update router: myid --route destination=10.0.3.0/24,nexthop=10.0.0.10
# --route destination=fd7a:1d63:2063::/64,
# nexthop=fd7a:1d63:2063:0:f816:3eff:fe0e:a697
resource = 'router'
cmd = router.UpdateRouter(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid,
'--route',
'destination=10.0.3.0/24,nexthop=10.0.0.10',
'--route',
'destination=fd7a:1d63:2063::/64,'
'nexthop=fd7a:1d63:2063:0:f816:3eff:fe0e:a697']
routes = [{'destination': '10.0.3.0/24',
'nexthop': '10.0.0.10'},
{'destination': 'fd7a:1d63:2063::/64',
'nexthop': 'fd7a:1d63:2063:0:f816:3eff:fe0e:a697'}]
updatefields = {'routes': routes}
self._test_update_resource(resource, cmd, myid, args, updatefields)
def test_update_router_no_routes_with_add_route(self):
# Update router: --no-routes with --route
resource = 'router'
cmd = router.UpdateRouter(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid,
'--no-routes',
'--route',
'destination=10.0.3.0/24,nexthop=10.0.0.10']
exception = self.assertRaises(SystemExit,
self._test_update_resource,
resource, cmd, myid, args, None)
self.assertEqual(2, exception.code)
def test_delete_router(self):
# Delete router: myid.
resource = 'router'
cmd = router.DeleteRouter(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)
def test_show_router(self):
# Show router: myid.
resource = 'router'
cmd = router.ShowRouter(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args,
['id', 'name'])
def _test_add_remove_interface(self, action, mode, cmd, args):
resource = 'router'
subcmd = '%s_router_interface' % action
if mode == 'port':
body = {'port_id': 'portid'}
else:
body = {'subnet_id': 'subnetid'}
if action == 'add':
retval = {'subnet_id': 'subnetid', 'port_id': 'portid'}
retval = self.client.serialize(retval)
expected_code = 200
else:
retval = None
expected_code = 204
self._test_update_resource_action(resource, cmd, 'myid',
subcmd, args,
body, expected_code, retval)
def test_add_interface_compat(self):
# Add interface to router: myid subnetid.
cmd = router.AddInterfaceRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'subnetid']
self._test_add_remove_interface('add', 'subnet', cmd, args)
def test_add_interface_by_subnet(self):
# Add interface to router: myid subnet=subnetid.
cmd = router.AddInterfaceRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'subnet=subnetid']
self._test_add_remove_interface('add', 'subnet', cmd, args)
def test_add_interface_by_port(self):
# Add interface to router: myid port=portid.
cmd = router.AddInterfaceRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'port=portid']
self._test_add_remove_interface('add', 'port', cmd, args)
def test_del_interface_compat(self):
# Delete interface from router: myid subnetid.
cmd = router.RemoveInterfaceRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'subnetid']
self._test_add_remove_interface('remove', 'subnet', cmd, args)
def test_del_interface_by_subnet(self):
# Delete interface from router: myid subnet=subnetid.
cmd = router.RemoveInterfaceRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'subnet=subnetid']
self._test_add_remove_interface('remove', 'subnet', cmd, args)
def test_del_interface_by_port(self):
# Delete interface from router: myid port=portid.
cmd = router.RemoveInterfaceRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'port=portid']
self._test_add_remove_interface('remove', 'port', cmd, args)
def test_set_gateway(self):
# Set external gateway for router: myid externalid.
resource = 'router'
cmd = router.SetGatewayRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'externalid']
self._test_update_resource(resource, cmd, 'myid',
args,
{"external_gateway_info":
{"network_id": "externalid"}}
)
def test_set_gateway_enable_snat(self):
# enable external gateway for router: myid externalid.
resource = 'router'
cmd = router.SetGatewayRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'externalid', '--enable-snat']
self._test_update_resource(resource, cmd, 'myid',
args,
{"external_gateway_info":
{"network_id": "externalid",
"enable_snat": True}}
)
def test_set_gateway_disable_snat(self):
# set external gateway for router: myid externalid.
resource = 'router'
cmd = router.SetGatewayRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'externalid', '--disable-snat']
self._test_update_resource(resource, cmd, 'myid',
args,
{"external_gateway_info":
{"network_id": "externalid",
"enable_snat": False}}
)
def test_set_gateway_external_ip(self):
# set external gateway for router: myid externalid --fixed-ip ...
resource = 'router'
cmd = router.SetGatewayRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'externalid', '--fixed-ip', 'ip_address=10.0.0.2']
self._test_update_resource(resource, cmd, 'myid',
args,
{"external_gateway_info":
{"network_id": "externalid",
"external_fixed_ips": [
{"ip_address": "10.0.0.2"}]}}
)
def test_set_gateway_external_subnet(self):
# set external gateway for router: myid externalid --fixed-ip ...
resource = 'router'
cmd = router.SetGatewayRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'externalid', '--fixed-ip', 'subnet_id=mysubnet']
self._test_update_resource(resource, cmd, 'myid',
args,
{"external_gateway_info":
{"network_id": "externalid",
"external_fixed_ips": [
{"subnet_id": "mysubnet"}]}}
)
def test_set_gateway_external_ip_and_subnet(self):
# set external gateway for router: myid externalid --fixed-ip ...
resource = 'router'
cmd = router.SetGatewayRouter(test_cli20.MyApp(sys.stdout), None)
args = ['myid', 'externalid', '--fixed-ip',
'ip_address=10.0.0.2,subnet_id=mysubnet']
self._test_update_resource(resource, cmd, 'myid',
args,
{"external_gateway_info":
{"network_id": "externalid",
"external_fixed_ips": [
{"subnet_id": "mysubnet",
"ip_address": "10.0.0.2"}]}}
)
def test_remove_gateway(self):
# Remove external gateway from router: externalid.
resource = 'router'
cmd = router.RemoveGatewayRouter(test_cli20.MyApp(sys.stdout), None)
args = ['externalid']
self._test_update_resource(resource, cmd, 'externalid',
args, {"external_gateway_info": {}}
)

View File

@ -1,657 +0,0 @@
# Copyright 2012 Red Hat
# 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 sys
from unittest import mock
import urllib.parse as urlparse
from oslo_utils import uuidutils
from neutronclient.common import exceptions
from neutronclient.common import utils
from neutronclient.neutron.v2_0 import securitygroup
from neutronclient.tests.unit import test_cli20
class CLITestV20SecurityGroupsJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['security_group', 'security_group_rule']
def test_create_security_group(self):
# Create security group: webservers.
resource = 'security_group'
cmd = securitygroup.CreateSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
name = 'webservers'
myid = 'myid'
args = [name, ]
position_names = ['name']
position_values = [name]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_security_group_tenant(self):
# Create security group: webservers.
resource = 'security_group'
cmd = securitygroup.CreateSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
name = 'webservers'
description = 'my webservers'
myid = 'myid'
args = ['--tenant_id', 'tenant_id', '--description', description, name]
position_names = ['name', 'description']
position_values = [name, description]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenant_id')
def test_create_security_group_with_description(self):
# Create security group: webservers.
resource = 'security_group'
cmd = securitygroup.CreateSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
name = 'webservers'
description = 'my webservers'
myid = 'myid'
args = [name, '--description', description]
position_names = ['name', 'description']
position_values = [name, description]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_list_security_groups(self):
resources = "security_groups"
cmd = securitygroup.ListSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_security_groups_pagination(self):
resources = "security_groups"
cmd = securitygroup.ListSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_security_groups_sort(self):
resources = "security_groups"
cmd = securitygroup.ListSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_security_groups_limit(self):
resources = "security_groups"
cmd = securitygroup.ListSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_security_group_id(self):
resource = 'security_group'
cmd = securitygroup.ShowSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id'])
def test_show_security_group_id_name(self):
resource = 'security_group'
cmd = securitygroup.ShowSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_delete_security_group(self):
# Delete security group: myid.
resource = 'security_group'
cmd = securitygroup.DeleteSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)
def test_update_security_group(self):
# Update security group: myid --name myname --description desc.
resource = 'security_group'
cmd = securitygroup.UpdateSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--description', 'mydescription'],
{'name': 'myname',
'description': 'mydescription'}
)
def test_update_security_group_with_unicode(self):
resource = 'security_group'
cmd = securitygroup.UpdateSecurityGroup(
test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', u'\u7f51\u7edc',
'--description', u'\u7f51\u7edc'],
{'name': u'\u7f51\u7edc',
'description': u'\u7f51\u7edc'}
)
def test_create_security_group_rule_full(self):
# Create security group rule.
resource = 'security_group_rule'
cmd = securitygroup.CreateSecurityGroupRule(
test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
direction = 'ingress'
ethertype = 'IPv4'
protocol = 'tcp'
port_range_min = '22'
port_range_max = '22'
remote_ip_prefix = '10.0.0.0/24'
security_group_id = '1'
remote_group_id = '1'
args = ['--remote_ip_prefix', remote_ip_prefix, '--direction',
direction, '--ethertype', ethertype, '--protocol', protocol,
'--port_range_min', port_range_min, '--port_range_max',
port_range_max, '--remote_group_id', remote_group_id,
security_group_id, '--description', 'PCI policy 1421912']
position_names = ['remote_ip_prefix', 'direction', 'ethertype',
'protocol', 'port_range_min', 'port_range_max',
'remote_group_id', 'security_group_id']
position_values = [remote_ip_prefix, direction, ethertype, protocol,
port_range_min, port_range_max, remote_group_id,
security_group_id]
self._test_create_resource(resource, cmd, None, myid, args,
position_names, position_values,
description='PCI policy 1421912')
def test_create_security_group_rule_with_integer_protocol_value(self):
resource = 'security_group_rule'
cmd = securitygroup.CreateSecurityGroupRule(
test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
direction = 'ingress'
ethertype = 'IPv4'
protocol = '2'
port_range_min = '22'
port_range_max = '22'
remote_ip_prefix = '10.0.0.0/24'
security_group_id = '1'
remote_group_id = '1'
args = ['--remote_ip_prefix', remote_ip_prefix, '--direction',
direction, '--ethertype', ethertype, '--protocol', protocol,
'--port_range_min', port_range_min, '--port_range_max',
port_range_max, '--remote_group_id', remote_group_id,
security_group_id]
position_names = ['remote_ip_prefix', 'direction', 'ethertype',
'protocol', 'port_range_min', 'port_range_max',
'remote_group_id', 'security_group_id']
position_values = [remote_ip_prefix, direction, ethertype, protocol,
port_range_min, port_range_max, remote_group_id,
security_group_id]
self._test_create_resource(resource, cmd, None, myid, args,
position_names, position_values)
def test_delete_security_group_rule(self):
# Delete security group rule: myid.
resource = 'security_group_rule'
cmd = securitygroup.DeleteSecurityGroupRule(
test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)
@mock.patch.object(securitygroup.ListSecurityGroupRule, "extend_list")
def test_list_security_group_rules(self, mock_extend_list):
resources = "security_group_rules"
cmd = securitygroup.ListSecurityGroupRule(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
def _build_test_data(self, data, excess=0):
# Length of a query filter on security group rule id
# in these testcases, id='secgroupid%02d' (with len(id)=12)
sec_group_id_filter_len = 12
response = []
replace_rules = {'security_group_id': 'security_group',
'remote_group_id': 'remote_group'}
search_opts = {'fields': ['id', 'name']}
sec_group_ids = set()
for rule in data:
for key in replace_rules:
if rule.get(key):
sec_group_ids.add(rule[key])
response.append({'id': rule[key], 'name': 'default'})
sec_group_ids = list(sec_group_ids)
result = []
sec_group_count = len(sec_group_ids)
max_size = ((sec_group_id_filter_len * sec_group_count) - excess)
chunk_size = max_size // sec_group_id_filter_len
for i in range(0, sec_group_count, chunk_size):
search_opts['id'] = sec_group_ids[i: i + chunk_size]
params = utils.safe_encode_dict(search_opts)
resp_str = self.client.serialize({'security_groups': response})
result.append({
'filter': urlparse.urlencode(params, doseq=1),
'response': (test_cli20.MyResp(200), resp_str),
})
return result
def test_extend_list(self):
data = [{'name': 'default',
'remote_group_id': 'remgroupid%02d' % i}
for i in range(10)]
data.append({'name': 'default', 'remote_group_id': None})
resources = "security_groups"
cmd = securitygroup.ListSecurityGroupRule(
test_cli20.MyApp(sys.stdout), None)
path = getattr(self.client, resources + '_path')
responses = self._build_test_data(data)
known_args, _vs = cmd.get_parser(
'list' + resources).parse_known_args()
resp = responses[0]['response']
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request:
cmd.extend_list(data, known_args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(test_cli20.end_url(
path, responses[0]['filter']), self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
def test_extend_list_exceed_max_uri_len(self):
data = [{'name': 'default',
'security_group_id': 'secgroupid%02d' % i,
'remote_group_id': 'remgroupid%02d' % i}
for i in range(10)]
data.append({'name': 'default',
'security_group_id': 'secgroupid10',
'remote_group_id': None})
resources = "security_groups"
cmd = securitygroup.ListSecurityGroupRule(
test_cli20.MyApp(sys.stdout), None)
path = getattr(self.client, resources + '_path')
responses = self._build_test_data(data, excess=1)
known_args, _vs = cmd.get_parser(
'list' + resources).parse_known_args()
mock_request_side_effects = []
mock_request_calls = []
mock_check_uri_side_effects = [exceptions.RequestURITooLong(excess=1)]
mock_check_uri_calls = [mock.call(mock.ANY)]
for item in responses:
mock_request_side_effects.append(item['response'])
mock_request_calls.append(mock.call(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, item['filter']), self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN})))
mock_check_uri_side_effects.append(None)
mock_check_uri_calls.append(mock.call(mock.ANY))
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient,
"request") as mock_request, \
mock.patch.object(self.client.httpclient,
"_check_uri_length") as mock_check_uri:
mock_request.side_effect = mock_request_side_effects
mock_check_uri.side_effect = mock_check_uri_side_effects
cmd.extend_list(data, known_args)
mock_get_client.assert_called_once_with()
mock_request.assert_has_calls(mock_request_calls)
mock_check_uri.assert_has_calls(mock_check_uri_calls)
self.assertEqual(len(mock_request_calls), mock_request.call_count)
self.assertEqual(len(mock_check_uri_calls), mock_check_uri.call_count)
@mock.patch.object(securitygroup.ListSecurityGroupRule, "extend_list")
def test_list_security_group_rules_pagination(self, mock_extend_list):
resources = "security_group_rules"
cmd = securitygroup.ListSecurityGroupRule(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
@mock.patch.object(securitygroup.ListSecurityGroupRule, "extend_list")
def test_list_security_group_rules_sort(self, mock_extend_list):
resources = "security_group_rules"
cmd = securitygroup.ListSecurityGroupRule(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
@mock.patch.object(securitygroup.ListSecurityGroupRule, "extend_list")
def test_list_security_group_rules_limit(self, mock_extend_list):
resources = "security_group_rules"
cmd = securitygroup.ListSecurityGroupRule(
test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
def test_show_security_group_rule(self):
resource = 'security_group_rule'
cmd = securitygroup.ShowSecurityGroupRule(
test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id'])
def _test_list_security_group_rules_extend(self, api_data, expected,
args=(), conv=True,
query_fields=None):
def setup_list_stub(resources, data, query, mock_calls, mock_returns):
reses = {resources: data}
resstr = self.client.serialize(reses)
resp = (test_cli20.MyResp(200), resstr)
path = getattr(self.client, resources + '_path')
mock_calls.append(mock.call(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, query),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN})))
mock_returns.append(resp)
cmd = securitygroup.ListSecurityGroupRule(
test_cli20.MyApp(sys.stdout), None)
query = ''
if query_fields:
query = '&'.join(['fields=' + f for f in query_fields])
mock_request_calls = []
mock_request_returns = []
setup_list_stub('security_group_rules', api_data, query,
mock_request_calls, mock_request_returns)
if conv:
sec_ids = set()
for n in api_data:
sec_ids.add(n['security_group_id'])
if n.get('remote_group_id'):
sec_ids.add(n['remote_group_id'])
filters = ''
for id in sec_ids:
filters = filters + "&id=%s" % id
setup_list_stub('security_groups',
[{'id': 'myid1', 'name': 'group1'},
{'id': 'myid2', 'name': 'group2'},
{'id': 'myid3', 'name': 'group3'}],
'fields=id&fields=name' + filters,
mock_request_calls,
mock_request_returns)
cmd_parser = cmd.get_parser('list_security_group_rules')
parsed_args = cmd_parser.parse_args(args)
with mock.patch.object(cmd, "get_client",
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient,
"request") as mock_request:
mock_request.side_effect = mock_request_returns
result = cmd.take_action(parsed_args)
self.assert_mock_multiple_calls_with_same_arguments(
mock_get_client, mock.call(), None)
mock_request.assert_has_calls(mock_request_calls)
self.assertEqual(len(mock_request_calls), mock_request.call_count)
self.assertEqual(expected['cols'], result[0])
# Check data
_result = [x for x in result[1]]
self.assertEqual(len(expected['data']), len(_result))
for res, exp in zip(_result, expected['data']):
self.assertEqual(len(exp), len(res))
self.assertEqual(exp, res)
def _test_list_security_group_rules_extend_sg_name(
self, expected_mode=None, args=(), conv=True, query_field=False):
if query_field:
field_filters = ['id', 'security_group_id',
'remote_ip_prefix', 'remote_group_id']
else:
field_filters = None
data = [self._prepare_rule(rule_id='ruleid1', sg_id='myid1',
remote_group_id='myid1',
filters=field_filters),
self._prepare_rule(rule_id='ruleid2', sg_id='myid2',
remote_group_id='myid3',
filters=field_filters),
self._prepare_rule(rule_id='ruleid3', sg_id='myid2',
remote_group_id='myid2',
filters=field_filters),
]
if expected_mode == 'noconv':
expected = {'cols': ['id', 'security_group_id', 'remote_group_id'],
'data': [('ruleid1', 'myid1', 'myid1'),
('ruleid2', 'myid2', 'myid3'),
('ruleid3', 'myid2', 'myid2')]}
elif expected_mode == 'remote_group_id':
expected = {'cols': ['id', 'security_group', 'remote_group'],
'data': [('ruleid1', 'group1', 'group1'),
('ruleid2', 'group2', 'group3'),
('ruleid3', 'group2', 'group2')]}
else:
expected = {'cols': ['id', 'security_group', 'remote'],
'data': [('ruleid1', 'group1', 'group1 (group)'),
('ruleid2', 'group2', 'group3 (group)'),
('ruleid3', 'group2', 'group2 (group)')]}
self._test_list_security_group_rules_extend(
data, expected, args=args, conv=conv, query_fields=field_filters)
def test_list_security_group_rules_extend_remote_sg_name(self):
args = '-c id -c security_group -c remote'.split()
self._test_list_security_group_rules_extend_sg_name(args=args)
def test_list_security_group_rules_extend_sg_name_noconv(self):
args = '--no-nameconv -c id -c security_group_id -c remote_group_id'
args = args.split()
self._test_list_security_group_rules_extend_sg_name(
expected_mode='noconv', args=args, conv=False)
def test_list_security_group_rules_extend_sg_name_with_columns(self):
args = '-c id -c security_group_id -c remote_group_id'.split()
self._test_list_security_group_rules_extend_sg_name(
expected_mode='remote_group_id', args=args)
def test_list_security_group_rules_extend_sg_name_with_columns_no_id(self):
args = '-c id -c security_group -c remote_group'.split()
self._test_list_security_group_rules_extend_sg_name(
expected_mode='remote_group_id', args=args)
def test_list_security_group_rules_extend_sg_name_with_fields(self):
# NOTE: remote_ip_prefix is required to show "remote" column
args = ('-F id -F security_group_id '
'-F remote_ip_prefix -F remote_group_id').split()
self._test_list_security_group_rules_extend_sg_name(
args=args, query_field=True)
def test_list_security_group_rules_extend_sg_name_with_fields_no_id(self):
# NOTE: remote_ip_prefix is required to show "remote" column
args = ('-F id -F security_group '
'-F remote_ip_prefix -F remote_group').split()
self._test_list_security_group_rules_extend_sg_name(args=args,
query_field=True)
def test_list_security_group_rules_extend_remote(self):
args = '-c id -c security_group -c remote'.split()
data = [self._prepare_rule(rule_id='ruleid1', sg_id='myid1',
remote_ip_prefix='172.16.18.0/24'),
self._prepare_rule(rule_id='ruleid2', sg_id='myid2',
remote_ip_prefix='172.16.20.0/24'),
self._prepare_rule(rule_id='ruleid3', sg_id='myid2',
remote_group_id='myid3')]
expected = {'cols': ['id', 'security_group', 'remote'],
'data': [('ruleid1', 'group1', '172.16.18.0/24 (CIDR)'),
('ruleid2', 'group2', '172.16.20.0/24 (CIDR)'),
('ruleid3', 'group2', 'group3 (group)')]}
self._test_list_security_group_rules_extend(data, expected, args)
def test_list_security_group_rules_extend_proto_port(self):
data = [self._prepare_rule(rule_id='ruleid1', sg_id='myid1',
protocol='tcp',
port_range_min=22, port_range_max=22),
self._prepare_rule(rule_id='ruleid2', sg_id='myid2',
direction='egress', ethertype='IPv6',
protocol='udp',
port_range_min=80, port_range_max=81),
self._prepare_rule(rule_id='ruleid3', sg_id='myid2',
protocol='icmp',
remote_ip_prefix='10.2.0.0/16')]
expected = {
'cols': ['id', 'security_group', 'direction', 'ethertype',
'port/protocol', 'remote'],
'data': [
('ruleid1', 'group1', 'ingress', 'IPv4', '22/tcp', 'any'),
('ruleid2', 'group2', 'egress', 'IPv6', '80-81/udp', 'any'),
('ruleid3', 'group2', 'ingress', 'IPv4', 'icmp',
'10.2.0.0/16 (CIDR)')
]}
self._test_list_security_group_rules_extend(data, expected)
def _prepare_rule(self, rule_id=None, sg_id=None, tenant_id=None,
direction=None, ethertype=None,
protocol=None, port_range_min=None, port_range_max=None,
remote_ip_prefix=None, remote_group_id=None,
filters=None):
rule = {'id': rule_id or uuidutils.generate_uuid(),
'tenant_id': tenant_id or uuidutils.generate_uuid(),
'security_group_id': sg_id or uuidutils.generate_uuid(),
'direction': direction or 'ingress',
'ethertype': ethertype or 'IPv4',
'protocol': protocol,
'port_range_min': port_range_min,
'port_range_max': port_range_max,
'remote_ip_prefix': remote_ip_prefix,
'remote_group_id': remote_group_id}
if filters:
return dict([(k, v) for k, v in rule.items() if k in filters])
else:
return rule
def test__get_remote_both_unspecified(self):
sg_rule = self._prepare_rule(remote_ip_prefix=None,
remote_group_id=None)
self.assertIsNone(securitygroup._get_remote(sg_rule))
def test__get_remote_remote_ip_prefix_specified(self):
sg_rule = self._prepare_rule(remote_ip_prefix='172.16.18.0/24')
self.assertEqual('172.16.18.0/24 (CIDR)',
securitygroup._get_remote(sg_rule))
def test__get_remote_remote_group_specified(self):
sg_rule = self._prepare_rule(remote_group_id='sg_id1')
self.assertEqual('sg_id1 (group)', securitygroup._get_remote(sg_rule))
def test__get_protocol_port_all_none(self):
sg_rule = self._prepare_rule()
self.assertIsNone(securitygroup._get_protocol_port(sg_rule))
def test__get_protocol_port_tcp_all_port(self):
sg_rule = self._prepare_rule(protocol='tcp')
self.assertEqual('tcp', securitygroup._get_protocol_port(sg_rule))
def test__get_protocol_port_tcp_one_port(self):
sg_rule = self._prepare_rule(protocol='tcp',
port_range_min=22, port_range_max=22)
self.assertEqual('22/tcp', securitygroup._get_protocol_port(sg_rule))
def test__get_protocol_port_tcp_port_range(self):
sg_rule = self._prepare_rule(protocol='tcp',
port_range_min=5000, port_range_max=5010)
self.assertEqual('5000-5010/tcp',
securitygroup._get_protocol_port(sg_rule))
def test__get_protocol_port_udp_all_port(self):
sg_rule = self._prepare_rule(protocol='udp')
self.assertEqual('udp', securitygroup._get_protocol_port(sg_rule))
def test__get_protocol_port_udp_one_port(self):
sg_rule = self._prepare_rule(protocol='udp',
port_range_min=22, port_range_max=22)
self.assertEqual('22/udp', securitygroup._get_protocol_port(sg_rule))
def test__get_protocol_port_udp_port_range(self):
sg_rule = self._prepare_rule(protocol='udp',
port_range_min=5000, port_range_max=5010)
self.assertEqual('5000-5010/udp',
securitygroup._get_protocol_port(sg_rule))
def test__get_protocol_port_icmp_all(self):
sg_rule = self._prepare_rule(protocol='icmp')
self.assertEqual('icmp', securitygroup._get_protocol_port(sg_rule))
def test_get_ethertype_for_protocol_icmpv6(self):
self.assertEqual('IPv6',
securitygroup.generate_default_ethertype('icmpv6'))
def test_get_ethertype_for_protocol_icmp(self):
self.assertEqual('IPv4',
securitygroup.generate_default_ethertype('icmp'))
def test__get_protocol_port_udp_code_type(self):
sg_rule = self._prepare_rule(protocol='icmp',
port_range_min=1, port_range_max=8)
self.assertEqual('icmp (type:1, code:8)',
securitygroup._get_protocol_port(sg_rule))
def test__format_sg_rules(self):
rules = [self._prepare_rule(),
self._prepare_rule(protocol='tcp', port_range_min=80,
port_range_max=80),
self._prepare_rule(remote_ip_prefix='192.168.1.0/24'),
self._prepare_rule(remote_group_id='group1'),
self._prepare_rule(protocol='tcp',
remote_ip_prefix='10.1.1.0/24'),
self._prepare_rule(direction='egress'),
self._prepare_rule(direction='egress', ethertype='IPv6'),
]
sg = {'security_group_rules': rules}
expected_data = ['ingress, IPv4',
'ingress, IPv4, 80/tcp',
'ingress, IPv4, remote_ip_prefix: 192.168.1.0/24',
'ingress, IPv4, remote_group_id: group1',
'ingress, IPv4, tcp, remote_ip_prefix: 10.1.1.0/24',
'egress, IPv4',
'egress, IPv6',
]
expected = '\n'.join(sorted(expected_data))
self.assertEqual(expected, securitygroup._format_sg_rules(sg))

View File

@ -1,55 +0,0 @@
# 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 sys
from neutronclient.neutron.v2_0 import servicetype
from neutronclient.tests.unit import test_cli20
class CLITestV20ServiceProvidersJSON(test_cli20.CLITestV20Base):
id_field = "name"
def setUp(self):
super(CLITestV20ServiceProvidersJSON, self).setUp(
plurals={'tags': 'tag'}
)
def test_list_service_providers(self):
resources = "service_providers"
cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True)
def test_list_service_providers_pagination(self):
resources = "service_providers"
cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_service_providers_sort(self):
resources = "service_providers"
cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd,
sort_key=["name"],
sort_dir=["asc", "desc"])
def test_list_service_providers_limit(self):
resources = "service_providers"
cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, page_size=1000)

View File

@ -1,687 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# 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 sys
from unittest import mock
from neutronclient.common import exceptions
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.neutron.v2_0 import subnet
from neutronclient.tests.unit import test_cli20
class CLITestV20SubnetJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['subnet']
def setUp(self):
super(CLITestV20SubnetJSON, self).setUp(plurals={'tags': 'tag'})
def test_create_subnet(self):
# Create subnet: --gateway gateway netid cidr.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = '10.10.10.0/24'
gateway = 'gatewayvalue'
args = ['--gateway', gateway, netid, cidr, '--description', 'cave']
position_names = ['ip_version', 'network_id', 'cidr', 'gateway_ip']
position_values = [4, netid, cidr, gateway]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
description='cave')
def test_create_subnet_network_cidr_seperated(self):
# For positional value, network_id and cidr can be separated.
# Create subnet: --gateway gateway netid cidr.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = '10.10.10.0/24'
gateway = 'gatewayvalue'
args = [netid, '--gateway', gateway, cidr]
position_names = ['ip_version', 'network_id', 'cidr', 'gateway_ip']
position_values = [4, netid, cidr, gateway]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_subnet_with_no_gateway(self):
# Create subnet: --no-gateway netid cidr.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'cidrvalue'
args = ['--no-gateway', netid, cidr]
position_names = ['ip_version', 'network_id', 'cidr', 'gateway_ip']
position_values = [4, netid, cidr, None]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_subnet_with_segment(self):
# Create subnet: --segment segment netid cidr.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = '10.10.10.0/24'
segment = 'segment'
args = ['--segment', segment, netid, cidr,
'--description', 'cave']
position_names = ['ip_version', 'network_id', 'cidr', 'segment_id']
position_values = [4, netid, cidr, segment]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
description='cave')
def test_create_subnet_with_bad_gateway_option(self):
# Create sbunet: --no-gateway netid cidr.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'cidrvalue'
gateway = 'gatewayvalue'
args = ['--gateway', gateway, '--no-gateway', netid, cidr]
position_names = ['ip_version', 'network_id', 'cidr', 'gateway_ip']
position_values = [4, netid, cidr, None]
self.assertRaises(
SystemExit, self._test_create_resource,
resource, cmd, name, myid, args, position_names, position_values)
def _test_create_resource_and_catch_command_error(self, should_fail,
*args):
if should_fail:
params = {'no_api_call': True,
'expected_exception': exceptions.CommandError}
else:
params = {}
self._test_create_resource(*args, **params)
def test_create_subnet_with_enable_and_disable_dhcp(self):
# Create subnet: --enable-dhcp and --disable-dhcp.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'cidrvalue'
position_names = ['ip_version', 'network_id', 'cidr', 'enable_dhcp']
# enable_dhcp value is appended later inside the loop
position_values = [4, netid, cidr]
for enable_dhcp_arg, should_fail in (
('--enable-dhcp=False', False),
('--enable-dhcp=True', True),
('--enable-dhcp', True)
):
tested_args = [enable_dhcp_arg, '--disable-dhcp']
args = tested_args + [netid, cidr]
pos_values = position_values + [should_fail]
self._test_create_resource_and_catch_command_error(
should_fail,
resource, cmd, name, myid, args, position_names, pos_values)
def test_create_subnet_with_multiple_enable_dhcp(self):
# Create subnet with multiple --enable-dhcp arguments passed.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'cidrvalue'
position_names = ['ip_version', 'network_id', 'cidr', 'enable_dhcp']
# enable_dhcp value is appended later inside the loop
position_values = [4, netid, cidr]
_ = 'UNUSED_MARKER'
for tested_args, should_fail, pos_value in (
(['--enable-dhcp', '--enable-dhcp=True'], False, True),
(['--enable-dhcp', '--enable-dhcp=False'], True, _),
(['--enable-dhcp=False', '--enable-dhcp'], True, _),
(['--enable-dhcp=True', '--enable-dhcp=False'], True, _),
(['--enable-dhcp=False', '--enable-dhcp=True'], True, _)
):
args = tested_args + [netid, cidr]
pos_values = position_values + [pos_value]
self._test_create_resource_and_catch_command_error(
should_fail,
resource, cmd, name, myid, args, position_names, pos_values)
def test_create_subnet_tenant(self):
# Create subnet: --tenant_id tenantid netid cidr.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid', netid, cidr]
position_names = ['ip_version', 'network_id', 'cidr']
position_values = [4, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_tags(self):
# Create subnet: netid cidr --tags a b.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = [netid, cidr, '--tags', 'a', 'b']
position_names = ['ip_version', 'network_id', 'cidr']
position_values = [4, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tags=['a', 'b'])
def test_create_subnet_allocation_pool(self):
# Create subnet: --tenant_id tenantid <pool> netid cidr.
# The <pool> is --allocation_pool start=1.1.1.10,end=1.1.1.20
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--allocation_pool', 'start=1.1.1.10,end=1.1.1.20',
netid, cidr]
position_names = ['ip_version', 'allocation_pools', 'network_id',
'cidr']
pool = [{'start': '1.1.1.10', 'end': '1.1.1.20'}]
position_values = [4, pool, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_allocation_pools(self):
# Create subnet: --tenant-id tenantid <pools> netid cidr.
# The <pools> are --allocation_pool start=1.1.1.10,end=1.1.1.20 and
# --allocation_pool start=1.1.1.30,end=1.1.1.40
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--allocation_pool', 'start=1.1.1.10,end=1.1.1.20',
'--allocation_pool', 'start=1.1.1.30,end=1.1.1.40',
netid, cidr]
position_names = ['ip_version', 'allocation_pools', 'network_id',
'cidr']
pools = [{'start': '1.1.1.10', 'end': '1.1.1.20'},
{'start': '1.1.1.30', 'end': '1.1.1.40'}]
position_values = [4, pools, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_host_route(self):
# Create subnet: --tenant_id tenantid <host_route> netid cidr.
# The <host_route> is
# --host-route destination=172.16.1.0/24,nexthop=1.1.1.20
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--host-route', 'destination=172.16.1.0/24,nexthop=1.1.1.20',
netid, cidr]
position_names = ['ip_version', 'host_routes', 'network_id',
'cidr']
route = [{'destination': '172.16.1.0/24', 'nexthop': '1.1.1.20'}]
position_values = [4, route, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_host_routes(self):
# Create subnet: --tenant-id tenantid <host_routes> netid cidr.
# The <host_routes> are
# --host-route destination=172.16.1.0/24,nexthop=1.1.1.20 and
# --host-route destination=172.17.7.0/24,nexthop=1.1.1.40
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--host-route', 'destination=172.16.1.0/24,nexthop=1.1.1.20',
'--host-route', 'destination=172.17.7.0/24,nexthop=1.1.1.40',
netid, cidr]
position_names = ['ip_version', 'host_routes', 'network_id',
'cidr']
routes = [{'destination': '172.16.1.0/24', 'nexthop': '1.1.1.20'},
{'destination': '172.17.7.0/24', 'nexthop': '1.1.1.40'}]
position_values = [4, routes, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_dns_nameservers(self):
# Create subnet: --tenant-id tenantid <dns-nameservers> netid cidr.
# The <dns-nameservers> are
# --dns-nameserver 1.1.1.20 and --dns-nameserver 1.1.1.40
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--dns-nameserver', '1.1.1.20',
'--dns-nameserver', '1.1.1.40',
netid, cidr]
position_names = ['ip_version', 'dns_nameservers', 'network_id',
'cidr']
nameservers = ['1.1.1.20', '1.1.1.40']
position_values = [4, nameservers, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_with_use_default_subnetpool(self):
# Create subnet: --tenant-id tenantid --use-default-subnetpool \
# netid cidr.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--use-default-subnetpool',
netid, cidr]
position_names = ['ip_version', 'use_default_subnetpool', 'network_id',
'cidr']
position_values = [4, True, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_with_disable_dhcp(self):
# Create subnet: --tenant-id tenantid --disable-dhcp netid cidr.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--disable-dhcp',
netid, cidr]
position_names = ['ip_version', 'enable_dhcp', 'network_id',
'cidr']
position_values = [4, False, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_merge_single_plurar(self):
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--allocation-pool', 'start=1.1.1.10,end=1.1.1.20',
netid, cidr,
'--allocation-pools', 'list=true', 'type=dict',
'start=1.1.1.30,end=1.1.1.40']
position_names = ['ip_version', 'allocation_pools', 'network_id',
'cidr']
pools = [{'start': '1.1.1.10', 'end': '1.1.1.20'},
{'start': '1.1.1.30', 'end': '1.1.1.40'}]
position_values = [4, pools, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_merge_plurar(self):
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
netid, cidr,
'--allocation-pools', 'list=true', 'type=dict',
'start=1.1.1.30,end=1.1.1.40']
position_names = ['ip_version', 'allocation_pools', 'network_id',
'cidr']
pools = [{'start': '1.1.1.30', 'end': '1.1.1.40'}]
position_values = [4, pools, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_merge_single_single(self):
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--allocation-pool', 'start=1.1.1.10,end=1.1.1.20',
netid, cidr,
'--allocation-pool',
'start=1.1.1.30,end=1.1.1.40']
position_names = ['ip_version', 'allocation_pools', 'network_id',
'cidr']
pools = [{'start': '1.1.1.10', 'end': '1.1.1.20'},
{'start': '1.1.1.30', 'end': '1.1.1.40'}]
position_values = [4, pools, netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_max_v4_cidr(self):
# Create subnet: --gateway gateway netid cidr.
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = '192.168.0.1/32'
gateway = 'gatewayvalue'
args = ['--gateway', gateway, netid, cidr]
position_names = ['ip_version', 'network_id', 'cidr', 'gateway_ip']
position_values = [4, netid, cidr, gateway]
with mock.patch.object(cmd.log, 'warning') as mock_warning:
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
mock_warning.assert_called_once_with(mock.ANY,
{'ip': 4, 'cidr': '/32'})
def test_create_subnet_with_ipv6_ra_mode(self):
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--ip-version', '6',
'--ipv6-ra-mode', 'dhcpv6-stateful',
netid, cidr]
position_names = ['ip_version', 'ipv6_ra_mode',
'network_id', 'cidr']
position_values = [6, 'dhcpv6-stateful', netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_with_ipv6_address_mode(self):
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--ip-version', '6',
'--ipv6-address-mode', 'dhcpv6-stateful',
netid, cidr]
position_names = ['ip_version', 'ipv6_address_mode',
'network_id', 'cidr']
position_values = [6, 'dhcpv6-stateful', netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_with_ipv6_modes(self):
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--ip-version', '6',
'--ipv6-address-mode', 'slaac',
'--ipv6-ra-mode', 'slaac',
netid, cidr]
position_names = ['ip_version', 'ipv6_address_mode',
'ipv6_ra_mode', 'network_id', 'cidr']
position_values = [6, 'slaac', 'slaac', netid, cidr]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_subnet_with_ipv6_ra_mode_ipv4(self):
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--ip-version', '4',
'--ipv6-ra-mode', 'slaac',
netid, cidr]
position_names = ['ip_version', 'ipv6_ra_mode',
'network_id', 'cidr']
position_values = [4, None, netid, cidr]
self._test_create_resource(
resource, cmd, name, myid, args, position_names,
position_values, tenant_id='tenantid',
no_api_call=True, expected_exception=exceptions.CommandError)
def test_create_subnet_with_ipv6_address_mode_ipv4(self):
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'prefixvalue'
args = ['--tenant_id', 'tenantid',
'--ip-version', '4',
'--ipv6-address-mode', 'slaac',
netid, cidr]
position_names = ['ip_version', 'ipv6_address_mode',
'network_id', 'cidr']
position_values = [4, None, netid, cidr]
self._test_create_resource(
resource, cmd, name, myid, args, position_names,
position_values, tenant_id='tenantid',
no_api_call=True, expected_exception=exceptions.CommandError)
@mock.patch.object(neutronV20, 'find_resource_by_name_or_id')
def test_create_subnet_with_subnetpool_ipv6_and_ip_ver_ignored(
self, mock_find_resource):
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--tenant_id', 'tenantid',
'--ip-version', '4',
'--subnetpool', 'subnetpool_id',
netid]
position_names = ['ip_version', 'network_id', 'subnetpool_id']
position_values = [6, netid, 'subnetpool_id']
mock_find_resource.return_value = {
'id': 'subnetpool_id', 'ip_version': 6}
self._test_create_resource(
resource, cmd, name, myid, args, position_names,
position_values, tenant_id='tenantid')
mock_find_resource.assert_called_once_with(
self.client, 'subnetpool', 'subnetpool_id')
@mock.patch.object(neutronV20, 'find_resource_by_name_or_id')
def test_create_subnet_with_subnetpool_ipv4_with_cidr_wildcard(
self, mock_find_resource):
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
cidr = 'cidrwildcard'
args = ['--tenant_id', 'tenantid',
'--ip-version', '4',
'--ipv6-address-mode', 'slaac',
'--subnetpool', 'subnetpool_id',
netid, cidr]
position_names = ['ip_version', 'ipv6_address_mode',
'network_id', 'subnetpool_id', 'cidr']
position_values = [4, None, netid, 'subnetpool_id', cidr]
mock_find_resource.return_value = {'id': 'subnetpool_id',
'ip_version': 4}
self._test_create_resource(
resource, cmd, name, myid, args, position_names,
position_values, tenant_id='tenantid',
no_api_call=True, expected_exception=exceptions.CommandError)
mock_find_resource.assert_called_once_with(
self.client, 'subnetpool', 'subnetpool_id')
@mock.patch.object(neutronV20, 'find_resource_by_name_or_id')
def test_create_subnet_with_subnetpool_ipv4_with_prefixlen(
self, mock_find_resource):
resource = 'subnet'
cmd = subnet.CreateSubnet(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--tenant_id', 'tenantid',
'--ip-version', '4',
'--ipv6-address-mode', 'slaac',
'--subnetpool', 'subnetpool_id',
'--prefixlen', '31',
netid]
position_names = ['ip_version', 'ipv6_address_mode',
'network_id', 'subnetpool_id']
position_values = [4, None, netid, 'subnetpool_id']
mock_find_resource.return_value = {'id': 'subnetpool_id',
'ip_version': 4}
self._test_create_resource(
resource, cmd, name, myid, args, position_names,
position_values, tenant_id='tenantid',
no_api_call=True, expected_exception=exceptions.CommandError)
mock_find_resource.assert_called_once_with(
self.client, 'subnetpool', 'subnetpool_id')
def test_list_subnets_detail(self):
# List subnets: -D.
resources = "subnets"
cmd = subnet.ListSubnet(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_subnets_tags(self):
# List subnets: -- --tags a b.
resources = "subnets"
cmd = subnet.ListSubnet(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, tags=['a', 'b'])
def test_list_subnets_detail_tags(self):
# List subnets: -D -- --tags a b.
resources = "subnets"
cmd = subnet.ListSubnet(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, detail=True, tags=['a', 'b'])
def test_list_subnets_fields(self):
# List subnets: --fields a --fields b -- --fields c d.
resources = "subnets"
cmd = subnet.ListSubnet(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
fields_1=['a', 'b'], fields_2=['c', 'd'])
def test_list_subnets_pagination(self):
resources = "subnets"
cmd = subnet.ListSubnet(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_subnets_sort(self):
# List subnets: --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = "subnets"
cmd = subnet.ListSubnet(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_subnets_limit(self):
# List subnets: -P.
resources = "subnets"
cmd = subnet.ListSubnet(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_update_subnet(self):
# Update subnet: myid --name myname --tags a b.
resource = 'subnet'
cmd = subnet.UpdateSubnet(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--description', 'cavern',
'--tags', 'a', 'b'],
{'name': 'myname', 'tags': ['a', 'b'],
'description': 'cavern'})
def test_update_subnet_allocation_pools(self):
# Update subnet: myid --name myname --tags a b.
resource = 'subnet'
cmd = subnet.UpdateSubnet(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--allocation-pool',
'start=1.2.0.2,end=1.2.0.127'],
{'allocation_pools': [{'start': '1.2.0.2',
'end': '1.2.0.127'}]}
)
def test_update_subnet_enable_disable_dhcp(self):
# Update sbunet: --enable-dhcp and --disable-dhcp.
resource = 'subnet'
cmd = subnet.UpdateSubnet(test_cli20.MyApp(sys.stdout), None)
self.assertRaises(exceptions.CommandError,
self._test_update_resource,
resource, cmd, 'myid',
['myid', '--name', 'myname', '--enable-dhcp',
'--disable-dhcp'], {'name': 'myname', })
def test_show_subnet(self):
# Show subnet: --fields id --fields name myid.
resource = 'subnet'
cmd = subnet.ShowSubnet(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_delete_subnet(self):
# Delete subnet: subnetid.
resource = 'subnet'
cmd = subnet.DeleteSubnet(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)

View File

@ -1,208 +0,0 @@
# Copyright 2015 OpenStack Foundation.
# 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 sys
from unittest import mock
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0 import subnetpool
from neutronclient.tests.unit import test_cli20
class CLITestV20SubnetPoolJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['subnetpool']
def setUp(self):
super(CLITestV20SubnetPoolJSON, self).setUp(plurals={'tags': 'tag'})
def test_create_subnetpool_with_options(self):
# Create subnetpool: myname.
resource = 'subnetpool'
cmd = subnetpool.CreateSubnetPool(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
min_prefixlen = 30
prefix1 = '10.11.12.0/24'
prefix2 = '12.11.13.0/24'
args = [name, '--min-prefixlen', str(min_prefixlen),
'--pool-prefix', prefix1, '--pool-prefix', prefix2,
'--shared', '--description', 'public pool',
'--tenant-id', 'tenantid']
position_names = ['name', 'min_prefixlen', 'prefixes', 'shared',
'tenant_id']
position_values = [name, min_prefixlen, [prefix1, prefix2], True,
'tenantid']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
description='public pool')
def test_create_subnetpool_only_with_required_options(self):
# Create subnetpool: myname.
resource = 'subnetpool'
cmd = subnetpool.CreateSubnetPool(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
min_prefixlen = 30
prefix1 = '10.11.12.0/24'
prefix2 = '12.11.13.0/24'
args = [name, '--min-prefixlen', str(min_prefixlen),
'--pool-prefix', prefix1, '--pool-prefix', prefix2]
position_names = ['name', 'min_prefixlen', 'prefixes']
position_values = [name, min_prefixlen, [prefix1, prefix2]]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_subnetpool_with_is_default(self, default='false'):
# Create subnetpool: myname.
resource = 'subnetpool'
cmd = subnetpool.CreateSubnetPool(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
min_prefixlen = 30
prefix1 = '10.11.12.0/24'
prefix2 = '12.11.13.0/24'
args = [name, '--min-prefixlen', str(min_prefixlen),
'--pool-prefix', prefix1, '--pool-prefix', prefix2,
'--is-default', default]
position_names = ['name', 'min_prefixlen', 'prefixes', 'is_default']
position_values = [name, min_prefixlen, [prefix1, prefix2], default]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_subnetpool_default(self):
self.test_create_subnetpool_with_is_default(default='true')
def test_create_subnetpool_with_unicode(self):
# Create subnetpool: u'\u7f51\u7edc'.
resource = 'subnetpool'
cmd = subnetpool.CreateSubnetPool(test_cli20.MyApp(sys.stdout), None)
name = u'\u7f51\u7edc'
myid = 'myid'
min_prefixlen = 30
prefixes = '10.11.12.0/24'
args = [name, '--min-prefixlen', str(min_prefixlen),
'--pool-prefix', prefixes]
position_names = ['name', 'min_prefixlen', 'prefixes']
position_values = [name, min_prefixlen, [prefixes]]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_subnetpool_with_addrscope(self):
# Create subnetpool: myname in addrscope: foo-address-scope
resource = 'subnetpool'
cmd = subnetpool.CreateSubnetPool(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
min_prefixlen = 30
prefix1 = '11.11.11.0/24'
prefix2 = '12.12.12.0/24'
address_scope = 'foo-address-scope'
args = [name, '--min-prefixlen', str(min_prefixlen),
'--pool-prefix', prefix1, '--pool-prefix', prefix2,
'--address-scope', address_scope]
position_names = ['name', 'min_prefixlen', 'prefixes',
'address_scope_id']
position_values = [name, min_prefixlen, [prefix1, prefix2],
address_scope]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_subnetpool_no_poolprefix(self):
# Should raise an error because --pool-prefix is required
resource = 'subnetpool'
cmd = subnetpool.CreateSubnetPool(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
args = [name]
position_names = ['name']
position_values = [name]
self.assertRaises(SystemExit, self._test_create_resource, resource,
cmd, name, myid, args, position_names,
position_values)
@mock.patch.object(subnetpool.ListSubnetPool, "extend_list")
def test_list_subnetpool_pagination(self, mock_extend_list):
cmd = subnetpool.ListSubnetPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination("subnetpools", cmd)
mock_extend_list.assert_called_once_with(test_cli20.IsA(list),
mock.ANY)
def test_list_subnetpools_sort(self):
# List subnetpools:
# --sort-key name --sort-key id --sort-key asc --sort-key desc
resources = "subnetpools"
cmd = subnetpool.ListSubnetPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_subnetpools_limit(self):
# List subnetpools: -P.
resources = "subnetpools"
cmd = subnetpool.ListSubnetPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_update_subnetpool_exception(self):
# Update subnetpool: myid.
resource = 'subnetpool'
cmd = subnetpool.UpdateSubnetPool(test_cli20.MyApp(sys.stdout), None)
self.assertRaises(exceptions.CommandError, self._test_update_resource,
resource, cmd, 'myid', ['myid'], {})
def test_update_subnetpool(self):
# Update subnetpool: myid --name myname.
resource = 'subnetpool'
cmd = subnetpool.UpdateSubnetPool(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--description', ':)'],
{'name': 'myname', 'description': ':)'})
def test_update_subnetpool_with_address_scope(self):
# Update subnetpool: myid --address-scope newscope.
resource = 'subnetpool'
cmd = subnetpool.UpdateSubnetPool(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--address-scope', 'newscope'],
{'address_scope_id': 'newscope'}
)
def test_update_subnetpool_with_no_address_scope(self):
# Update subnetpool: myid --no-address-scope.
resource = 'subnetpool'
cmd = subnetpool.UpdateSubnetPool(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--no-address-scope'],
{'address_scope_id': None}
)
def test_show_subnetpool(self):
# Show subnetpool: --fields id --fields name myid.
resource = 'subnetpool'
cmd = subnetpool.ShowSubnetPool(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args,
['id', 'name'])
def test_delete_subnetpool(self):
# Delete subnetpool: subnetpoolid.
resource = 'subnetpool'
cmd = subnetpool.DeleteSubnetPool(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)

View File

@ -1,131 +0,0 @@
# 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 sys
from unittest import mock
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0 import network
from neutronclient.neutron.v2_0 import tag
from neutronclient import shell
from neutronclient.tests.unit import test_cli20
class CLITestV20Tag(test_cli20.CLITestV20Base):
def _test_tag_operation(self, cmd, path, method, args, prog_name,
body=None):
with mock.patch.object(cmd, 'get_client',
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, 'request',
return_value=(test_cli20.MyResp(204), None)
) as mock_request:
if body:
body = test_cli20.MyComparator(body, self.client)
cmd_parser = cmd.get_parser(prog_name)
shell.run_command(cmd, cmd_parser, args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(test_cli20.end_url(path), self.client),
method, body=body,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
def _test_tags_query(self, cmd, resources, args, query):
path = getattr(self.client, resources + "_path")
res = {resources: [{'id': 'myid'}]}
resstr = self.client.serialize(res)
with mock.patch.object(cmd, 'get_client',
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, 'request',
return_value=(test_cli20.MyResp(200), resstr)
) as mock_request:
cmd_parser = cmd.get_parser("list_networks")
shell.run_command(cmd, cmd_parser, args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(test_cli20.end_url(path, query),
self.client),
'GET', body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
_str = self.fake_stdout.make_string()
self.assertIn('myid', _str)
def _make_tag_path(self, resource, resource_id, tag):
path = getattr(self.client, "tag_path")
resource_plural = self.client.get_resource_plural(resource)
return path % (resource_plural, resource_id, tag)
def _make_tags_path(self, resource, resource_id):
path = getattr(self.client, "tags_path")
resource_plural = self.client.get_resource_plural(resource)
return path % (resource_plural, resource_id)
def test_add_tag(self):
cmd = tag.AddTag(test_cli20.MyApp(sys.stdout), None)
path = self._make_tag_path('network', 'myid', 'red')
args = ['--resource-type', 'network', '--resource', 'myid',
'--tag', 'red']
self._test_tag_operation(cmd, path, 'PUT', args, "tag-add")
def test_add_tag_empty_tag(self):
cmd = tag.AddTag(test_cli20.MyApp(sys.stdout), None)
path = self._make_tag_path('network', 'myid', '')
args = ['--resource-type', 'network', '--resource', 'myid',
'--tag', '']
self.assertRaises(exceptions.CommandError, self._test_tag_operation,
cmd, path, 'PUT', args, "tag-add")
def test_replace_tag(self):
cmd = tag.ReplaceTag(test_cli20.MyApp(sys.stdout), None)
path = self._make_tags_path('network', 'myid')
args = ['--resource-type', 'network', '--resource', 'myid',
'--tag', 'red', '--tag', 'blue']
body = {'tags': ['red', 'blue']}
self._test_tag_operation(cmd, path, 'PUT', args, "tag-replace",
body=body)
def test_remove_tag(self):
cmd = tag.RemoveTag(test_cli20.MyApp(sys.stdout), None)
path = self._make_tag_path('network', 'myid', 'red')
args = ['--resource-type', 'network', '--resource', 'myid',
'--tag', 'red']
self._test_tag_operation(cmd, path, 'DELETE', args, "tag-remove")
def test_remove_tag_all(self):
cmd = tag.RemoveTag(test_cli20.MyApp(sys.stdout), None)
path = self._make_tags_path('network', 'myid')
args = ['--resource-type', 'network', '--resource', 'myid',
'--all']
self._test_tag_operation(cmd, path, 'DELETE', args, "tag-remove")
def test_no_tag_nor_all(self):
cmd = tag.RemoveTag(test_cli20.MyApp(sys.stdout), None)
path = self._make_tags_path('network', 'myid')
args = ['--resource-type', 'network', '--resource', 'myid']
self.assertRaises(exceptions.CommandError, self._test_tag_operation,
cmd, path, 'DELETE', args, "tag-remove")
def test_tags_query(self):
# This test examines that '-' in the tag related filters
# is not converted to '_'.
resources = 'networks'
cmd = network.ListNetwork(test_cli20.MyApp(sys.stdout), None)
with mock.patch.object(network.ListNetwork, 'extend_list'):
args = ['--not-tags', 'red,blue', '--tags-any', 'green',
'--not-tags-any', 'black']
query = "not-tags=red,blue&tags-any=green&not-tags-any=black"
self._test_tags_query(cmd, resources, args, query)

View File

@ -1,221 +0,0 @@
# Copyright 2015 Rackspace Hosting 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 inspect
import sys
from unittest import mock
from neutronclient.common import extension
from neutronclient.neutron.v2_0.contrib import _fox_sockets as fox_sockets
from neutronclient import shell
from neutronclient.tests.unit import test_cli20
class CLITestV20ExtensionJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['fox_socket']
def setUp(self):
# need to mock before super because extensions loaded on instantiation
self._mock_extension_loading()
super(CLITestV20ExtensionJSON, self).setUp(plurals={'tags': 'tag'})
def _mock_extension_loading(self):
ext_pkg = 'neutronclient.common.extension'
contrib = mock.patch(ext_pkg + '._discover_via_entry_points').start()
contrib.return_value = [("_fox_sockets", fox_sockets)]
return contrib
def test_ext_cmd_loaded(self):
neutron_shell = shell.NeutronShell('2.0')
ext_cmd = {'fox-sockets-list': fox_sockets.FoxInSocketsList,
'fox-sockets-create': fox_sockets.FoxInSocketsCreate,
'fox-sockets-update': fox_sockets.FoxInSocketsUpdate,
'fox-sockets-delete': fox_sockets.FoxInSocketsDelete,
'fox-sockets-show': fox_sockets.FoxInSocketsShow}
for cmd_name, cmd_class in ext_cmd.items():
found = neutron_shell.command_manager.find_command([cmd_name])
self.assertEqual(cmd_class, found[0])
def test_ext_cmd_help_doc_with_extension_name(self):
neutron_shell = shell.NeutronShell('2.0')
ext_cmd = {'fox-sockets-list': fox_sockets.FoxInSocketsList,
'fox-sockets-create': fox_sockets.FoxInSocketsCreate,
'fox-sockets-update': fox_sockets.FoxInSocketsUpdate,
'fox-sockets-delete': fox_sockets.FoxInSocketsDelete,
'fox-sockets-show': fox_sockets.FoxInSocketsShow}
for cmd_name, cmd_class in ext_cmd.items():
found = neutron_shell.command_manager.find_command([cmd_name])
found_factory = found[0]
self.assertEqual(cmd_class, found_factory)
self.assertTrue(found_factory.__doc__.startswith("[_fox_sockets]"))
def test_delete_fox_socket(self):
# Delete fox socket: myid.
resource = 'fox_socket'
cmd = fox_sockets.FoxInSocketsDelete(test_cli20.MyApp(sys.stdout),
None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)
def test_update_fox_socket(self):
# Update fox_socket: myid --name myname.
resource = 'fox_socket'
cmd = fox_sockets.FoxInSocketsUpdate(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname'],
{'name': 'myname'})
def test_create_fox_socket(self):
# Create fox_socket: myname.
resource = 'fox_socket'
cmd = fox_sockets.FoxInSocketsCreate(test_cli20.MyApp(sys.stdout),
None)
name = 'myname'
myid = 'myid'
args = [name, ]
position_names = ['name', ]
position_values = [name, ]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_list_fox_sockets(self):
# List fox_sockets.
resources = 'fox_sockets'
cmd = fox_sockets.FoxInSocketsList(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_fox_pagination(self):
resources = 'fox_sockets'
cmd = fox_sockets.FoxInSocketsList(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_show_fox_socket(self):
# Show fox_socket: --fields id --fields name myid.
resource = 'fox_socket'
cmd = fox_sockets.FoxInSocketsShow(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
class CLITestV20ExtensionJSONAlternatePlurals(test_cli20.CLITestV20Base):
class IPAddress(extension.NeutronClientExtension):
resource = 'ip_address'
resource_plural = '%ses' % resource
object_path = '/%s' % resource_plural
resource_path = '/%s/%%s' % resource_plural
versions = ['2.0']
class IPAddressesList(extension.ClientExtensionList, IPAddress):
shell_command = 'ip-address-list'
def setUp(self):
# need to mock before super because extensions loaded on instantiation
self._mock_extension_loading()
super(CLITestV20ExtensionJSONAlternatePlurals, self).setUp()
def _mock_extension_loading(self):
ext_pkg = 'neutronclient.common.extension'
contrib = mock.patch(ext_pkg + '._discover_via_entry_points').start()
ip_address = mock.Mock()
ip_address.IPAddress = self.IPAddress
ip_address.IPAddressesList = self.IPAddressesList
contrib.return_value = [("ip_address", ip_address)]
return contrib
def test_ext_cmd_loaded(self):
neutron_shell = shell.NeutronShell('2.0')
ext_cmd = {'ip-address-list': self.IPAddressesList}
for cmd_name, cmd_class in ext_cmd.items():
found = neutron_shell.command_manager.find_command([cmd_name])
self.assertEqual(cmd_class, found[0])
def test_list_ip_addresses(self):
# List ip_addresses.
resources = 'ip_addresses'
cmd = self.IPAddressesList(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
class CLITestV20ExtensionJSONChildResource(test_cli20.CLITestV20Base):
class Child(extension.NeutronClientExtension):
parent_resource = 'parents'
child_resource = 'child'
resource = '%s_%s' % (parent_resource, child_resource)
resource_plural = '%sren' % resource
child_resource_plural = '%ren' % child_resource
object_path = '/%s/%%s/%s' % (parent_resource, child_resource_plural)
resource_path = '/%s/%%s/%s/%%s' % (parent_resource,
child_resource_plural)
versions = ['2.0']
class ChildrenList(extension.ClientExtensionList, Child):
shell_command = 'parent-child-list'
class ChildShow(extension.ClientExtensionShow, Child):
shell_command = 'parent-child-show'
class ChildUpdate(extension.ClientExtensionUpdate, Child):
shell_command = 'parent-child-update'
class ChildDelete(extension.ClientExtensionDelete, Child):
shell_command = 'parent-child-delete'
class ChildCreate(extension.ClientExtensionCreate, Child):
shell_command = 'parent-child-create'
def setUp(self):
# need to mock before super because extensions loaded on instantiation
self._mock_extension_loading()
super(CLITestV20ExtensionJSONChildResource, self).setUp()
def _mock_extension_loading(self):
ext_pkg = 'neutronclient.common.extension'
contrib = mock.patch(ext_pkg + '._discover_via_entry_points').start()
child = mock.Mock()
child.Child = self.Child
child.ChildrenList = self.ChildrenList
child.ChildShow = self.ChildShow
child.ChildUpdate = self.ChildUpdate
child.ChildDelete = self.ChildDelete
child.ChildCreate = self.ChildCreate
contrib.return_value = [("child", child)]
return contrib
def test_ext_cmd_loaded(self):
neutron_shell = shell.NeutronShell('2.0')
ext_cmd = {'parent-child-list': self.ChildrenList,
'parent-child-show': self.ChildShow,
'parent-child-update': self.ChildUpdate,
'parent-child-delete': self.ChildDelete,
'parent-child-create': self.ChildCreate}
for cmd_name, cmd_class in ext_cmd.items():
found = neutron_shell.command_manager.find_command([cmd_name])
self.assertEqual(cmd_class, found[0])
def test_client_methods_have_parent_id_arg(self):
methods = (self.client.list_parents_children,
self.client.show_parents_child,
self.client.update_parents_child,
self.client.delete_parents_child,
self.client.create_parents_child)
for method in methods:
argspec = inspect.getfullargspec(method)
self.assertIn("parent_id", argspec.args)

View File

@ -1,244 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# 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 oslo_utils import uuidutils
import testtools
from neutronclient.common import exceptions
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.tests.unit import test_cli20
from neutronclient.v2_0 import client
class CLITestNameorID(testtools.TestCase):
def setUp(self):
"""Prepare the test environment."""
super(CLITestNameorID, self).setUp()
self.endurl = test_cli20.ENDURL
self.client = client.Client(token=test_cli20.TOKEN,
endpoint_url=self.endurl)
def test_get_id_from_id(self):
_id = uuidutils.generate_uuid()
reses = {'networks': [{'id': _id, }, ], }
resstr = self.client.serialize(reses)
resp = (test_cli20.MyResp(200), resstr)
path = getattr(self.client, "networks_path")
with mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request:
returned_id = neutronV20.find_resourceid_by_name_or_id(
self.client, 'network', _id)
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, "fields=id&id=" + _id),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
self.assertEqual(_id, returned_id)
def test_get_id_from_id_then_name_empty(self):
_id = uuidutils.generate_uuid()
reses = {'networks': [{'id': _id, }, ], }
resstr = self.client.serialize(reses)
resstr1 = self.client.serialize({'networks': []})
path = getattr(self.client, "networks_path")
with mock.patch.object(self.client.httpclient,
"request") as mock_request:
mock_request.side_effect = [(test_cli20.MyResp(200), resstr1),
(test_cli20.MyResp(200), resstr)]
returned_id = neutronV20.find_resourceid_by_name_or_id(
self.client, 'network', _id)
self.assertEqual(2, mock_request.call_count)
mock_request.assert_has_calls([
mock.call(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, "fields=id&id=" + _id),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN})),
mock.call(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, "fields=id&name=" + _id),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))])
self.assertEqual(_id, returned_id)
def test_get_id_from_name(self):
name = 'myname'
_id = uuidutils.generate_uuid()
reses = {'networks': [{'id': _id, }, ], }
resstr = self.client.serialize(reses)
resp = (test_cli20.MyResp(200), resstr)
path = getattr(self.client, "networks_path")
with mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request:
returned_id = neutronV20.find_resourceid_by_name_or_id(
self.client, 'network', name)
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, "fields=id&name=" + name),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
self.assertEqual(_id, returned_id)
def test_get_id_from_name_multiple(self):
name = 'myname'
reses = {'networks': [{'id': uuidutils.generate_uuid()},
{'id': uuidutils.generate_uuid()}]}
resstr = self.client.serialize(reses)
resp = (test_cli20.MyResp(200), resstr)
path = getattr(self.client, "networks_path")
with mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request:
exception = self.assertRaises(
exceptions.NeutronClientNoUniqueMatch,
neutronV20.find_resourceid_by_name_or_id,
self.client, 'network', name)
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, "fields=id&name=" + name),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
self.assertIn('Multiple', exception.message)
def test_get_id_from_name_notfound(self):
name = 'myname'
reses = {'networks': []}
resstr = self.client.serialize(reses)
resp = (test_cli20.MyResp(200), resstr)
path = getattr(self.client, "networks_path")
with mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request:
exception = self.assertRaises(
exceptions.NotFound,
neutronV20.find_resourceid_by_name_or_id,
self.client, 'network', name)
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, "fields=id&name=" + name),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
self.assertIn('Unable to find', exception.message)
self.assertEqual(404, exception.status_code)
def test_get_id_from_name_multiple_with_project(self):
name = 'web_server'
project = uuidutils.generate_uuid()
expect_id = uuidutils.generate_uuid()
reses = {'security_groups':
[{'id': expect_id, 'tenant_id': project}]}
resstr = self.client.serialize(reses)
resp = (test_cli20.MyResp(200), resstr)
path = getattr(self.client, "security_groups_path")
with mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request:
observed_id = neutronV20.find_resourceid_by_name_or_id(
self.client, 'security_group', name, project)
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, "fields=id&name=%s&tenant_id=%s" %
(name, project)), self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
self.assertEqual(expect_id, observed_id)
def test_get_id_from_name_multiple_with_project_not_found(self):
name = 'web_server'
project = uuidutils.generate_uuid()
resstr_notfound = self.client.serialize({'security_groups': []})
resp = (test_cli20.MyResp(200), resstr_notfound)
path = getattr(self.client, "security_groups_path")
with mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request:
exc = self.assertRaises(exceptions.NotFound,
neutronV20.find_resourceid_by_name_or_id,
self.client, 'security_group', name,
project)
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, "fields=id&name=%s&tenant_id=%s" %
(name, project)), self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
self.assertIn('Unable to find', exc.message)
self.assertEqual(404, exc.status_code)
def _test_get_resource_by_id(self, id_only=False):
_id = uuidutils.generate_uuid()
net = {'id': _id, 'name': 'test'}
reses = {'networks': [net], }
resstr = self.client.serialize(reses)
resp = (test_cli20.MyResp(200), resstr)
path = getattr(self.client, "networks_path")
if id_only:
query_params = "fields=id&id=%s" % _id
else:
query_params = "id=%s" % _id
with mock.patch.object(self.client.httpclient, "request",
return_value=resp) as mock_request:
if id_only:
returned_id = neutronV20.find_resourceid_by_id(
self.client, 'network', _id)
self.assertEqual(_id, returned_id)
else:
result = neutronV20.find_resource_by_id(
self.client, 'network', _id)
self.assertEqual(net, result)
mock_request.assert_called_once_with(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, query_params),
self.client),
'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
def test_get_resource_by_id(self):
self._test_get_resource_by_id(id_only=False)
def test_get_resourceid_by_id(self):
self._test_get_resource_by_id(id_only=True)

View File

@ -1,99 +0,0 @@
# Copyright (C) 2013 Yahoo! 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 sys
from unittest import mock
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0 import quota as test_quota
from neutronclient.tests.unit import test_cli20
class CLITestV20Quota(test_cli20.CLITestV20Base):
def test_show_quota(self):
resource = 'quota'
cmd = test_quota.ShowQuota(
test_cli20.MyApp(sys.stdout), None)
args = ['--tenant-id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args)
def test_update_quota(self):
resource = 'quota'
cmd = test_quota.UpdateQuota(
test_cli20.MyApp(sys.stdout), None)
args = ['--tenant-id', self.test_id, '--network', 'test']
self.assertRaises(
exceptions.CommandError, self._test_update_resource,
resource, cmd, self.test_id, args=args,
extrafields={'network': 'new'})
def test_delete_quota_get_parser(self):
cmd = test_cli20.MyApp(sys.stdout)
test_quota.DeleteQuota(cmd, None).get_parser(cmd)
def test_show_quota_positional(self):
resource = 'quota'
cmd = test_quota.ShowQuota(
test_cli20.MyApp(sys.stdout), None)
args = [self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args)
def test_update_quota_positional(self):
resource = 'quota'
cmd = test_quota.UpdateQuota(
test_cli20.MyApp(sys.stdout), None)
args = [self.test_id, '--network', 'test']
self.assertRaises(
exceptions.CommandError, self._test_update_resource,
resource, cmd, self.test_id, args=args,
extrafields={'network': 'new'})
def test_show_quota_default(self):
resource = 'quota'
cmd = test_quota.ShowQuotaDefault(
test_cli20.MyApp(sys.stdout), None)
args = ['--tenant-id', self.test_id]
expected_res = {'quota': {'port': 50, 'network': 10, 'subnet': 10}}
resstr = self.client.serialize(expected_res)
path = getattr(self.client, "quota_default_path")
return_tup = (test_cli20.MyResp(200), resstr)
with mock.patch.object(cmd, 'get_client',
return_value=self.client) as mock_get_client, \
mock.patch.object(self.client.httpclient, 'request',
return_value=return_tup) as mock_request:
cmd_parser = cmd.get_parser("test_" + resource)
parsed_args = cmd_parser.parse_args(args)
cmd.run(parsed_args)
mock_get_client.assert_called_once_with()
mock_request.assert_called_once_with(
test_cli20.end_url(path % self.test_id), 'GET',
body=None,
headers=test_cli20.ContainsKeyValue(
{'X-Auth-Token': test_cli20.TOKEN}))
_str = self.fake_stdout.make_string()
self.assertIn('network', _str)
self.assertIn('subnet', _str)
self.assertIn('port', _str)
self.assertNotIn('subnetpool', _str)
def test_update_quota_noargs(self):
resource = 'quota'
cmd = test_quota.UpdateQuota(test_cli20.MyApp(sys.stdout), None)
args = [self.test_id]
self.assertRaises(exceptions.CommandError, self._test_update_resource,
resource, cmd, self.test_id, args=args,
extrafields=None)

View File

@ -1,366 +0,0 @@
# Copyright (C) 2013 Yahoo! 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 argparse
from io import StringIO
import logging
import os
import re
import sys
from unittest import mock
import fixtures
from keystoneauth1 import session
import testtools
from testtools import matchers
from neutronclient.common import clientmanager
from neutronclient.neutron.v2_0 import network
from neutronclient import shell as openstack_shell
DEFAULT_USERNAME = 'username'
DEFAULT_PASSWORD = 'password'
DEFAULT_TENANT_ID = 'tenant_id'
DEFAULT_TENANT_NAME = 'tenant_name'
DEFAULT_AUTH_URL = 'http://127.0.0.1:5000/v2.0/'
DEFAULT_TOKEN = '3bcc3d3a03f44e3d8377f9247b0ad155'
DEFAULT_URL = 'http://quantum.example.org:9696/'
DEFAULT_REGION = 'regionOne'
DEFAULT_ENDPOINT_TYPE = 'public'
DEFAULT_API_VERSION = '2.0'
DEFAULT_SERVICE_TYPE = 'network'
DEFAULT_SERVICE_NAME = 'neutron'
DEFAULT_RETRIES = 3
DEFAULT_TIMEOUT = 3.0
class ShellTest(testtools.TestCase):
FAKE_ENV = {
'OS_USERNAME': DEFAULT_USERNAME,
'OS_PASSWORD': DEFAULT_PASSWORD,
'OS_TENANT_ID': DEFAULT_TENANT_ID,
'OS_TENANT_NAME': DEFAULT_TENANT_NAME,
'OS_AUTH_URL': DEFAULT_AUTH_URL,
'OS_REGION_NAME': None,
'HTTP_PROXY': None,
'http_proxy': None,
}
# Patch os.environ to avoid required auth info.
def setUp(self):
super(ShellTest, self).setUp()
for var in self.FAKE_ENV:
self.useFixture(
fixtures.EnvironmentVariable(
var, self.FAKE_ENV[var]))
def shell(self, argstr, check=False, expected_val=0):
# expected_val is the expected return value after executing
# the command in NeutronShell
orig = (sys.stdout, sys.stderr)
clean_env = {}
_old_env, os.environ = os.environ, clean_env.copy()
try:
sys.stdout = StringIO()
sys.stderr = StringIO()
_shell = openstack_shell.NeutronShell('2.0')
_shell.run(argstr.split())
except SystemExit:
exc_type, exc_value, exc_traceback = sys.exc_info()
self.assertEqual(expected_val, exc_value.code)
finally:
stdout = sys.stdout.getvalue()
stderr = sys.stderr.getvalue()
sys.stdout.close()
sys.stderr.close()
sys.stdout, sys.stderr = orig
os.environ = _old_env
return stdout, stderr
def test_run_unknown_command(self):
self.useFixture(fixtures.FakeLogger(level=logging.DEBUG))
stdout, stderr = self.shell('fake', check=True)
self.assertFalse(stdout)
self.assertIn("Unknown command ['fake']", stderr.strip())
def test_help(self):
required = 'usage:'
help_text, stderr = self.shell('help')
self.assertThat(
help_text,
matchers.MatchesRegex(required))
def test_bash_completion(self):
required = '.*os_user_domain_id.*'
bash_completion, stderr = self.shell('bash-completion')
self.assertThat(
bash_completion,
matchers.MatchesRegex(required))
def test_help_on_subcommand(self):
required = [
'.*?^usage: .* quota-list']
stdout, stderr = self.shell('help quota-list')
for r in required:
self.assertThat(
stdout,
matchers.MatchesRegex(r, re.DOTALL | re.MULTILINE))
def test_help_command(self):
required = 'usage:'
help_text, stderr = self.shell('help network-create')
self.assertThat(
help_text,
matchers.MatchesRegex(required))
def test_bash_completion_in_outputs_of_help_command(self):
help_text, stderr = self.shell('help')
completion_cmd = "bash-completion"
completion_help_str = ("Prints all of the commands and options "
"for bash-completion.")
self.assertIn(completion_cmd, help_text)
self.assertIn(completion_help_str, help_text)
def test_bash_completion_command(self):
# just check we have some output
required = [
'.*--tenant_id',
'.*help',
'.*--dns-nameserver']
help_text, stderr = self.shell('neutron bash-completion')
for r in required:
self.assertThat(help_text,
matchers.MatchesRegex(r, re.DOTALL | re.MULTILINE))
def test_build_option_parser(self):
neutron_shell = openstack_shell.NeutronShell('2.0')
result = neutron_shell.build_option_parser('descr', '2.0')
self.assertIsInstance(result, argparse.ArgumentParser)
@mock.patch.object(openstack_shell.NeutronShell, 'run')
def test_main_with_unicode(self, fake_shell):
unicode_text = u'\u7f51\u7edc'
argv = ['net-list', unicode_text, unicode_text]
fake_shell.return_value = 0
ret = openstack_shell.main(argv=argv)
fake_shell.assert_called_once_with([u'net-list', unicode_text,
unicode_text])
self.assertEqual(0, ret)
def test_endpoint_option(self):
shell = openstack_shell.NeutronShell('2.0')
parser = shell.build_option_parser('descr', '2.0')
# Neither $OS_ENDPOINT_TYPE nor --os-endpoint-type
namespace = parser.parse_args([])
self.assertEqual('public', namespace.os_endpoint_type)
# --endpoint-type but not $OS_ENDPOINT_TYPE
namespace = parser.parse_args(['--os-endpoint-type=admin'])
self.assertEqual('admin', namespace.os_endpoint_type)
def test_endpoint_environment_variable(self):
fixture = fixtures.EnvironmentVariable("OS_ENDPOINT_TYPE",
"public")
self.useFixture(fixture)
shell = openstack_shell.NeutronShell('2.0')
parser = shell.build_option_parser('descr', '2.0')
# $OS_ENDPOINT_TYPE but not --endpoint-type
namespace = parser.parse_args([])
self.assertEqual("public", namespace.os_endpoint_type)
# --endpoint-type and $OS_ENDPOINT_TYPE
namespace = parser.parse_args(['--endpoint-type=admin'])
self.assertEqual('admin', namespace.endpoint_type)
def test_timeout_option(self):
shell = openstack_shell.NeutronShell('2.0')
parser = shell.build_option_parser('descr', '2.0')
# Neither $OS_ENDPOINT_TYPE nor --endpoint-type
namespace = parser.parse_args([])
self.assertIsNone(namespace.http_timeout)
# --endpoint-type but not $OS_ENDPOINT_TYPE
namespace = parser.parse_args(['--http-timeout=50'])
self.assertEqual(50, namespace.http_timeout)
def test_timeout_environment_variable(self):
fixture = fixtures.EnvironmentVariable("OS_NETWORK_TIMEOUT",
"50")
self.useFixture(fixture)
shell = openstack_shell.NeutronShell('2.0')
parser = shell.build_option_parser('descr', '2.0')
namespace = parser.parse_args([])
self.assertEqual(50, namespace.http_timeout)
def test_run_incomplete_command(self):
self.useFixture(fixtures.FakeLogger(level=logging.DEBUG))
cmd = (
'--os-username test --os-password test --os-project-id test '
'--os-auth-strategy keystone --os-auth-url '
'%s port-create' %
DEFAULT_AUTH_URL)
stdout, stderr = self.shell(cmd, check=True, expected_val=2)
search_str = "Try 'neutron help port-create' for more information"
self.assertTrue(any(search_str in string for string
in stderr.split('\n')))
def _test_authenticate_user(self, expect_verify, expect_insecure,
**options):
base_options = {'os_cloud': None,
'http_timeout': DEFAULT_TIMEOUT,
'region_name': DEFAULT_REGION,
'network_service_name': DEFAULT_SERVICE_NAME,
'neutron_service_type': DEFAULT_SERVICE_TYPE}
options.update(base_options)
if options.get('os_token'):
options.update({'auth_type': 'token'})
options.update({'os_token': 'token', 'os_url': 'url'})
else:
options.update({'os_token': None, 'os_url': None})
with mock.patch.object(openstack_shell.NeutronShell,
'run_subcommand'), \
mock.patch.object(session, 'Session') as session_mock, \
mock.patch.object(clientmanager, 'ClientManager') as cmgr_mock:
shell = openstack_shell.NeutronShell(DEFAULT_API_VERSION)
shell.options = mock.Mock(spec=options.keys())
for k, v in options.items():
setattr(shell.options, k, v)
shell.options.os_endpoint_type = DEFAULT_ENDPOINT_TYPE
shell.options.retries = DEFAULT_RETRIES
if not (options.get('os_token') and options.get('os_url')):
auth = mock.ANY
auth_session = mock.sentinel.session
session_mock.return_value = auth_session
else:
auth = None
auth_session = None
shell.authenticate_user()
if not (options.get('os_token') and options.get('os_url')):
session_mock.assert_called_once_with(
auth=mock.ANY, verify=expect_verify,
cert=options.get('cert'),
timeout=DEFAULT_TIMEOUT)
else:
self.assertFalse(session_mock.called)
cmgr_mock.assert_called_once_with(
retries=DEFAULT_RETRIES,
raise_errors=False,
session=auth_session,
url=options.get('os_url'),
token=options.get('os_token'),
region_name=DEFAULT_REGION,
api_version=DEFAULT_API_VERSION,
service_type=DEFAULT_SERVICE_TYPE,
service_name=DEFAULT_SERVICE_NAME,
endpoint_type=DEFAULT_ENDPOINT_TYPE,
auth=auth,
insecure=expect_insecure,
log_credentials=True)
def test_authenticate_secure_with_cacert_with_cert(self):
self._test_authenticate_user(
insecure=False, cacert='cacert', cert='cert',
expect_verify='cacert', expect_insecure=False)
def test_authenticate_secure_with_cacert_with_cert_with_token(self):
self._test_authenticate_user(
os_token='token',
insecure=False, cacert='cacert', cert='cert',
expect_verify='cacert', expect_insecure=False)
def test_authenticate_insecure_with_cacert_with_cert(self):
self._test_authenticate_user(
insecure=True, cacert='cacert', cert='cert',
expect_verify=False, expect_insecure=True)
def test_authenticate_insecure_with_cacert_with_cert_with_token(self):
self._test_authenticate_user(
os_token='token',
insecure=True, cacert='cacert', cert='cert',
expect_verify=False, expect_insecure=True)
def test_authenticate_secure_without_cacert_with_cert(self):
self._test_authenticate_user(
insecure=False, cert='cert',
expect_verify=True, expect_insecure=False)
def test_authenticate_secure_without_cacert_with_cert_with_token(self):
self._test_authenticate_user(
os_token='token',
insecure=False, cert='cert',
expect_verify=True, expect_insecure=False)
def test_authenticate_insecure_without_cacert_with_cert(self):
self._test_authenticate_user(
insecure=True, cert='cert',
expect_verify=False, expect_insecure=True)
def test_authenticate_insecure_without_cacert_with_cert_with_token(self):
self._test_authenticate_user(
os_token='token',
insecure=True, cert='cert',
expect_verify=False, expect_insecure=True)
def test_authenticate_secure_with_cacert_without_cert(self):
self._test_authenticate_user(
insecure=False, cacert='cacert',
expect_verify='cacert', expect_insecure=False)
def test_authenticate_secure_with_cacert_without_cert_with_token(self):
self._test_authenticate_user(
os_token='token',
insecure=False, cacert='cacert',
expect_verify='cacert', expect_insecure=False)
def test_authenticate_insecure_with_cacert_without_cert(self):
self._test_authenticate_user(
insecure=True, cacert='cacert',
expect_verify=False, expect_insecure=True)
def test_authenticate_insecure_with_cacert_without_cert_with_token(self):
self._test_authenticate_user(
os_token='token',
insecure=True, cacert='cacert',
expect_verify=False, expect_insecure=True)
def test_commands_dict_populated(self):
# neutron.shell.COMMANDS is populated once NeutronShell is initialized.
# To check COMMANDS during NeutronShell initialization,
# reset COMMANDS to some dummy value before calling NeutronShell().
self.useFixture(fixtures.MockPatchObject(openstack_shell,
'COMMANDS', None))
openstack_shell.NeutronShell('2.0')
self.assertLessEqual(
{'net-create': network.CreateNetwork,
'net-delete': network.DeleteNetwork,
'net-list': network.ListNetwork,
'net-show': network.ShowNetwork,
'net-update': network.UpdateNetwork}.items(),
openstack_shell.COMMANDS['2.0'].items())

View File

@ -1,145 +0,0 @@
# (c) 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.
#
import sys
from neutronclient.neutron.v2_0.vpn import endpoint_group
from neutronclient.tests.unit import test_cli20
class CLITestV20VpnEndpointGroupJSON(test_cli20.CLITestV20Base):
def setUp(self):
super(CLITestV20VpnEndpointGroupJSON, self).setUp()
self.register_non_admin_status_resource('endpoint_group')
def test_create_endpoint_group_with_cidrs(self):
# vpn-endpoint-group-create with CIDR endpoints."""
resource = 'endpoint_group'
cmd = endpoint_group.CreateEndpointGroup(test_cli20.MyApp(sys.stdout),
None)
tenant_id = 'mytenant-id'
my_id = 'my-id'
name = 'my-endpoint-group'
description = 'my endpoint group'
endpoint_type = 'cidr'
endpoints = ['10.0.0.0/24', '20.0.0.0/24']
args = ['--name', name,
'--description', description,
'--tenant-id', tenant_id,
'--type', endpoint_type,
'--value', '10.0.0.0/24',
'--value', '20.0.0.0/24']
position_names = ['name', 'description', 'tenant_id',
'type', 'endpoints']
position_values = [name, description, tenant_id,
endpoint_type, endpoints]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def test_create_endpoint_group_with_subnets(self):
# vpn-endpoint-group-create with subnet endpoints."""
resource = 'endpoint_group'
cmd = endpoint_group.CreateEndpointGroup(test_cli20.MyApp(sys.stdout),
None)
tenant_id = 'mytenant-id'
my_id = 'my-id'
endpoint_type = 'subnet'
subnet = 'subnet-id'
endpoints = [subnet]
args = ['--type', endpoint_type,
'--value', subnet,
'--tenant-id', tenant_id]
position_names = ['type', 'endpoints', 'tenant_id']
position_values = [endpoint_type, endpoints, tenant_id]
self._test_create_resource(resource, cmd, None, my_id, args,
position_names, position_values)
def test_list_endpoint_group(self):
# vpn-endpoint-group-list.
resources = "endpoint_groups"
cmd = endpoint_group.ListEndpointGroup(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True)
def test_list_endpoint_group_pagination(self):
# vpn-endpoint-group-list.
resources = "endpoint_groups"
cmd = endpoint_group.ListEndpointGroup(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_endpoint_group_sort(self):
# vpn-endpoint-group-list --sort-key name --sort-key id
# --sort-key asc --sort-key desc
resources = "endpoint_groups"
cmd = endpoint_group.ListEndpointGroup(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_endpoint_group_limit(self):
# vpn-endpoint-group-list -P.
resources = "endpoint_groups"
cmd = endpoint_group.ListEndpointGroup(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_endpoint_group_id(self):
# vpn-endpoint-group-show test_id.
resource = 'endpoint_group'
cmd = endpoint_group.ShowEndpointGroup(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_show_endpoint_group_id_name(self):
# vpn-endpoint-group-show.
resource = 'endpoint_group'
cmd = endpoint_group.ShowEndpointGroup(test_cli20.MyApp(sys.stdout),
None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_update_endpoint_group(self):
# vpn-endpoint-group-update myid --name newname --description newdesc.
resource = 'endpoint_group'
cmd = endpoint_group.UpdateEndpointGroup(test_cli20.MyApp(sys.stdout),
None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'newname',
'--description', 'newdesc'],
{'name': 'newname',
'description': 'newdesc'})
def test_delete_endpoint_group(self):
# vpn-endpoint-group-delete my-id.
resource = 'endpoint_group'
cmd = endpoint_group.DeleteEndpointGroup(test_cli20.MyApp(sys.stdout),
None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)

View File

@ -1,241 +0,0 @@
# (c) Copyright 2013 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.
#
import sys
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0.vpn import ikepolicy
from neutronclient.tests.unit import test_cli20
class CLITestV20VpnIkePolicyJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['ikepolicy']
def _test_create_ikepolicy_all_params(self, auth='sha1',
expected_exc=None):
# vpn-ikepolicy-create all params.
resource = 'ikepolicy'
cmd = ikepolicy.CreateIKEPolicy(test_cli20.MyApp(sys.stdout), None)
name = 'ikepolicy1'
description = 'my-ike-policy'
auth_algorithm = auth
encryption_algorithm = 'aes-256'
ike_version = 'v1'
phase1_negotiation_mode = 'main'
pfs = 'group5'
tenant_id = 'my-tenant'
my_id = 'my-id'
lifetime = 'units=seconds,value=20000'
args = [name,
'--description', description,
'--tenant-id', tenant_id,
'--auth-algorithm', auth_algorithm,
'--encryption-algorithm', encryption_algorithm,
'--ike-version', ike_version,
'--phase1-negotiation-mode', phase1_negotiation_mode,
'--lifetime', lifetime,
'--pfs', pfs]
position_names = ['name', 'description',
'auth_algorithm', 'encryption_algorithm',
'phase1_negotiation_mode',
'ike_version', 'pfs',
'tenant_id']
position_values = [name, description,
auth_algorithm, encryption_algorithm,
phase1_negotiation_mode, ike_version, pfs,
tenant_id]
extra_body = {
'lifetime': {
'units': 'seconds',
'value': 20000,
},
}
if not expected_exc:
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
extra_body=extra_body)
else:
self.assertRaises(
expected_exc,
self._test_create_resource,
resource, cmd, name, my_id, args,
position_names, position_values,
extra_body=extra_body)
def test_create_ikepolicy_all_params(self):
self._test_create_ikepolicy_all_params()
def test_create_ikepolicy_auth_sha256(self):
self._test_create_ikepolicy_all_params(auth='sha256')
def test_create_ikepolicy_auth_sha384(self):
self._test_create_ikepolicy_all_params(auth='sha384')
def test_create_ikepolicy_auth_sha512(self):
self._test_create_ikepolicy_all_params(auth='sha512')
def test_create_ikepolicy_invalid_auth(self):
self._test_create_ikepolicy_all_params(auth='invalid',
expected_exc=SystemExit)
def test_create_ikepolicy_with_limited_params(self):
# vpn-ikepolicy-create with limited params.
resource = 'ikepolicy'
cmd = ikepolicy.CreateIKEPolicy(test_cli20.MyApp(sys.stdout), None)
name = 'ikepolicy1'
auth_algorithm = 'sha1'
encryption_algorithm = 'aes-128'
ike_version = 'v1'
phase1_negotiation_mode = 'main'
pfs = 'group5'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = [name,
'--tenant-id', tenant_id]
position_names = ['name',
'auth_algorithm', 'encryption_algorithm',
'phase1_negotiation_mode',
'ike_version', 'pfs',
'tenant_id']
position_values = [name,
auth_algorithm, encryption_algorithm,
phase1_negotiation_mode,
ike_version, pfs,
tenant_id]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def _test_lifetime_values(self, lifetime, expected_exc=None):
resource = 'ikepolicy'
cmd = ikepolicy.CreateIKEPolicy(test_cli20.MyApp(sys.stdout), None)
name = 'ikepolicy1'
description = 'my-ike-policy'
auth_algorithm = 'sha1'
encryption_algorithm = 'aes-256'
ike_version = 'v1'
phase1_negotiation_mode = 'main'
pfs = 'group5'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = [name,
'--description', description,
'--tenant-id', tenant_id,
'--auth-algorithm', auth_algorithm,
'--encryption-algorithm', encryption_algorithm,
'--ike-version', ike_version,
'--phase1-negotiation-mode', phase1_negotiation_mode,
'--lifetime', lifetime,
'--pfs', pfs]
position_names = ['name', 'description',
'auth_algorithm', 'encryption_algorithm',
'phase1_negotiation_mode',
'ike_version', 'pfs',
'tenant_id']
position_values = [name, description,
auth_algorithm, encryption_algorithm,
phase1_negotiation_mode, ike_version, pfs,
tenant_id]
if not expected_exc:
expected_exc = exceptions.CommandError
self.assertRaises(
expected_exc,
self._test_create_resource,
resource, cmd, name, my_id, args,
position_names, position_values)
def test_create_ikepolicy_with_invalid_lifetime_keys(self):
lifetime = 'uts=seconds,val=20000'
self._test_lifetime_values(lifetime, expected_exc=SystemExit)
def test_create_ikepolicy_with_invalid_lifetime_value(self):
lifetime = 'units=seconds,value=-1'
self._test_lifetime_values(lifetime)
def test_list_ikepolicy(self):
# vpn-ikepolicy-list.
resources = "ikepolicies"
cmd = ikepolicy.ListIKEPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_ikepolicy_pagination(self):
# vpn-ikepolicy-list.
resources = "ikepolicies"
cmd = ikepolicy.ListIKEPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_ikepolicy_sort(self):
# vpn-ikepolicy-list --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = "ikepolicies"
cmd = ikepolicy.ListIKEPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_ikepolicy_limit(self):
# vpn-ikepolicy-list -P.
resources = "ikepolicies"
cmd = ikepolicy.ListIKEPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_ikepolicy_id(self):
# vpn-ikepolicy-show ikepolicy_id.
resource = 'ikepolicy'
cmd = ikepolicy.ShowIKEPolicy(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_show_ikepolicy_id_name(self):
# vpn-ikepolicy-show.
resource = 'ikepolicy'
cmd = ikepolicy.ShowIKEPolicy(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_update_ikepolicy(self):
# vpn-ikepolicy-update myid --name newname --tags a b.
resource = 'ikepolicy'
cmd = ikepolicy.UpdateIKEPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'newname'],
{'name': 'newname', })
# vpn-ikepolicy-update myid --pfs group2 --ike-version v2.
self._test_update_resource(resource, cmd, 'myid',
['myid', '--pfs', 'group2',
'--ike-version', 'v2'],
{'pfs': 'group2',
'ike_version': 'v2'})
def test_delete_ikepolicy(self):
# vpn-ikepolicy-delete my-id.
resource = 'ikepolicy'
cmd = ikepolicy.DeleteIKEPolicy(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)

View File

@ -1,342 +0,0 @@
# (c) Copyright 2013 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.
#
import sys
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0.vpn import ipsec_site_connection
from neutronclient.tests.unit import test_cli20
class CLITestV20IPsecSiteConnectionJSON(test_cli20.CLITestV20Base):
# TODO(pcm): Remove, once peer-cidr is deprecated completely
def test_create_ipsec_site_connection_all_params_using_peer_cidrs(self):
# ipsecsite-connection-create all params using peer CIDRs.
resource = 'ipsec_site_connection'
cmd = ipsec_site_connection.CreateIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
tenant_id = 'mytenant_id'
name = 'connection1'
my_id = 'my_id'
peer_address = '192.168.2.10'
peer_id = '192.168.2.10'
psk = 'abcd'
mtu = '1500'
initiator = 'bi-directional'
vpnservice_id = 'vpnservice_id'
ikepolicy_id = 'ikepolicy_id'
ipsecpolicy_id = 'ipsecpolicy_id'
peer_cidrs = ['192.168.3.0/24', '192.168.2.0/24']
admin_state = True
description = 'my-vpn-connection'
dpd = 'action=restart,interval=30,timeout=120'
args = ['--tenant-id', tenant_id,
'--peer-address', peer_address, '--peer-id', peer_id,
'--psk', psk, '--initiator', initiator,
'--vpnservice-id', vpnservice_id,
'--ikepolicy-id', ikepolicy_id, '--name', name,
'--ipsecpolicy-id', ipsecpolicy_id, '--mtu', mtu,
'--description', description,
'--peer-cidr', '192.168.3.0/24',
'--peer-cidr', '192.168.2.0/24',
'--dpd', dpd]
position_names = ['name', 'tenant_id', 'admin_state_up',
'peer_address', 'peer_id', 'peer_cidrs',
'psk', 'mtu', 'initiator', 'description',
'vpnservice_id', 'ikepolicy_id',
'ipsecpolicy_id']
position_values = [name, tenant_id, admin_state, peer_address,
peer_id, peer_cidrs, psk, mtu,
initiator, description,
vpnservice_id, ikepolicy_id, ipsecpolicy_id]
extra_body = {
'dpd': {
'action': 'restart',
'interval': 30,
'timeout': 120,
},
}
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
extra_body=extra_body)
def test_create_ipsec_site_conn_all_params(self):
# ipsecsite-connection-create all params using endpoint groups.
resource = 'ipsec_site_connection'
cmd = ipsec_site_connection.CreateIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
tenant_id = 'mytenant_id'
name = 'connection1'
my_id = 'my_id'
peer_address = '192.168.2.10'
peer_id = '192.168.2.10'
psk = 'abcd'
mtu = '1500'
initiator = 'bi-directional'
vpnservice_id = 'vpnservice_id'
ikepolicy_id = 'ikepolicy_id'
ipsecpolicy_id = 'ipsecpolicy_id'
local_ep_group = 'local-epg'
peer_ep_group = 'peer-epg'
admin_state = True
description = 'my-vpn-connection'
dpd = 'action=restart,interval=30,timeout=120'
args = ['--tenant-id', tenant_id,
'--peer-address', peer_address, '--peer-id', peer_id,
'--psk', psk, '--initiator', initiator,
'--vpnservice-id', vpnservice_id,
'--ikepolicy-id', ikepolicy_id, '--name', name,
'--ipsecpolicy-id', ipsecpolicy_id, '--mtu', mtu,
'--description', description,
'--local-ep-group', local_ep_group,
'--peer-ep-group', peer_ep_group,
'--dpd', dpd]
position_names = ['name', 'tenant_id', 'admin_state_up',
'peer_address', 'peer_id', 'psk', 'mtu',
'local_ep_group_id', 'peer_ep_group_id',
'initiator', 'description',
'vpnservice_id', 'ikepolicy_id',
'ipsecpolicy_id']
position_values = [name, tenant_id, admin_state, peer_address,
peer_id, psk, mtu, local_ep_group,
peer_ep_group, initiator, description,
vpnservice_id, ikepolicy_id, ipsecpolicy_id]
extra_body = {
'dpd': {
'action': 'restart',
'interval': 30,
'timeout': 120,
},
}
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
extra_body=extra_body)
def test_create_ipsec_site_connection_with_limited_params(self):
# ipsecsite-connection-create with limited params.
resource = 'ipsec_site_connection'
cmd = ipsec_site_connection.CreateIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
tenant_id = 'mytenant_id'
my_id = 'my_id'
peer_address = '192.168.2.10'
peer_id = '192.168.2.10'
psk = 'abcd'
mtu = '1500'
initiator = 'bi-directional'
vpnservice_id = 'vpnservice_id'
ikepolicy_id = 'ikepolicy_id'
ipsecpolicy_id = 'ipsecpolicy_id'
local_ep_group = 'local-epg'
peer_ep_group = 'peer-epg'
admin_state = True
args = ['--tenant-id', tenant_id,
'--peer-address', peer_address,
'--peer-id', peer_id,
'--psk', psk,
'--vpnservice-id', vpnservice_id,
'--ikepolicy-id', ikepolicy_id,
'--ipsecpolicy-id', ipsecpolicy_id,
'--local-ep-group', local_ep_group,
'--peer-ep-group', peer_ep_group]
position_names = ['tenant_id', 'admin_state_up',
'peer_address', 'peer_id',
'local_ep_group_id', 'peer_ep_group_id',
'psk', 'mtu', 'initiator',
'vpnservice_id', 'ikepolicy_id',
'ipsecpolicy_id']
position_values = [tenant_id, admin_state, peer_address, peer_id,
local_ep_group, peer_ep_group, psk, mtu, initiator,
vpnservice_id, ikepolicy_id, ipsecpolicy_id]
self._test_create_resource(resource, cmd, None, my_id, args,
position_names, position_values)
def _test_create_failure(self, additional_args=None, expected_exc=None):
# Helper to test failure of IPSec site-to-site creation failure.
resource = 'ipsec_site_connection'
cmd = ipsec_site_connection.CreateIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
tenant_id = 'mytenant_id'
my_id = 'my_id'
peer_address = '192.168.2.10'
peer_id = '192.168.2.10'
psk = 'abcd'
mtu = '1500'
initiator = 'bi-directional'
vpnservice_id = 'vpnservice_id'
ikepolicy_id = 'ikepolicy_id'
ipsecpolicy_id = 'ipsecpolicy_id'
admin_state = True
args = ['--tenant-id', tenant_id,
'--peer-address', peer_address,
'--peer-id', peer_id,
'--psk', psk,
'--vpnservice-id', vpnservice_id,
'--ikepolicy-id', ikepolicy_id,
'--ipsecpolicy-id', ipsecpolicy_id]
if additional_args is not None:
args += additional_args
position_names = ['tenant_id', 'admin_state_up', 'peer_address',
'peer_id', 'psk', 'mtu', 'initiator',
'local_ep_group_id', 'peer_ep_group_id',
'vpnservice_id', 'ikepolicy_id', 'ipsecpolicy_id']
position_values = [tenant_id, admin_state, peer_address, peer_id, psk,
mtu, initiator, None, None, vpnservice_id,
ikepolicy_id, ipsecpolicy_id]
if not expected_exc:
expected_exc = exceptions.CommandError
self.assertRaises(expected_exc,
self._test_create_resource,
resource, cmd, None, my_id, args,
position_names, position_values)
def test_fail_create_with_invalid_mtu(self):
# ipsecsite-connection-create with invalid dpd values.
bad_mtu = ['--mtu', '67']
self._test_create_failure(bad_mtu)
def test_fail_create_with_invalid_dpd_keys(self):
bad_dpd_key = ['--dpd', 'act=restart,interval=30,time=120']
self._test_create_failure(bad_dpd_key, SystemExit)
def test_fail_create_with_invalid_dpd_values(self):
bad_dpd_values = ['--dpd', 'action=hold,interval=30,timeout=-1']
self._test_create_failure(bad_dpd_values)
def test_fail_create_missing_endpoint_groups_or_cidr(self):
# Must provide either endpoint groups or peer cidrs.
self._test_create_failure()
def test_fail_create_missing_peer_endpoint_group(self):
# Fails if dont have both endpoint groups - missing peer.
self._test_create_failure(['--local-ep-group', 'local-epg'])
def test_fail_create_missing_local_endpoint_group(self):
# Fails if dont have both endpoint groups - missing local.
self._test_create_failure(['--peer-ep-group', 'peer-epg'])
def test_fail_create_when_both_endpoints_and_peer_cidr(self):
# Cannot intermix endpoint groups and peer CIDRs for create.
additional_args = ['--local-ep-group', 'local-epg',
'--peer-ep-group', 'peer-epg',
'--peer-cidr', '10.2.0.0/24']
self._test_create_failure(additional_args)
def test_list_ipsec_site_connection(self):
# ipsecsite-connection-list.
resources = "ipsec_site_connections"
cmd = ipsec_site_connection.ListIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
self._test_list_resources(resources, cmd, True)
def test_list_ipsec_site_connection_pagination(self):
# ipsecsite-connection-list.
resources = "ipsec_site_connections"
cmd = ipsec_site_connection.ListIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_ipsec_site_connection_sort(self):
# ipsecsite-connection-list.
# --sort-key name --sort-key id --sort-key asc --sort-key desc
resources = "ipsec_site_connections"
cmd = ipsec_site_connection.ListIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_ipsec_site_connection_limit(self):
# ipsecsite-connection-list -P.
resources = "ipsec_site_connections"
cmd = ipsec_site_connection.ListIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
self._test_list_resources(resources, cmd, page_size=1000)
def test_delete_ipsec_site_connection(self):
# ipsecsite-connection-delete my-id.
resource = 'ipsec_site_connection'
cmd = ipsec_site_connection.DeleteIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)
def test_update_ipsec_site_connection(self):
# ipsecsite-connection-update myid --name Branch-new --tags a b.
resource = 'ipsec_site_connection'
cmd = ipsec_site_connection.UpdateIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'Branch-new',
'--tags', 'a', 'b'],
{'name': 'Branch-new',
'tags': ['a', 'b'], })
# ipsecsite-connection-update myid --mtu 69 --initiator response-only
# --peer-id '192.168.2.11' --peer-ep-group 'update-grp'
self._test_update_resource(resource, cmd, 'myid',
['myid', '--mtu', '69',
'--initiator', 'response-only',
'--peer-id', '192.168.2.11',
'--peer-ep-group', 'update-grp'],
{'mtu': '69',
'initiator': 'response-only',
'peer_id': '192.168.2.11',
'peer_ep_group_id': 'update-grp', },)
def test_show_ipsec_site_connection_id(self):
# ipsecsite-connection-show test_id."""
resource = 'ipsec_site_connection'
cmd = ipsec_site_connection.ShowIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_show_ipsec_site_connection_id_name(self):
# ipsecsite-connection-show."""
resource = 'ipsec_site_connection'
cmd = ipsec_site_connection.ShowIPsecSiteConnection(
test_cli20.MyApp(sys.stdout), None
)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])

View File

@ -1,249 +0,0 @@
# (c) Copyright 2013 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.
#
import sys
from neutronclient.common import exceptions
from neutronclient.neutron.v2_0.vpn import ipsecpolicy
from neutronclient.tests.unit import test_cli20
class CLITestV20VpnIpsecPolicyJSON(test_cli20.CLITestV20Base):
non_admin_status_resources = ['ipsecpolicy']
def _test_create_ipsecpolicy_all_params(self, auth='sha1',
expected_exc=None):
# vpn-ipsecpolicy-create all params with dashes.
resource = 'ipsecpolicy'
cmd = ipsecpolicy.CreateIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
name = 'ipsecpolicy1'
description = 'first-ipsecpolicy1'
auth_algorithm = auth
encryption_algorithm = 'aes-256'
encapsulation_mode = 'tunnel'
pfs = 'group5'
transform_protocol = 'ah'
tenant_id = 'my-tenant'
my_id = 'my-id'
lifetime = 'units=seconds,value=20000'
args = [name,
'--description', description,
'--tenant-id', tenant_id,
'--auth-algorithm', auth_algorithm,
'--encryption-algorithm', encryption_algorithm,
'--transform-protocol', transform_protocol,
'--encapsulation-mode', encapsulation_mode,
'--lifetime', lifetime,
'--pfs', pfs]
position_names = ['name', 'auth_algorithm', 'encryption_algorithm',
'encapsulation_mode', 'description',
'transform_protocol', 'pfs',
'tenant_id']
position_values = [name, auth_algorithm, encryption_algorithm,
encapsulation_mode, description,
transform_protocol, pfs,
tenant_id]
extra_body = {
'lifetime': {
'units': 'seconds',
'value': 20000,
},
}
if not expected_exc:
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
extra_body=extra_body)
else:
self.assertRaises(
expected_exc,
self._test_create_resource,
resource, cmd, name, my_id, args,
position_names, position_values,
extra_body=extra_body)
def test_create_ipsecpolicy_all_params(self):
self._test_create_ipsecpolicy_all_params()
def test_create_ipsecpolicy_auth_sha256(self):
self._test_create_ipsecpolicy_all_params(auth='sha256')
def test_create_ipsecpolicy_auth_sha384(self):
self._test_create_ipsecpolicy_all_params(auth='sha384')
def test_create_ipsecpolicy_auth_sha512(self):
self._test_create_ipsecpolicy_all_params(auth='sha512')
def test_create_ipsecpolicy_invalid_auth(self):
self._test_create_ipsecpolicy_all_params(auth='invalid',
expected_exc=SystemExit)
def test_create_ipsecpolicy_with_limited_params(self):
# vpn-ipsecpolicy-create with limited params.
resource = 'ipsecpolicy'
cmd = ipsecpolicy.CreateIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
name = 'ipsecpolicy1'
auth_algorithm = 'sha1'
encryption_algorithm = 'aes-128'
encapsulation_mode = 'tunnel'
pfs = 'group5'
transform_protocol = 'esp'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = [name,
'--tenant-id', tenant_id]
position_names = ['name', 'auth_algorithm', 'encryption_algorithm',
'encapsulation_mode',
'transform_protocol', 'pfs',
'tenant_id']
position_values = [name, auth_algorithm, encryption_algorithm,
encapsulation_mode,
transform_protocol, pfs,
tenant_id]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def _test_lifetime_values(self, lifetime, expected_exc=None):
resource = 'ipsecpolicy'
cmd = ipsecpolicy.CreateIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
name = 'ipsecpolicy1'
description = 'my-ipsec-policy'
auth_algorithm = 'sha1'
encryption_algorithm = 'aes-256'
ike_version = 'v1'
phase1_negotiation_mode = 'main'
pfs = 'group5'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = [name,
'--description', description,
'--tenant-id', tenant_id,
'--auth-algorithm', auth_algorithm,
'--encryption-algorithm', encryption_algorithm,
'--ike-version', ike_version,
'--phase1-negotiation-mode', phase1_negotiation_mode,
'--lifetime', lifetime,
'--pfs', pfs]
position_names = ['name', 'description',
'auth_algorithm', 'encryption_algorithm',
'phase1_negotiation_mode',
'ike_version', 'pfs',
'tenant_id']
position_values = [name, description,
auth_algorithm, encryption_algorithm,
phase1_negotiation_mode, ike_version, pfs,
tenant_id]
if not expected_exc:
expected_exc = exceptions.CommandError
self.assertRaises(
expected_exc,
self._test_create_resource,
resource, cmd, name, my_id, args,
position_names, position_values)
def test_create_ipsecpolicy_with_invalid_lifetime_keys(self):
lifetime = 'uts=seconds,val=20000'
self._test_lifetime_values(lifetime, SystemExit)
def test_create_ipsecpolicy_with_invalid_lifetime_units(self):
lifetime = 'units=minutes,value=600'
self._test_lifetime_values(lifetime)
def test_create_ipsecpolicy_with_invalid_lifetime_value(self):
lifetime = 'units=seconds,value=0'
self._test_lifetime_values(lifetime)
def test_list_ipsecpolicy(self):
# vpn-ipsecpolicy-list.
resources = "ipsecpolicies"
cmd = ipsecpolicy.ListIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_ipsecpolicy_pagination(self):
# vpn-ipsecpolicy-list.
resources = "ipsecpolicies"
cmd = ipsecpolicy.ListIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_ipsecpolicy_sort(self):
# vpn-ipsecpolicy-list --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = "ipsecpolicies"
cmd = ipsecpolicy.ListIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_ipsecpolicy_limit(self):
# vpn-ipsecpolicy-list -P.
resources = "ipsecpolicies"
cmd = ipsecpolicy.ListIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_ipsecpolicy_id(self):
# vpn-ipsecpolicy-show ipsecpolicy_id.
resource = 'ipsecpolicy'
cmd = ipsecpolicy.ShowIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_show_ipsecpolicy_id_name(self):
# vpn-ipsecpolicy-show.
resource = 'ipsecpolicy'
cmd = ipsecpolicy.ShowIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_update_ipsecpolicy_name(self):
# vpn-ipsecpolicy-update myid --name newname --tags a b.
resource = 'ipsecpolicy'
cmd = ipsecpolicy.UpdateIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'newname'],
{'name': 'newname', })
def test_update_ipsecpolicy_other_params(self):
# vpn-ipsecpolicy-update myid --transform-protocol esp
# --pfs group14 --encapsulation-mode transport
resource = 'ipsecpolicy'
cmd = ipsecpolicy.UpdateIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--transform-protocol', 'esp',
'--pfs', 'group14',
'--encapsulation-mode', 'transport'],
{'transform_protocol': 'esp',
'pfs': 'group14',
'encapsulation_mode': 'transport', })
def test_delete_ipsecpolicy(self):
# vpn-ipsecpolicy-delete my-id.
resource = 'ipsecpolicy'
cmd = ipsecpolicy.DeleteIPsecPolicy(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)

View File

@ -1,157 +0,0 @@
# (c) Copyright 2013 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.
#
import sys
from neutronclient.neutron.v2_0.vpn import vpnservice
from neutronclient.tests.unit import test_cli20
class CLITestV20VpnServiceJSON(test_cli20.CLITestV20Base):
def test_create_vpnservice_all_params(self):
# vpn-service-create all params.
resource = 'vpnservice'
cmd = vpnservice.CreateVPNService(test_cli20.MyApp(sys.stdout), None)
subnet = 'mysubnet-id'
router = 'myrouter-id'
tenant_id = 'mytenant-id'
my_id = 'my-id'
name = 'myvpnservice'
description = 'my-vpn-service'
admin_state = True
args = ['--name', name,
'--description', description,
router,
subnet,
'--tenant-id', tenant_id]
position_names = ['admin_state_up', 'name', 'description',
'subnet_id', 'router_id',
'tenant_id']
position_values = [admin_state, name, description,
subnet, router, tenant_id]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values)
def test_create_vpnservice_with_limited_params(self):
# vpn-service-create with limited params.
resource = 'vpnservice'
cmd = vpnservice.CreateVPNService(test_cli20.MyApp(sys.stdout), None)
subnet = 'mysubnet-id'
router = 'myrouter-id'
tenant_id = 'mytenant-id'
my_id = 'my-id'
admin_state = True
args = [router,
subnet,
'--tenant-id', tenant_id]
position_names = ['admin_state_up',
'subnet_id', 'router_id',
'tenant_id']
position_values = [admin_state, subnet, router, tenant_id]
self._test_create_resource(resource, cmd, None, my_id, args,
position_names, position_values)
def test_create_vpnservice_without_subnet(self):
# vpn-service-create with no subnet provided.
resource = 'vpnservice'
cmd = vpnservice.CreateVPNService(test_cli20.MyApp(sys.stdout), None)
router = 'myrouter-id'
tenant_id = 'mytenant-id'
my_id = 'my-id'
admin_state = True
args = [router,
'--tenant-id', tenant_id]
position_names = ['admin_state_up',
'subnet_id', 'router_id',
'tenant_id']
position_values = [admin_state, None, router, tenant_id]
self._test_create_resource(resource, cmd, None, my_id, args,
position_names, position_values)
def test_list_vpnservice(self):
# vpn-service-list.
resources = "vpnservices"
cmd = vpnservice.ListVPNService(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_vpnservice_pagination(self):
# vpn-service-list.
resources = "vpnservices"
cmd = vpnservice.ListVPNService(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_vpnservice_sort(self):
# vpn-service-list --sort-key name --sort-key id --sort-key asc
# --sort-key desc
resources = "vpnservices"
cmd = vpnservice.ListVPNService(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_vpnservice_limit(self):
# vpn-service-list -P.
resources = "vpnservices"
cmd = vpnservice.ListVPNService(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_show_vpnservice_id(self):
# vpn-service-show test_id.
resource = 'vpnservice'
cmd = vpnservice.ShowVPNService(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_show_vpnservice_id_name(self):
# vpn-service-show."""
resource = 'vpnservice'
cmd = vpnservice.ShowVPNService(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_update_vpnservice(self):
# vpn-service-update myid --name newname --tags a b.
resource = 'vpnservice'
cmd = vpnservice.UpdateVPNService(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'newname'],
{'name': 'newname', })
# vpn-service-update myid --admin-state-up False
self._test_update_resource(resource, cmd, 'myid',
['myid', '--admin-state-up', 'False'],
{'admin_state_up': 'False', })
def test_delete_vpnservice(self):
# vpn-service-delete my-id.
resource = 'vpnservice'
cmd = vpnservice.DeleteVPNService(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)

View File

@ -1,130 +0,0 @@
# (c) Copyright 2013 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.
#
import testtools
from neutronclient.common import exceptions
from neutronclient.common import utils
from neutronclient.neutron.v2_0.vpn import utils as vpn_utils
class TestVPNUtils(testtools.TestCase):
def test_validate_lifetime_dictionary_seconds(self):
input_str = utils.str2dict("units=seconds,value=3600")
self.assertIsNone(vpn_utils.validate_lifetime_dict(input_str))
def test_validate_dpd_dictionary_action_hold(self):
input_str = utils.str2dict("action=hold,interval=30,timeout=120")
self.assertIsNone(vpn_utils.validate_dpd_dict(input_str))
def test_validate_dpd_dictionary_action_restart(self):
input_str = utils.str2dict("action=restart,interval=30,timeout=120")
self.assertIsNone(vpn_utils.validate_dpd_dict(input_str))
def test_validate_dpd_dictionary_action_restart_by_peer(self):
input_str = utils.str2dict(
"action=restart-by-peer,interval=30,timeout=120"
)
self.assertIsNone(vpn_utils.validate_dpd_dict(input_str))
def test_validate_dpd_dictionary_action_clear(self):
input_str = utils.str2dict('action=clear,interval=30,timeout=120')
self.assertIsNone(vpn_utils.validate_dpd_dict(input_str))
def test_validate_dpd_dictionary_action_disabled(self):
input_str = utils.str2dict('action=disabled,interval=30,timeout=120')
self.assertIsNone(vpn_utils.validate_dpd_dict(input_str))
def test_validate_lifetime_dictionary_invalid_unit_key(self):
input_str = utils.str2dict('ut=seconds,value=3600')
self._test_validate_lifetime_negative_test_case(input_str)
def test_validate_lifetime_dictionary_invalid_unit_key_value(self):
input_str = utils.str2dict('units=seconds,val=3600')
self._test_validate_lifetime_negative_test_case(input_str)
def test_validate_lifetime_dictionary_unsupported_units(self):
input_str = utils.str2dict('units=minutes,value=3600')
self._test_validate_lifetime_negative_test_case(input_str)
def test_validate_lifetime_dictionary_invalid_empty_unit(self):
input_str = utils.str2dict('units=,value=3600')
self._test_validate_lifetime_negative_test_case(input_str)
def test_validate_lifetime_dictionary_under_minimum_integer_value(self):
input_str = utils.str2dict('units=seconds,value=59')
self._test_validate_lifetime_negative_test_case(input_str)
def test_validate_lifetime_dictionary_negative_integer_value(self):
input_str = utils.str2dict('units=seconds,value=-1')
self._test_validate_lifetime_negative_test_case(input_str)
def test_validate_lifetime_dictionary_empty_value(self):
input_str = utils.str2dict('units=seconds,value=')
self._test_validate_lifetime_negative_test_case(input_str)
def test_validate_dpd_dictionary_invalid_key_action(self):
input_str = utils.str2dict('act=hold,interval=30,timeout=120')
self._test_validate_dpd_negative_test_case(input_str)
def test_validate_dpd_dictionary_invalid_key_interval(self):
input_str = utils.str2dict('action=hold,int=30,timeout=120')
self._test_validate_dpd_negative_test_case(input_str)
def test_validate_dpd_dictionary_invalid_key_timeout(self):
input_str = utils.str2dict('action=hold,interval=30,tiut=120')
self._test_validate_dpd_negative_test_case(input_str)
def test_validate_dpd_dictionary_unsupported_action(self):
input_str = utils.str2dict('action=bye-bye,interval=30,timeout=120')
self._test_validate_dpd_negative_test_case(input_str)
def test_validate_dpd_dictionary_empty_action(self):
input_str = utils.str2dict('action=,interval=30,timeout=120')
self._test_validate_dpd_negative_test_case(input_str)
def test_validate_dpd_dictionary_empty_interval(self):
input_str = utils.str2dict('action=hold,interval=,timeout=120')
self._test_validate_dpd_negative_test_case(input_str)
def test_validate_dpd_dictionary_negative_interval_value(self):
input_str = utils.str2dict('action=hold,interval=-1,timeout=120')
self._test_validate_lifetime_negative_test_case(input_str)
def test_validate_dpd_dictionary_zero_timeout(self):
input_str = utils.str2dict('action=hold,interval=30,timeout=0')
self._test_validate_dpd_negative_test_case(input_str)
def test_validate_dpd_dictionary_empty_timeout(self):
input_str = utils.str2dict('action=hold,interval=30,timeout=')
self._test_validate_dpd_negative_test_case(input_str)
def test_validate_dpd_dictionary_negative_timeout_value(self):
input_str = utils.str2dict('action=hold,interval=30,timeout=-1')
self._test_validate_lifetime_negative_test_case(input_str)
def _test_validate_lifetime_negative_test_case(self, input_str):
"""Generic handler for negative lifetime tests."""
self.assertRaises(exceptions.CommandError,
vpn_utils.validate_lifetime_dict,
(input_str))
def _test_validate_dpd_negative_test_case(self, input_str):
"""Generic handler for negative lifetime tests."""
self.assertRaises(exceptions.CommandError,
vpn_utils.validate_lifetime_dict,
(input_str))

View File

@ -0,0 +1,12 @@
prelude: >
|
This new version of ``python-neutronclient`` does not include the
command line interface code. The "neutron" script is no longer
supported. This project only contains the OpenStack Client bindings
that are currently being moved to OpenStack SDK
<https://bugs.launchpad.net/neutron/+bug/1999774>_.
deprecations:
- |
This project no longer provides CLI support. All code has been removed.
Please use openstack CLI instead. See `openstack CLI command list
<https://docs.openstack.org/python-openstackclient/latest/cli/command-list.html>`_.

287
setup.cfg
View File

@ -26,9 +26,6 @@ packages =
neutronclient neutronclient
[entry_points] [entry_points]
console_scripts =
neutron = neutronclient.shell:main
openstack.cli.extension = openstack.cli.extension =
neutronclient = neutronclient.osc.plugin neutronclient = neutronclient.osc.plugin
@ -163,287 +160,3 @@ openstack.neutronclient.v2 =
vpn_ipsec_site_connection_show = neutronclient.osc.v2.vpnaas.ipsec_site_connection:ShowIPsecSiteConnection vpn_ipsec_site_connection_show = neutronclient.osc.v2.vpnaas.ipsec_site_connection:ShowIPsecSiteConnection
network_onboard_subnets = neutronclient.osc.v2.subnet_onboard.subnet_onboard:NetworkOnboardSubnets network_onboard_subnets = neutronclient.osc.v2.subnet_onboard.subnet_onboard:NetworkOnboardSubnets
neutron.cli.v2 =
bash-completion = neutronclient.shell:BashCompletionCommand
net-list = neutronclient.neutron.v2_0.network:ListNetwork
net-external-list = neutronclient.neutron.v2_0.network:ListExternalNetwork
net-show = neutronclient.neutron.v2_0.network:ShowNetwork
net-create = neutronclient.neutron.v2_0.network:CreateNetwork
net-delete = neutronclient.neutron.v2_0.network:DeleteNetwork
net-update = neutronclient.neutron.v2_0.network:UpdateNetwork
subnet-list = neutronclient.neutron.v2_0.subnet:ListSubnet
subnet-show = neutronclient.neutron.v2_0.subnet:ShowSubnet
subnet-create = neutronclient.neutron.v2_0.subnet:CreateSubnet
subnet-delete = neutronclient.neutron.v2_0.subnet:DeleteSubnet
subnet-update = neutronclient.neutron.v2_0.subnet:UpdateSubnet
subnetpool-list = neutronclient.neutron.v2_0.subnetpool:ListSubnetPool
subnetpool-show = neutronclient.neutron.v2_0.subnetpool:ShowSubnetPool
subnetpool-create = neutronclient.neutron.v2_0.subnetpool:CreateSubnetPool
subnetpool-delete = neutronclient.neutron.v2_0.subnetpool:DeleteSubnetPool
subnetpool-update = neutronclient.neutron.v2_0.subnetpool:UpdateSubnetPool
port-list = neutronclient.neutron.v2_0.port:ListPort
port-show = neutronclient.neutron.v2_0.port:ShowPort
port-create = neutronclient.neutron.v2_0.port:CreatePort
port-delete = neutronclient.neutron.v2_0.port:DeletePort
port-update = neutronclient.neutron.v2_0.port:UpdatePort
purge = neutronclient.neutron.v2_0.purge:Purge
quota-list = neutronclient.neutron.v2_0.quota:ListQuota
quota-show = neutronclient.neutron.v2_0.quota:ShowQuota
quota-default-show = neutronclient.neutron.v2_0.quota:ShowQuotaDefault
quota-delete = neutronclient.neutron.v2_0.quota:DeleteQuota
quota-update = neutronclient.neutron.v2_0.quota:UpdateQuota
ext-list = neutronclient.neutron.v2_0.extension:ListExt
ext-show = neutronclient.neutron.v2_0.extension:ShowExt
router-list = neutronclient.neutron.v2_0.router:ListRouter
router-port-list = neutronclient.neutron.v2_0.port:ListRouterPort
router-show = neutronclient.neutron.v2_0.router:ShowRouter
router-create = neutronclient.neutron.v2_0.router:CreateRouter
router-delete = neutronclient.neutron.v2_0.router:DeleteRouter
router-update = neutronclient.neutron.v2_0.router:UpdateRouter
router-interface-add = neutronclient.neutron.v2_0.router:AddInterfaceRouter
router-interface-delete = neutronclient.neutron.v2_0.router:RemoveInterfaceRouter
router-gateway-set = neutronclient.neutron.v2_0.router:SetGatewayRouter
router-gateway-clear = neutronclient.neutron.v2_0.router:RemoveGatewayRouter
floatingip-list = neutronclient.neutron.v2_0.floatingip:ListFloatingIP
floatingip-show = neutronclient.neutron.v2_0.floatingip:ShowFloatingIP
floatingip-create = neutronclient.neutron.v2_0.floatingip:CreateFloatingIP
floatingip-delete = neutronclient.neutron.v2_0.floatingip:DeleteFloatingIP
floatingip-associate = neutronclient.neutron.v2_0.floatingip:AssociateFloatingIP
floatingip-disassociate = neutronclient.neutron.v2_0.floatingip:DisassociateFloatingIP
security-group-list = neutronclient.neutron.v2_0.securitygroup:ListSecurityGroup
security-group-show = neutronclient.neutron.v2_0.securitygroup:ShowSecurityGroup
security-group-create = neutronclient.neutron.v2_0.securitygroup:CreateSecurityGroup
security-group-delete = neutronclient.neutron.v2_0.securitygroup:DeleteSecurityGroup
security-group-update = neutronclient.neutron.v2_0.securitygroup:UpdateSecurityGroup
security-group-rule-list = neutronclient.neutron.v2_0.securitygroup:ListSecurityGroupRule
security-group-rule-show = neutronclient.neutron.v2_0.securitygroup:ShowSecurityGroupRule
security-group-rule-create = neutronclient.neutron.v2_0.securitygroup:CreateSecurityGroupRule
security-group-rule-delete = neutronclient.neutron.v2_0.securitygroup:DeleteSecurityGroupRule
agent-list = neutronclient.neutron.v2_0.agent:ListAgent
agent-show = neutronclient.neutron.v2_0.agent:ShowAgent
agent-delete = neutronclient.neutron.v2_0.agent:DeleteAgent
agent-update = neutronclient.neutron.v2_0.agent:UpdateAgent
dhcp-agent-network-add = neutronclient.neutron.v2_0.agentscheduler:AddNetworkToDhcpAgent
dhcp-agent-network-remove = neutronclient.neutron.v2_0.agentscheduler:RemoveNetworkFromDhcpAgent
net-list-on-dhcp-agent = neutronclient.neutron.v2_0.agentscheduler:ListNetworksOnDhcpAgent
dhcp-agent-list-hosting-net = neutronclient.neutron.v2_0.agentscheduler:ListDhcpAgentsHostingNetwork
l3-agent-router-add = neutronclient.neutron.v2_0.agentscheduler:AddRouterToL3Agent
l3-agent-router-remove = neutronclient.neutron.v2_0.agentscheduler:RemoveRouterFromL3Agent
router-list-on-l3-agent = neutronclient.neutron.v2_0.agentscheduler:ListRoutersOnL3Agent
l3-agent-list-hosting-router = neutronclient.neutron.v2_0.agentscheduler:ListL3AgentsHostingRouter
lb-pool-list-on-agent = neutronclient.neutron.v2_0.agentscheduler:ListPoolsOnLbaasAgent
lb-agent-hosting-pool = neutronclient.neutron.v2_0.agentscheduler:GetLbaasAgentHostingPool
lbaas-loadbalancer-list-on-agent = neutronclient.neutron.v2_0.agentscheduler:ListLoadBalancersOnLbaasAgent
lbaas-agent-hosting-loadbalancer = neutronclient.neutron.v2_0.agentscheduler:GetLbaasAgentHostingLoadBalancer
service-provider-list = neutronclient.neutron.v2_0.servicetype:ListServiceProvider
rbac-create = neutronclient.neutron.v2_0.rbac:CreateRBACPolicy
rbac-update = neutronclient.neutron.v2_0.rbac:UpdateRBACPolicy
rbac-list = neutronclient.neutron.v2_0.rbac:ListRBACPolicy
rbac-show = neutronclient.neutron.v2_0.rbac:ShowRBACPolicy
rbac-delete = neutronclient.neutron.v2_0.rbac:DeleteRBACPolicy
address-scope-list = neutronclient.neutron.v2_0.address_scope:ListAddressScope
address-scope-show = neutronclient.neutron.v2_0.address_scope:ShowAddressScope
address-scope-create = neutronclient.neutron.v2_0.address_scope:CreateAddressScope
address-scope-delete = neutronclient.neutron.v2_0.address_scope:DeleteAddressScope
address-scope-update = neutronclient.neutron.v2_0.address_scope:UpdateAddressScope
availability-zone-list = neutronclient.neutron.v2_0.availability_zone:ListAvailabilityZone
auto-allocated-topology-show = neutronclient.neutron.v2_0.auto_allocated_topology:ShowAutoAllocatedTopology
auto-allocated-topology-delete = neutronclient.neutron.v2_0.auto_allocated_topology:DeleteAutoAllocatedTopology
net-ip-availability-list = neutronclient.neutron.v2_0.network_ip_availability:ListIpAvailability
net-ip-availability-show = neutronclient.neutron.v2_0.network_ip_availability:ShowIpAvailability
tag-add = neutronclient.neutron.v2_0.tag:AddTag
tag-replace = neutronclient.neutron.v2_0.tag:ReplaceTag
tag-remove = neutronclient.neutron.v2_0.tag:RemoveTag
qos-policy-list = neutronclient.neutron.v2_0.qos.policy:ListQoSPolicy
qos-policy-show = neutronclient.neutron.v2_0.qos.policy:ShowQoSPolicy
qos-policy-create = neutronclient.neutron.v2_0.qos.policy:CreateQoSPolicy
qos-policy-update = neutronclient.neutron.v2_0.qos.policy:UpdateQoSPolicy
qos-policy-delete = neutronclient.neutron.v2_0.qos.policy:DeleteQoSPolicy
qos-bandwidth-limit-rule-create = neutronclient.neutron.v2_0.qos.bandwidth_limit_rule:CreateQoSBandwidthLimitRule
qos-bandwidth-limit-rule-show = neutronclient.neutron.v2_0.qos.bandwidth_limit_rule:ShowQoSBandwidthLimitRule
qos-bandwidth-limit-rule-list = neutronclient.neutron.v2_0.qos.bandwidth_limit_rule:ListQoSBandwidthLimitRules
qos-bandwidth-limit-rule-update = neutronclient.neutron.v2_0.qos.bandwidth_limit_rule:UpdateQoSBandwidthLimitRule
qos-bandwidth-limit-rule-delete = neutronclient.neutron.v2_0.qos.bandwidth_limit_rule:DeleteQoSBandwidthLimitRule
qos-dscp-marking-rule-create = neutronclient.neutron.v2_0.qos.dscp_marking_rule:CreateQoSDscpMarkingRule
qos-dscp-marking-rule-show = neutronclient.neutron.v2_0.qos.dscp_marking_rule:ShowQoSDscpMarkingRule
qos-dscp-marking-rule-list = neutronclient.neutron.v2_0.qos.dscp_marking_rule:ListQoSDscpMarkingRules
qos-dscp-marking-rule-update = neutronclient.neutron.v2_0.qos.dscp_marking_rule:UpdateQoSDscpMarkingRule
qos-dscp-marking-rule-delete = neutronclient.neutron.v2_0.qos.dscp_marking_rule:DeleteQoSDscpMarkingRule
qos-minimum-bandwidth-rule-create = neutronclient.neutron.v2_0.qos.minimum_bandwidth_rule:CreateQoSMinimumBandwidthRule
qos-minimum-bandwidth-rule-show = neutronclient.neutron.v2_0.qos.minimum_bandwidth_rule:ShowQoSMinimumBandwidthRule
qos-minimum-bandwidth-rule-list = neutronclient.neutron.v2_0.qos.minimum_bandwidth_rule:ListQoSMinimumBandwidthRules
qos-minimum-bandwidth-rule-update = neutronclient.neutron.v2_0.qos.minimum_bandwidth_rule:UpdateQoSMinimumBandwidthRule
qos-minimum-bandwidth-rule-delete = neutronclient.neutron.v2_0.qos.minimum_bandwidth_rule:DeleteQoSMinimumBandwidthRule
qos-available-rule-types = neutronclient.neutron.v2_0.qos.rule:ListQoSRuleTypes
flavor-list = neutronclient.neutron.v2_0.flavor.flavor:ListFlavor
flavor-show = neutronclient.neutron.v2_0.flavor.flavor:ShowFlavor
flavor-create = neutronclient.neutron.v2_0.flavor.flavor:CreateFlavor
flavor-delete = neutronclient.neutron.v2_0.flavor.flavor:DeleteFlavor
flavor-update = neutronclient.neutron.v2_0.flavor.flavor:UpdateFlavor
flavor-associate = neutronclient.neutron.v2_0.flavor.flavor:AssociateFlavor
flavor-disassociate = neutronclient.neutron.v2_0.flavor.flavor:DisassociateFlavor
flavor-profile-list = neutronclient.neutron.v2_0.flavor.flavor_profile:ListFlavorProfile
flavor-profile-show = neutronclient.neutron.v2_0.flavor.flavor_profile:ShowFlavorProfile
flavor-profile-create = neutronclient.neutron.v2_0.flavor.flavor_profile:CreateFlavorProfile
flavor-profile-delete = neutronclient.neutron.v2_0.flavor.flavor_profile:DeleteFlavorProfile
flavor-profile-update = neutronclient.neutron.v2_0.flavor.flavor_profile:UpdateFlavorProfile
meter-label-create = neutronclient.neutron.v2_0.metering:CreateMeteringLabel
meter-label-list = neutronclient.neutron.v2_0.metering:ListMeteringLabel
meter-label-show = neutronclient.neutron.v2_0.metering:ShowMeteringLabel
meter-label-delete = neutronclient.neutron.v2_0.metering:DeleteMeteringLabel
meter-label-rule-create = neutronclient.neutron.v2_0.metering:CreateMeteringLabelRule
meter-label-rule-list = neutronclient.neutron.v2_0.metering:ListMeteringLabelRule
meter-label-rule-show = neutronclient.neutron.v2_0.metering:ShowMeteringLabelRule
meter-label-rule-delete = neutronclient.neutron.v2_0.metering:DeleteMeteringLabelRule
firewall-rule-list = neutronclient.neutron.v2_0.fw.firewallrule:ListFirewallRule
firewall-rule-show = neutronclient.neutron.v2_0.fw.firewallrule:ShowFirewallRule
firewall-rule-create = neutronclient.neutron.v2_0.fw.firewallrule:CreateFirewallRule
firewall-rule-update = neutronclient.neutron.v2_0.fw.firewallrule:UpdateFirewallRule
firewall-rule-delete = neutronclient.neutron.v2_0.fw.firewallrule:DeleteFirewallRule
firewall-policy-list = neutronclient.neutron.v2_0.fw.firewallpolicy:ListFirewallPolicy
firewall-policy-show = neutronclient.neutron.v2_0.fw.firewallpolicy:ShowFirewallPolicy
firewall-policy-create = neutronclient.neutron.v2_0.fw.firewallpolicy:CreateFirewallPolicy
firewall-policy-update = neutronclient.neutron.v2_0.fw.firewallpolicy:UpdateFirewallPolicy
firewall-policy-delete = neutronclient.neutron.v2_0.fw.firewallpolicy:DeleteFirewallPolicy
firewall-policy-insert-rule = neutronclient.neutron.v2_0.fw.firewallpolicy:FirewallPolicyInsertRule
firewall-policy-remove-rule = neutronclient.neutron.v2_0.fw.firewallpolicy:FirewallPolicyRemoveRule
firewall-list = neutronclient.neutron.v2_0.fw.firewall:ListFirewall
firewall-show = neutronclient.neutron.v2_0.fw.firewall:ShowFirewall
firewall-create = neutronclient.neutron.v2_0.fw.firewall:CreateFirewall
firewall-update = neutronclient.neutron.v2_0.fw.firewall:UpdateFirewall
firewall-delete = neutronclient.neutron.v2_0.fw.firewall:DeleteFirewall
bgp-dragent-speaker-add = neutronclient.neutron.v2_0.bgp.dragentscheduler:AddBGPSpeakerToDRAgent
bgp-dragent-speaker-remove = neutronclient.neutron.v2_0.bgp.dragentscheduler:RemoveBGPSpeakerFromDRAgent
bgp-speaker-list-on-dragent = neutronclient.neutron.v2_0.bgp.dragentscheduler:ListBGPSpeakersOnDRAgent
bgp-dragent-list-hosting-speaker = neutronclient.neutron.v2_0.bgp.dragentscheduler:ListDRAgentsHostingBGPSpeaker
bgp-speaker-list = neutronclient.neutron.v2_0.bgp.speaker:ListSpeakers
bgp-speaker-advertiseroute-list = neutronclient.neutron.v2_0.bgp.speaker:ListRoutesAdvertisedBySpeaker
bgp-speaker-show = neutronclient.neutron.v2_0.bgp.speaker:ShowSpeaker
bgp-speaker-create = neutronclient.neutron.v2_0.bgp.speaker:CreateSpeaker
bgp-speaker-update = neutronclient.neutron.v2_0.bgp.speaker:UpdateSpeaker
bgp-speaker-delete = neutronclient.neutron.v2_0.bgp.speaker:DeleteSpeaker
bgp-speaker-peer-add = neutronclient.neutron.v2_0.bgp.speaker:AddPeerToSpeaker
bgp-speaker-peer-remove = neutronclient.neutron.v2_0.bgp.speaker:RemovePeerFromSpeaker
bgp-speaker-network-add = neutronclient.neutron.v2_0.bgp.speaker:AddNetworkToSpeaker
bgp-speaker-network-remove = neutronclient.neutron.v2_0.bgp.speaker:RemoveNetworkFromSpeaker
bgp-peer-list = neutronclient.neutron.v2_0.bgp.peer:ListPeers
bgp-peer-show = neutronclient.neutron.v2_0.bgp.peer:ShowPeer
bgp-peer-create = neutronclient.neutron.v2_0.bgp.peer:CreatePeer
bgp-peer-update = neutronclient.neutron.v2_0.bgp.peer:UpdatePeer
bgp-peer-delete = neutronclient.neutron.v2_0.bgp.peer:DeletePeer
lbaas-loadbalancer-list = neutronclient.neutron.v2_0.lb.v2.loadbalancer:ListLoadBalancer
lbaas-loadbalancer-show = neutronclient.neutron.v2_0.lb.v2.loadbalancer:ShowLoadBalancer
lbaas-loadbalancer-create = neutronclient.neutron.v2_0.lb.v2.loadbalancer:CreateLoadBalancer
lbaas-loadbalancer-update = neutronclient.neutron.v2_0.lb.v2.loadbalancer:UpdateLoadBalancer
lbaas-loadbalancer-delete = neutronclient.neutron.v2_0.lb.v2.loadbalancer:DeleteLoadBalancer
lbaas-loadbalancer-stats = neutronclient.neutron.v2_0.lb.v2.loadbalancer:RetrieveLoadBalancerStats
lbaas-loadbalancer-status = neutronclient.neutron.v2_0.lb.v2.loadbalancer:RetrieveLoadBalancerStatus
lbaas-listener-list = neutronclient.neutron.v2_0.lb.v2.listener:ListListener
lbaas-listener-show = neutronclient.neutron.v2_0.lb.v2.listener:ShowListener
lbaas-listener-create = neutronclient.neutron.v2_0.lb.v2.listener:CreateListener
lbaas-listener-update = neutronclient.neutron.v2_0.lb.v2.listener:UpdateListener
lbaas-listener-delete = neutronclient.neutron.v2_0.lb.v2.listener:DeleteListener
lbaas-l7policy-list = neutronclient.neutron.v2_0.lb.v2.l7policy:ListL7Policy
lbaas-l7policy-show = neutronclient.neutron.v2_0.lb.v2.l7policy:ShowL7Policy
lbaas-l7policy-create = neutronclient.neutron.v2_0.lb.v2.l7policy:CreateL7Policy
lbaas-l7policy-update = neutronclient.neutron.v2_0.lb.v2.l7policy:UpdateL7Policy
lbaas-l7policy-delete = neutronclient.neutron.v2_0.lb.v2.l7policy:DeleteL7Policy
lbaas-l7rule-list = neutronclient.neutron.v2_0.lb.v2.l7rule:ListL7Rule
lbaas-l7rule-show = neutronclient.neutron.v2_0.lb.v2.l7rule:ShowL7Rule
lbaas-l7rule-create = neutronclient.neutron.v2_0.lb.v2.l7rule:CreateL7Rule
lbaas-l7rule-update = neutronclient.neutron.v2_0.lb.v2.l7rule:UpdateL7Rule
lbaas-l7rule-delete = neutronclient.neutron.v2_0.lb.v2.l7rule:DeleteL7Rule
lbaas-pool-list = neutronclient.neutron.v2_0.lb.v2.pool:ListPool
lbaas-pool-show = neutronclient.neutron.v2_0.lb.v2.pool:ShowPool
lbaas-pool-create = neutronclient.neutron.v2_0.lb.v2.pool:CreatePool
lbaas-pool-update = neutronclient.neutron.v2_0.lb.v2.pool:UpdatePool
lbaas-pool-delete = neutronclient.neutron.v2_0.lb.v2.pool:DeletePool
lbaas-healthmonitor-list = neutronclient.neutron.v2_0.lb.v2.healthmonitor:ListHealthMonitor
lbaas-healthmonitor-show = neutronclient.neutron.v2_0.lb.v2.healthmonitor:ShowHealthMonitor
lbaas-healthmonitor-create = neutronclient.neutron.v2_0.lb.v2.healthmonitor:CreateHealthMonitor
lbaas-healthmonitor-update = neutronclient.neutron.v2_0.lb.v2.healthmonitor:UpdateHealthMonitor
lbaas-healthmonitor-delete = neutronclient.neutron.v2_0.lb.v2.healthmonitor:DeleteHealthMonitor
lbaas-member-list = neutronclient.neutron.v2_0.lb.v2.member:ListMember
lbaas-member-show = neutronclient.neutron.v2_0.lb.v2.member:ShowMember
lbaas-member-create = neutronclient.neutron.v2_0.lb.v2.member:CreateMember
lbaas-member-update = neutronclient.neutron.v2_0.lb.v2.member:UpdateMember
lbaas-member-delete = neutronclient.neutron.v2_0.lb.v2.member:DeleteMember
lb-vip-list = neutronclient.neutron.v2_0.lb.vip:ListVip
lb-vip-show = neutronclient.neutron.v2_0.lb.vip:ShowVip
lb-vip-create = neutronclient.neutron.v2_0.lb.vip:CreateVip
lb-vip-update = neutronclient.neutron.v2_0.lb.vip:UpdateVip
lb-vip-delete = neutronclient.neutron.v2_0.lb.vip:DeleteVip
lb-pool-list = neutronclient.neutron.v2_0.lb.pool:ListPool
lb-pool-show = neutronclient.neutron.v2_0.lb.pool:ShowPool
lb-pool-create = neutronclient.neutron.v2_0.lb.pool:CreatePool
lb-pool-update = neutronclient.neutron.v2_0.lb.pool:UpdatePool
lb-pool-delete = neutronclient.neutron.v2_0.lb.pool:DeletePool
lb-pool-stats = neutronclient.neutron.v2_0.lb.pool:RetrievePoolStats
lb-member-list = neutronclient.neutron.v2_0.lb.member:ListMember
lb-member-show = neutronclient.neutron.v2_0.lb.member:ShowMember
lb-member-create = neutronclient.neutron.v2_0.lb.member:CreateMember
lb-member-update = neutronclient.neutron.v2_0.lb.member:UpdateMember
lb-member-delete = neutronclient.neutron.v2_0.lb.member:DeleteMember
lb-healthmonitor-list = neutronclient.neutron.v2_0.lb.healthmonitor:ListHealthMonitor
lb-healthmonitor-show = neutronclient.neutron.v2_0.lb.healthmonitor:ShowHealthMonitor
lb-healthmonitor-create = neutronclient.neutron.v2_0.lb.healthmonitor:CreateHealthMonitor
lb-healthmonitor-update = neutronclient.neutron.v2_0.lb.healthmonitor:UpdateHealthMonitor
lb-healthmonitor-delete = neutronclient.neutron.v2_0.lb.healthmonitor:DeleteHealthMonitor
lb-healthmonitor-associate = neutronclient.neutron.v2_0.lb.healthmonitor:AssociateHealthMonitor
lb-healthmonitor-disassociate = neutronclient.neutron.v2_0.lb.healthmonitor:DisassociateHealthMonitor
ipsec-site-connection-list = neutronclient.neutron.v2_0.vpn.ipsec_site_connection:ListIPsecSiteConnection
ipsec-site-connection-show = neutronclient.neutron.v2_0.vpn.ipsec_site_connection:ShowIPsecSiteConnection
ipsec-site-connection-create = neutronclient.neutron.v2_0.vpn.ipsec_site_connection:CreateIPsecSiteConnection
ipsec-site-connection-update = neutronclient.neutron.v2_0.vpn.ipsec_site_connection:UpdateIPsecSiteConnection
ipsec-site-connection-delete = neutronclient.neutron.v2_0.vpn.ipsec_site_connection:DeleteIPsecSiteConnection
vpn-endpoint-group-list = neutronclient.neutron.v2_0.vpn.endpoint_group:ListEndpointGroup
vpn-endpoint-group-show = neutronclient.neutron.v2_0.vpn.endpoint_group:ShowEndpointGroup
vpn-endpoint-group-create = neutronclient.neutron.v2_0.vpn.endpoint_group:CreateEndpointGroup
vpn-endpoint-group-update = neutronclient.neutron.v2_0.vpn.endpoint_group:UpdateEndpointGroup
vpn-endpoint-group-delete = neutronclient.neutron.v2_0.vpn.endpoint_group:DeleteEndpointGroup
vpn-service-list = neutronclient.neutron.v2_0.vpn.vpnservice:ListVPNService
vpn-service-show = neutronclient.neutron.v2_0.vpn.vpnservice:ShowVPNService
vpn-service-create = neutronclient.neutron.v2_0.vpn.vpnservice:CreateVPNService
vpn-service-update = neutronclient.neutron.v2_0.vpn.vpnservice:UpdateVPNService
vpn-service-delete = neutronclient.neutron.v2_0.vpn.vpnservice:DeleteVPNService
vpn-ipsecpolicy-list = neutronclient.neutron.v2_0.vpn.ipsecpolicy:ListIPsecPolicy
vpn-ipsecpolicy-show = neutronclient.neutron.v2_0.vpn.ipsecpolicy:ShowIPsecPolicy
vpn-ipsecpolicy-create = neutronclient.neutron.v2_0.vpn.ipsecpolicy:CreateIPsecPolicy
vpn-ipsecpolicy-update = neutronclient.neutron.v2_0.vpn.ipsecpolicy:UpdateIPsecPolicy
vpn-ipsecpolicy-delete = neutronclient.neutron.v2_0.vpn.ipsecpolicy:DeleteIPsecPolicy
vpn-ikepolicy-list = neutronclient.neutron.v2_0.vpn.ikepolicy:ListIKEPolicy
vpn-ikepolicy-show = neutronclient.neutron.v2_0.vpn.ikepolicy:ShowIKEPolicy
vpn-ikepolicy-create = neutronclient.neutron.v2_0.vpn.ikepolicy:CreateIKEPolicy
vpn-ikepolicy-update = neutronclient.neutron.v2_0.vpn.ikepolicy:UpdateIKEPolicy
vpn-ikepolicy-delete = neutronclient.neutron.v2_0.vpn.ikepolicy:DeleteIKEPolicy

View File

@ -1,27 +0,0 @@
_neutron_opts="" # lazy init
_neutron_flags="" # lazy init
_neutron_opts_exp="" # lazy init
_neutron()
{
local cur prev nbc cflags
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
if [ "x$_neutron_opts" == "x" ] ; then
nbc="`neutron bash-completion`"
_neutron_opts="`echo "$nbc" | sed -e "s/--[a-z0-9_-]*//g" -e "s/[ ][ ]*/ /g"`"
_neutron_flags="`echo " $nbc" | sed -e "s/ [^-][^-][a-z0-9_-]*//g" -e "s/[ ][ ]*/ /g"`"
_neutron_opts_exp="`echo "$_neutron_opts" | sed -e "s/[ ]/|/g"`"
fi
if [[ " ${COMP_WORDS[@]} " =~ " "($_neutron_opts_exp)" " && "$prev" != "help" ]] ; then
COMPLETION_CACHE=~/.neutronclient/*/*-cache
cflags="$_neutron_flags "$(cat $COMPLETION_CACHE 2> /dev/null | tr '\n' ' ')
COMPREPLY=($(compgen -W "${cflags}" -- ${cur}))
else
COMPREPLY=($(compgen -W "${_neutron_opts}" -- ${cur}))
fi
return 0
}
complete -F _neutron neutron

View File

@ -33,11 +33,6 @@ distribute = false
[testenv:venv] [testenv:venv]
commands = {posargs} commands = {posargs}
[testenv:functional]
setenv =
OS_TEST_PATH = ./neutronclient/tests/functional
OS_NEUTRONCLIENT_EXEC_DIR = {envdir}/bin
[testenv:cover] [testenv:cover]
setenv = setenv =
{[testenv]setenv} {[testenv]setenv}