def setup_method(self):
        self.session = Session('vswitch-dpm-host', 'vswitch-user',
                               'vswitch-pwd')
        self.client = Client(self.session)
        with requests_mock.mock() as m:
            # Because logon is deferred until needed, we perform it
            # explicitly in order to keep mocking in the actual test simple.
            m.post('/api/sessions', json={'api-session': 'vswitch-session-id'})
            self.session.logon()

        self.cpc_mgr = self.client.cpcs
        with requests_mock.mock() as m:
            result = {
                'cpcs': [
                    {
                        'object-uri': '/api/cpcs/vswitch-cpc-id-1',
                        'name': 'CPC',
                        'status': 'service-required',
                    }
                ]
            }
            m.get('/api/cpcs', json=result)

            cpcs = self.cpc_mgr.list()
            self.cpc = cpcs[0]
    def _do_parse_error_logon(self, m, json_content, exp_msg_pattern, exp_line,
                              exp_col):
        """
        Perform a session logon, and mock the provided (invalid) JSON content
        for the response so that a JSON parsing error is triggered.

        Assert that this is surfaced via a `zhmcclient.ParseError` exception,
        with the expected message (as a regexp pattern), line and column.
        """

        m.register_uri('POST', '/api/sessions',
                       content=json_content,
                       headers={'X-Request-Id': 'fake-request-id'})

        session = Session('fake-host', 'fake-user', 'fake-pw')

        exp_pe_pattern = \
            r"^JSON parse error in HTTP response: %s\. " \
            r"HTTP request: [^ ]+ [^ ]+\. " \
            r"Response status .*" % \
            exp_msg_pattern

        with pytest.raises(ParseError) as exc_info:
            session.logon()
        exc = exc_info.value

        assert re.match(exp_pe_pattern, str(exc))
        assert exc.line == exp_line
        assert exc.column == exp_col
def test_session_get_error_html_1():
    """
    This tests a dummy GET with a 500 response with HTML content.
    """
    session = Session('fake-host', 'fake-user', 'fake-id')
    with requests_mock.mock() as m:
        get_uri = "/api/version"
        get_resp_status = 500
        get_resp_content_type = 'text/html; charset=utf-8'
        get_resp_headers = {
            'content-type': get_resp_content_type,
        }
        get_resp_content = u"""\
<!doctype html public "-//IETF//DTD HTML 2.0//EN">\
 <html>\
<head>\
<title>Console Internal Error</title>\
 <link href="/skin/HMCskin.css" rel="stylesheet" type="text/css"/>\
</head>\
 <body>\
<h1>Console Internal Error</h1>\
<br><hr size="1" noshade>\
<h2>Details:</h2>\
<p><br>HTTP status code: 500\
<p><br>The server encountered an internal error that prevented it from\
 fulfilling this request.\
<p><br>\
<pre>javax.servlet.ServletException: Web Services are not enabled.
\tat com.ibm.hwmca.fw.api.ApiServlet.execute(ApiServlet.java:135)
\t. . .
</pre>\
<hr size="1" noshade>\
</body>\
</html>"""
        m.get(get_uri,
              text=get_resp_content,
              headers=get_resp_headers,
              status_code=get_resp_status)

        # The following expected results reflect what is done in
        # _session._result_object().

        exp_reason = 900
        exp_message = \
            "Console Configuration Error: " \
            "Web Services API is not enabled on the HMC."

        with pytest.raises(HTTPError) as exc_info:
            session.get(get_uri, logon_required=False)
        exc = exc_info.value

        assert exc.http_status == get_resp_status
        assert exc.reason == exp_reason
        assert exc.message == exp_message
        assert exc.request_uri.endswith(get_uri)
        assert exc.request_method == 'GET'
    def test_logoff(self):
        """Test Session.logoff() (and also Session.is_logon())."""

        with requests_mock.Mocker() as m:

            self.mock_server_1(m)

            # Create a session in logged-off state
            session = Session('fake-host', 'fake-userid', 'fake-pw')

            session.logon()

            logged_on = session.is_logon()
            assert logged_on

            # The code to be tested:
            session.logoff()

            assert session.session_id is None
            assert session.session is None
            assert 'X-API-Session' not in session.headers
            assert len(session.headers) == 2

            logged_on = session.is_logon()
            assert not logged_on
    def test_logon(
            self, host, userid, password, use_get_password, exp_exc):
        """Test Session.logon() (and also Session.is_logon())."""

        with requests_mock.Mocker() as m:

            self.mock_server_1(m)

            if use_get_password:
                get_password = mock.MagicMock()
                get_password.return_value = \
                    'fake-pw-{}-{}'.format(host, userid)
            else:
                get_password = None

            # Create a session in logged-off state
            session = Session(host, userid, password, None, get_password)

            assert session.session_id is None
            assert 'X-API-Session' not in session.headers
            assert session.session is None

            logged_on = session.is_logon()
            assert not logged_on

            if exp_exc:
                try:

                    # The code to be tested:
                    session.logon()

                except exp_exc:
                    pass

                logged_on = session.is_logon()
                assert not logged_on
            else:

                # The code to be tested:
                session.logon()

                assert session.session_id == 'fake-session-id'
                assert 'X-API-Session' in session.headers
                assert isinstance(session.session, requests.Session)

                if get_password:
                    if password is None:
                        get_password.assert_called_with(host, userid)
                        assert session._password == get_password.return_value
                    else:
                        get_password.assert_not_called()

                logged_on = session.is_logon()
                assert logged_on
def test_job_wait_complete3_success_result():
    """Test wait_for_completion() with successful complete job with a
    result."""
    with requests_mock.mock() as m:
        mock_server_1(m)
        session = Session('fake-host', 'fake-user', 'fake-pw')
        op_method = 'POST'
        op_uri = '/api/foo'
        job = Job(session, JOB_URI, op_method, op_uri)
        exp_op_result = {
            'foo': 'bar',
        }
        m.get(JOB_URI, [
            {
                'text': result_running_callback
            },
            {
                'text': result_complete_callback
            },
        ])
        m.delete(JOB_URI, status_code=204)

        op_result = job.wait_for_completion()

        assert op_result == exp_op_result
def test_job_check_complete_error1():
    """Test check_for_completion() with complete job in error (1)."""
    with requests_mock.mock() as m:
        mock_server_1(m)
        session = Session('fake-host', 'fake-user', 'fake-pw')
        op_method = 'POST'
        op_uri = '/api/foo'
        job = Job(session, JOB_URI, op_method, op_uri)
        query_job_status_result = {
            'status': 'complete',
            'job-status-code': 500,
            'job-reason-code': 42,
            # no 'job-results' field (it is not guaranteed to be there)
        }

        m.get(JOB_URI, json=query_job_status_result)
        m.delete(JOB_URI, status_code=204)

        with pytest.raises(HTTPError) as exc_info:
            job.check_for_completion()
        exc = exc_info.value

        assert exc.http_status == 500
        assert exc.reason == 42
        assert exc.message is None
    def test_init(self, host, userid, password, use_get_password, session_id):
        """Test initialization of Session object."""

        # TODO: Add support for input parameter: retry_timeout_config
        # TODO: Add support for input parameter: time_stats_keeper

        if use_get_password:
            def get_password(host, userid):
                pw = 'fake-pw-{}-{}'.format(host, userid)
                return pw
        else:
            get_password = None

        session = Session(host, userid, password, session_id, get_password)

        assert session.host == host
        assert session.userid == userid
        assert session._password == password
        assert session.session_id == session_id
        assert session.get_password == get_password

        base_url = 'https://{}:6794'.format(session.host)
        assert session.base_url == base_url

        assert session.headers['Content-type'] == 'application/json'
        assert session.headers['Accept'] == '*/*'

        if session_id is None:
            assert session.session is None
            assert 'X-API-Session' not in session.headers
            assert len(session.headers) == 2
        else:
            assert isinstance(session.session, requests.Session)
            assert session.headers['X-API-Session'] == session_id
            assert len(session.headers) == 3
 def setup_method(self):
     self.session = Session(host='fake-host')
     self.mgr = MyManager(self.session)
     self.uri = self.mgr._base_uri + '/deadbeef-beef-beef-beef-deadbeefbeef'
     self.name = "fake-name"
     self.uri_prop = 'fake-uri-prop'  # same as in MyManager
     self.name_prop = 'fake-name-prop'  # same as in MyManager
    def test_check_complete_success_result(self):
        """Test check_for_completion() with successful complete job with a
        result."""
        with requests_mock.mock() as m:
            self.mock_server_1(m)
            session = Session('fake-host', 'fake-user', 'fake-pw')
            op_method = 'POST'
            op_uri = '/api/foo'
            job = Job(session, self.job_uri, op_method, op_uri)
            exp_op_result = {
                'foo': 'bar',
            }
            query_job_status_result = {
                'status': 'complete',
                'job-status-code': 200,
                # 'job-reason-code' omitted because HTTP status good
                'job-results': exp_op_result,
            }
            m.get(self.job_uri, json=query_job_status_result)
            m.delete(self.job_uri, status_code=204)

            job_status, op_result = job.check_for_completion()

            assert job_status == 'complete'
            assert op_result == exp_op_result
Exemple #11
0
    def setup_method(self):
        """
        Setup that is called by pytest before each test method.
        """
        # pylint: disable=attribute-defined-outside-init

        self.session = Session(host='fake-host', userid='fake-user',
                               password='******')
        self.manager = MyManager(self.session)
        self.resource1_uri = "/api/fake-uri-1"
        self.resource1_name = "fake-name-1"
        self.resource1 = MyResource(
            self.manager, uri=self.resource1_uri,
            properties={
                self.manager._name_prop: self.resource1_name,
                "other": "fake-other-1"
            })
        self.resource2_uri = "/api/fake-uri-2"
        self.resource2_name = "fake-name-2"
        self.resource2 = MyResource(
            self.manager, uri=self.resource2_uri,
            properties={
                self.manager._name_prop: self.resource2_name,
                "other": "fake-other-2"
            })
        self.all_names = {self.resource1_name, self.resource2_name}
        self.manager._list_resources = [self.resource1, self.resource2]

        self.timetolive = 1.0  # seconds
        self.cache = _NameUriCache(self.manager, self.timetolive)
        self.created = datetime.now()
Exemple #12
0
    def setup_method(self):
        """
        Setup that is called by pytest before each test method.
        """
        # pylint: disable=attribute-defined-outside-init

        self.session = Session(host='fake-host', userid='fake-user',
                               password='******')
        self.manager = MyManager(self.session)
        self.resource1 = MyResource(
            self.manager,
            uri="/api/fake-uri-1",
            properties={
                self.manager._name_prop: "fake-name-1",
                "other": "fake-other-1",
                "same": "fake-same",
                "int_other": 23,
                "int_same": 42,
            })
        self.resource2 = MyResource(
            self.manager,
            uri="/api/fake-uri-2",
            properties={
                self.manager._name_prop: "fake-name-2",
                "other": "fake-other-2",
                "same": "fake-same",
                "int_other": 24,
                "int_same": 42,
            })
        self.manager._list_resources = [self.resource1, self.resource2]
Exemple #13
0
    def setup_method(self):
        self.session = Session(host='fake-host',
                               userid='fake-user',
                               password='******')
        self.manager = MyManager(self.session)
        self.resource1_uri = "/api/fake-uri-1"
        self.resource1_name = "fake-name-1"
        self.resource1 = MyResource(self.manager,
                                    uri=self.resource1_uri,
                                    properties={
                                        self.manager._name_prop:
                                        self.resource1_name,
                                        "other": "fake-other-1"
                                    })
        self.resource2_uri = "/api/fake-uri-2"
        self.resource2_name = "fake-name-2"
        self.resource2 = MyResource(self.manager,
                                    uri=self.resource2_uri,
                                    properties={
                                        self.manager._name_prop:
                                        self.resource2_name,
                                        "other": "fake-other-2"
                                    })
        self.all_names = {self.resource1_name, self.resource2_name}
        self.manager._list_resources = [self.resource1, self.resource2]

        self.timetolive = 1.0  # seconds
        self.cache = _NameUriCache(self.manager, self.timetolive)
        self.created = datetime.now()
    def test_check_complete_error4(self):
        """Test check_for_completion() with complete job in error (4)."""
        with requests_mock.mock() as m:
            self.mock_server_1(m)
            session = Session('fake-host', 'fake-user', 'fake-pw')
            op_method = 'POST'
            op_uri = '/api/foo'
            job = Job(session, self.job_uri, op_method, op_uri)
            query_job_status_result = {
                'status': 'complete',
                'job-status-code': 500,
                'job-reason-code': 42,
                'job-results': {
                    # Content is not documented for the error case.
                    # Some failures result in an 'message' field.
                    'message': 'bla message',
                },
            }

            m.get(self.job_uri, json=query_job_status_result)
            m.delete(self.job_uri, status_code=204)

            with pytest.raises(HTTPError) as exc_info:
                job_status, op_result = job.check_for_completion()
            exc = exc_info.value

            assert exc.http_status == 500
            assert exc.reason == 42
            assert exc.message == 'bla message'
    def test_check_complete_error2(self):
        """Test check_for_completion() with complete job in error (2)."""
        with requests_mock.mock() as m:
            self.mock_server_1(m)
            session = Session('fake-host', 'fake-user', 'fake-pw')
            op_method = 'POST'
            op_uri = '/api/foo'
            job = Job(session, self.job_uri, op_method, op_uri)
            query_job_status_result = {
                'status': 'complete',
                'job-status-code': 500,
                'job-reason-code': 42,
                'job-results': {},  # it is not guaranteed to have any content
            }

            m.get(self.job_uri, json=query_job_status_result)
            m.delete(self.job_uri, status_code=204)

            with pytest.raises(HTTPError) as exc_info:
                job_status, op_result = job.check_for_completion()
            exc = exc_info.value

            assert exc.http_status == 500
            assert exc.reason == 42
            assert exc.message is None
Exemple #16
0
    def setup_method(self):
        """
        Setup that is called by pytest before each test method.
        """
        # pylint: disable=attribute-defined-outside-init

        self.session = Session(host='fake-host', userid='fake-user',
                               password='******')
def test_session_get_notification_topics():
    """
    This tests the 'Get Notification Topics' operation.
    """
    session = Session('fake-host', 'fake-user', 'fake-id')
    with requests_mock.mock() as m:
        # Because logon is deferred until needed, we perform it
        # explicitly in order to keep mocking in the actual test simple.
        m.post('/api/sessions', json={'api-session': 'fake-session-id'})
        session.logon()
        gnt_uri = "/api/sessions/operations/get-notification-topics"
        gnt_result = {
            "topics": [{
                'topic-name': 'ensadmin.145',
                'topic-type': 'object-notification',
            }, {
                'topic-name': 'ensadmin.145job',
                'topic-type': 'job-notification',
            }, {
                'topic-name': 'ensadmin.145aud',
                'topic-type': 'audit-notification',
            }, {
                'topic-name': 'ensadmin.145sec',
                'topic-type': 'security-notification',
            }]
        }
        m.get(gnt_uri, json=gnt_result)

        result = session.get_notification_topics()

        assert result == gnt_result['topics']

        m.delete('/api/sessions/this-session', status_code=204)

        session.logoff()
Exemple #18
0
def probe_hmcz_and_enlist(
    user: str,
    hostname: str,
    username: str,
    password: str,
    accept_all: bool = False,
    domain: str = None,
    prefix_filter: str = None,
):
    """Extracts all of the VMs from an HMC for Z and enlists them into MAAS.

    :param user: user for the nodes.
    :param hostname: Hostname for Proxmox
    :param username: The username to connect to Proxmox to
    :param password: The password to connect to Proxmox with.
    :param accept_all: If True, commission enlisted nodes.
    :param domain: What domain discovered machines to be apart of.
    :param prefix_filter: only enlist nodes that have the prefix.
    """
    session = Session(hostname, username, password)
    client = Client(session)
    # Each HMC manages one or more CPCs(Central Processor Complex). Iterate
    # over all CPCs to find all partitions to add.
    for cpc in client.cpcs.list():
        if not cpc.dpm_enabled:
            maaslog.warning(
                f"DPM is not enabled on '{cpc.get_property('name')}', "
                "skipping")
            continue
        for partition in cpc.partitions.list():
            if prefix_filter and not partition.name.startswith(prefix_filter):
                continue

            system_id = yield create_node(
                [
                    nic.get_property("mac-address")
                    for nic in partition.nics.list()
                ],
                "s390x",
                "hmcz",
                {
                    "power_address": hostname,
                    "power_user": username,
                    "power_pass": password,
                    "power_partition_name": partition.name,
                },
                domain,
                partition.name,
            )

            # If the system_id is None an error occured when creating the machine.
            # Most likely the error is the node already exists.
            if system_id is None:
                continue

            if accept_all:
                yield commission_node(system_id, user)
def test_session_repr():
    """Test Session.__repr__()."""

    session = Session('fake-host', 'fake-user', 'fake-pw')

    repr_str = repr(session)

    repr_str = repr_str.replace('\n', '\\n')
    # We check just the begin of the string:
    assert re.match(
        r'^{classname}\s+at\s+0x{id:08x}\s+\(\\n.*'.format(
            classname=session.__class__.__name__, id=id(session)), repr_str)
    def setup_method(self):
        """
        Setup that is called by pytest before each test method.
        """
        # pylint: disable=attribute-defined-outside-init

        self.session = Session(host='fake-host')
        self.mgr = MyManager(self.session)
        self.uri = self.mgr._base_uri + '/deadbeef-beef-beef-beef-deadbeefbeef'
        self.name = "fake-name"
        self.uri_prop = 'fake-uri-prop'  # same as in MyManager
        self.name_prop = 'fake-name-prop'  # same as in MyManager
def get_session(faked_session, host, userid, password, ca_certs, verify):
    """
    Return a session object for the HMC.

    Parameters:
      faked_session (zhmcclient_mock.FakedSession or None):
        If this object is a `zhmcclient_mock.FakedSession` object, return that
        object.
        Else, return a new `zhmcclient.Session` object from the other arguments.
    """
    if isinstance(faked_session, FakedSession):
        return faked_session
    else:
        verify_cert = ca_certs if verify else False
        return Session(host, userid, password, verify_cert=verify_cert)
Exemple #22
0
 def setup_method(self):
     self.session = Session(host='fake-host',
                            userid='fake-user',
                            password='******')
     self.manager = MyManager(self.session)
     self.resource_uri = "/api/fake-uri-1"
     self.resource_name = "fake-name-1"
     self.resource = MyResource(self.manager,
                                uri=self.resource_uri,
                                properties={
                                    self.manager._name_prop:
                                    self.resource_name,
                                    "other": "fake-other-1",
                                })
     self.manager._list_resources = [self.resource]
def get_session(faked_session, host, userid, password):
    """
    Return a session object for the HMC.

    Parameters:
      faked_session (zhmcclient_mock.FakedSession or None):
        If this object is a `zhmcclient_mock.FakedSession` object, return that
        object.
        Else, return a new `zhmcclient.Session` object from the `host`,
        `userid`, and `password` arguments.
    """
    if isinstance(faked_session, FakedSession):
        return faked_session
    else:
        return Session(host, userid, password)
    def test_init(self):
        """Test initialization of Job object."""
        session = Session('fake-host', 'fake-user', 'fake-pw')

        # Jobs exist only for POST, but we want to test that the specified HTTP
        # method comes back regardless:
        op_method = 'GET'

        op_uri = '/api/bla'

        job = Job(session, self.job_uri, op_method, op_uri)

        assert job.uri == self.job_uri
        assert job.session == session
        assert job.op_method == op_method
        assert job.op_uri == op_uri
    def test_check_incomplete(self):
        """Test check_for_completion() with incomplete job."""
        with requests_mock.mock() as m:
            self.mock_server_1(m)
            session = Session('fake-host', 'fake-user', 'fake-pw')
            op_method = 'POST'
            op_uri = '/api/foo'
            job = Job(session, self.job_uri, op_method, op_uri)
            query_job_status_result = {
                'status': 'running',
            }
            m.get(self.job_uri, json=query_job_status_result)
            m.delete(self.job_uri, status_code=204)

            job_status, op_result = job.check_for_completion()

            assert job_status == 'running'
            assert op_result is None
def test_job_wait_complete3_timeout():
    """Test wait_for_completion() with timeout."""
    with requests_mock.mock() as m:
        mock_server_1(m)
        session = Session('fake-host', 'fake-user', 'fake-pw')
        op_method = 'POST'
        op_uri = '/api/foo'
        job = Job(session, JOB_URI, op_method, op_uri)
        m.get(JOB_URI, [
            {
                'text': result_running_callback
            },
            {
                'text': result_running_callback
            },
            {
                'text': result_complete_callback
            },
        ])
        m.delete(JOB_URI, status_code=204)

        # Here we provoke a timeout, by setting the timeout to less than
        # the time it would take to return the completed job status.
        # The time it would take is the sum of the following:
        # - 2 * 1 s (1 s is the sleep time in Job.wait_for_completion(),
        #   and this happens before each repeated status retrieval)
        # - 3 * 1 s (1 s is the sleep time in result_*_callback() in this
        #   module, and this happens in each mocked status retrieval)
        # Because status completion is given priority over achieving the
        # timeout duration, the timeout value needed to provoke the
        # timeout exception needs to be shorter by the last status
        # retrieval (the one that completes the job), so 3 s is the
        # boundary for the timeout value.
        operation_timeout = 2.9
        try:
            start_time = time.time()
            job.wait_for_completion(operation_timeout=operation_timeout)
            duration = time.time() - start_time
            raise AssertionError(
                "No OperationTimeout raised. Actual duration: %s s, "
                "timeout: %s s" % (duration, operation_timeout))
        except OperationTimeout as exc:
            msg = exc.args[0]
            assert msg.startswith("Waiting for completion of job")
Exemple #27
0
 def _get_partition(self, context: dict):
     session = Session(
         context["power_address"],
         context["power_user"],
         context["power_pass"],
     )
     partition_name = context["power_partition_name"]
     client = Client(session)
     # Each HMC manages one or more CPCs(Central Processor Complex). To find
     # a partition MAAS must iterate over all CPCs.
     for cpc in client.cpcs.list():
         if not cpc.dpm_enabled:
             maaslog.warning(
                 f"DPM is not enabled on '{cpc.get_property('name')}', "
                 "skipping")
             continue
         with contextlib.suppress(NotFound):
             return cpc.partitions.find(name=partition_name)
     raise PowerActionError(f"Unable to find '{partition_name}' on HMC!")
def test_job_check_complete_success_noresult():
    """Test check_for_completion() with successful complete job without
    result."""
    with requests_mock.mock() as m:
        mock_server_1(m)
        session = Session('fake-host', 'fake-user', 'fake-pw')
        op_method = 'POST'
        op_uri = '/api/foo'
        job = Job(session, JOB_URI, op_method, op_uri)
        query_job_status_result = {
            'status': 'complete',
            'job-status-code': 200,
            # 'job-reason-code' omitted because HTTP status good
            # 'job-results' is optional and is omitted
        }
        m.get(JOB_URI, json=query_job_status_result)
        m.delete(JOB_URI, status_code=204)

        job_status, op_result = job.check_for_completion()

        assert job_status == 'complete'
        assert op_result is None
Exemple #29
0
 def setup_method(self):
     self.session = Session(host='fake-host',
                            userid='fake-user',
                            password='******')
     self.manager = MyManager(self.session)
     self.resource1 = MyResource(self.manager,
                                 uri="/api/fake-uri-1",
                                 properties={
                                     self.manager._name_prop: "fake-name-1",
                                     "other": "fake-other-1",
                                     "same": "fake-same",
                                     "int_other": 23,
                                     "int_same": 42,
                                 })
     self.resource2 = MyResource(self.manager,
                                 uri="/api/fake-uri-2",
                                 properties={
                                     self.manager._name_prop: "fake-name-2",
                                     "other": "fake-other-2",
                                     "same": "fake-same",
                                     "int_other": 24,
                                     "int_same": 42,
                                 })
     self.manager._list_resources = [self.resource1, self.resource2]
class TestVirtualSwitch(object):
    """All tests for VirtualSwitch and VirtualSwitchManager classes."""

    def setup_method(self):
        self.session = Session('vswitch-dpm-host', 'vswitch-user',
                               'vswitch-pwd')
        self.client = Client(self.session)
        with requests_mock.mock() as m:
            # Because logon is deferred until needed, we perform it
            # explicitly in order to keep mocking in the actual test simple.
            m.post('/api/sessions', json={'api-session': 'vswitch-session-id'})
            self.session.logon()

        self.cpc_mgr = self.client.cpcs
        with requests_mock.mock() as m:
            result = {
                'cpcs': [
                    {
                        'object-uri': '/api/cpcs/vswitch-cpc-id-1',
                        'name': 'CPC',
                        'status': 'service-required',
                    }
                ]
            }
            m.get('/api/cpcs', json=result)

            cpcs = self.cpc_mgr.list()
            self.cpc = cpcs[0]

    def teardown_method(self):
        with requests_mock.mock() as m:
            m.delete('/api/sessions/this-session', status_code=204)
            self.session.logoff()

    def test_init(self):
        """Test __init__() on VirtualSwitchManager instance in CPC."""
        vswitch_mgr = self.cpc.virtual_switches
        assert vswitch_mgr.cpc == self.cpc

    def test_list_short_ok(self):
        """
        Test successful list() with short set of properties
        on VirtualSwitchManager instance in CPC.
        """
        vswitch_mgr = self.cpc.virtual_switches
        with requests_mock.mock() as m:
            result = {
                'virtual-switches': [
                    {
                        'name': 'VSWITCH1',
                        'object-uri': '/api/virtual-switches/fake-vswitch-id1',
                        'type': 'osd'
                    },
                    {
                        'name': 'VSWITCH2',
                        'object-uri': '/api/virtual-switches/fake-vswitch-id2',
                        'type': 'hpersockets'
                    }
                ]
            }

            m.get('/api/cpcs/vswitch-cpc-id-1/virtual-switches', json=result)

            vswitches = vswitch_mgr.list(full_properties=False)

            assert len(vswitches) == len(result['virtual-switches'])
            for idx, vswitch in enumerate(vswitches):
                assert vswitch.properties == \
                    result['virtual-switches'][idx]
                assert vswitch.uri == \
                    result['virtual-switches'][idx]['object-uri']
                assert not vswitch.full_properties
                assert vswitch.manager == vswitch_mgr

    def test_list_full_ok(self):
        """
        Test successful list() with full set of properties on
        VirtualSwitchManager instance in CPC.
        """
        vswitch_mgr = self.cpc.virtual_switches
        with requests_mock.mock() as m:
            result = {
                'virtual-switches': [
                    {
                        'name': 'VSWITCH1',
                        'object-uri': '/api/virtual-switches/fake-vswitch-id1',
                        'type': 'osd'
                    },
                    {
                        'name': 'VSWITCH2',
                        'object-uri': '/api/virtual-switches/fake-vswitch-id2',
                        'type': 'hipersockets'
                    }
                ]
            }

            m.get('/api/cpcs/vswitch-cpc-id-1/virtual-switches', json=result)

            mock_result_virtual_switch1 = {
                'name': 'VSWITCH1',
                'object-uri': '/api/virtual-switches/fake-vswitch-id1',
                'type': 'osd',
                'class': 'virtual-switch',
                'description': 'Test VirtualSwitch',
                'more_properties': 'bliblablub'
            }
            m.get('/api/virtual-switches/fake-vswitch-id1',
                  json=mock_result_virtual_switch1)
            mock_result_virtual_switch2 = {
                'name': 'VSWITCH2',
                'object-uri': '/api/virtual-switches/fake-vswitch-id2',
                'type': 'hipersockets',
                'class': 'virtual-switch',
                'description': 'Test VirtualSwitch',
                'more_properties': 'bliblablub'
            }
            m.get('/api/virtual-switches/fake-vswitch-id2',
                  json=mock_result_virtual_switch2)

            vswitches = vswitch_mgr.list(full_properties=True)

            assert len(vswitches) == len(result['virtual-switches'])
            for idx, vswitch in enumerate(vswitches):
                assert vswitch.properties['name'] == \
                    result['virtual-switches'][idx]['name']
                assert vswitch.uri == \
                    result['virtual-switches'][idx]['object-uri']
                assert vswitch.full_properties
                assert vswitch.manager == vswitch_mgr

    def test_update_properties(self):
        """
        This tests the 'Update VirtualSwitch Properties' operation.
        """
        vswitch_mgr = self.cpc.virtual_switches
        with requests_mock.mock() as m:
            result = {
                'virtual-switches': [
                    {
                        'name': 'VSWITCH1',
                        'object-uri': '/api/virtual-switches/fake-vswitch-id1',
                        'type': 'osd'
                    },
                    {
                        'name': 'VSWITCH2',
                        'object-uri': '/api/virtual-switches/fake-vswitch-id2',
                        'type': 'hpersockets'
                    }
                ]
            }
            m.get('/api/cpcs/vswitch-cpc-id-1/virtual-switches', json=result)

            vswitches = vswitch_mgr.list(full_properties=False)
            vswitch = vswitches[0]
            m.post("/api/virtual-switches/fake-vswitch-id1", status_code=204)
            vswitch.update_properties(properties={})

    def test_get_connected_nics(self):
        """
        This tests the `get_connected_nics()` method.
        """
        vswitch_mgr = self.cpc.virtual_switches
        with requests_mock.mock() as m:
            result = {
                'virtual-switches': [
                    {
                        'name': 'VSWITCH1',
                        'object-uri': '/api/virtual-switches/fake-vswitch-id1',
                        'type': 'osd'
                    },
                    {
                        'name': 'VSWITCH2',
                        'object-uri': '/api/virtual-switches/fake-vswitch-id2',
                        'type': 'hpersockets'
                    }
                ]
            }
            m.get('/api/cpcs/vswitch-cpc-id-1/virtual-switches', json=result)

            vswitches = vswitch_mgr.list(full_properties=False)
            vswitch = vswitches[0]
            result = {
                'connected-vnic-uris': [
                    '/api/partitions/fake-part-id1/nics/fake-nic-id1',
                    '/api/partitions/fake-part-id1/nics/fake-nic-id2',
                    '/api/partitions/fake-part-id1/nics/fake-nic-id3'
                ]
            }

            m.get(
                "/api/virtual-switches/fake-vswitch-id1/"
                "operations/get-connected-vnics",
                json=result)

            nics = vswitch.get_connected_nics()

            assert isinstance(nics, list)
            for i, nic in enumerate(nics):
                assert isinstance(nic, Nic)
                nic_uri = result['connected-vnic-uris'][i]
                assert nic.uri == nic_uri
                assert nic.properties['element-uri'] == nic_uri
                m = re.match(r"^/api/partitions/([^/]+)/nics/([^/]+)/?$",
                             nic_uri)
                nic_id = m.group(2)
                assert nic.properties['element-id'] == nic_id