Skip to content

Commit

Permalink
unit testing
Browse files Browse the repository at this point in the history
Work to add unit testing to the lib.
Makes changes to the connection and HTTP socket libs
to make sure we can use testing fixtures.

partial vmware#42
  • Loading branch information
hartsock committed Jul 17, 2014
1 parent 75f11ce commit 52a032b
Show file tree
Hide file tree
Showing 6 changed files with 210 additions and 8 deletions.
12 changes: 5 additions & 7 deletions pyVim/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@
import threading
import thread
import types
import httplib
import socket
import six
import time
import itertools
import re
Expand All @@ -41,7 +41,7 @@
except ImportError:
from elementtree.ElementTree import ElementTree
from xml.parsers.expat import ExpatError
import urllib
from six.moves.urllib.request import urlopen


"""
Expand Down Expand Up @@ -312,8 +312,6 @@ def __Login(host, port, user, pwd, service, adapter, version, path,
content = si.RetrieveContent()
except vmodl.MethodFault:
raise
except Exception, e:
raise vim.fault.HostConnectFault(msg=str(e))

# Get a ticket if we're connecting to localhost and password is not specified
if host == 'localhost' and not pwd:
Expand Down Expand Up @@ -429,7 +427,7 @@ def __GetServiceVersionDescription(protocol, server, port, path):

url = "%s://%s:%s/%s/vimServiceVersions.xml" % (protocol, server, port, path)
try:
with closing(urllib.urlopen(url)) as sock:
with closing(urlopen(url)) as sock:
if sock.getcode() == 200:
tree.parse(sock)
return tree
Expand All @@ -438,7 +436,7 @@ def __GetServiceVersionDescription(protocol, server, port, path):

url = "%s://%s:%s/%s/vimService.wsdl" % (protocol, server, port, path)
try:
with closing(urllib.urlopen(url)) as sock:
with closing(urlopen(url)) as sock:
if sock.getcode() == 200:
tree.parse(sock)
return tree
Expand Down Expand Up @@ -622,5 +620,5 @@ def OpenPathWithStub(path, stub):
request = urllib2.Request(url)
if stub.cookie:
request.add_header('Cookie', stub.cookie)
return urllib2.urlopen(request)
return urlopen(request)

3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,6 @@ def read(fname):
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: System :: Distributed Computing"
],
zip_safe=True
zip_safe=True,
test_suite="tests"
)
3 changes: 3 additions & 0 deletions test_requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
mock
unittest
vcrpy
31 changes: 31 additions & 0 deletions tests/ConnectionTests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# VMware vSphere Python SDK
# Copyright (c) 2008-2014 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.

from unittest import TestCase
import vcr

from pyVim import connect


class SimpleSmartConnectTest(TestCase):

def test_smart_connect_okay(self):
#with vcr.use_cassette('fixtures/smart-connect.yaml') as cass:
si = connect.SmartConnect(host='172.16.16.131',
user='root',
pwd='vmware',
port=443)
session_id = si.content.sessionManager.currentSession.key
self.assertIsNotNone(session_id)
101 changes: 101 additions & 0 deletions tests/SoapAdapterTests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# VMware vSphere Python SDK
# Copyright (c) 2008-2014 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.

from unittest import TestCase
from mock import Mock

import requests
import httpretty

from pyVmomi import vim
from pyVmomi import vmodl
from pyVmomi import SoapAdapter
from unittest import TestCase
from mock import Mock

import socket
import urllib
import urlparse
import httpretty

from tests import BaseTest
from tests import VIM_SERVICE_VERSIONS

from pyVim import connect
from pyVmomi import vim
from pyVmomi import vmodl
from pyVmomi import SoapAdapter

try:
from xml.etree.ElementTree import ElementTree
except ImportError:
from elementtree.ElementTree import ElementTree

class closing(object):
"""
Helper class for using closable objects in a 'with' statement,
similar to the one provided by contextlib.
"""
def __init__(self, obj):
self.obj = obj
def __enter__(self):
return self.obj
def __exit__(self, *exc_info):
self.obj.close()


LICENSE_QUERY_RESPONSE_BODY = (
'<?xml version=\'1.0\' encoding=\'UTF-8\'?>'
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" '
'xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" '
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" '
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
'<soapenv:Body>'
'<QueryLicenseEntriesResponse xmlns="urn:license">'
'<returnval>'
'<licenseId>1</licenseId>'
'<licenseKey>AAAAA-BBBBB-CCCCC-DDDDD-EEEEE</licenseKey>'
'<editionName>vCenter Server 5 Standard</editionName>'
'<costUnit>server</costUnit>'
'<costUnitNum>1</costUnitNum>'
'<capacity>64</capacity>'
'<expirationTimestamp>1420070400000</expirationTimestamp>'
'</returnval>'
'</QueryLicenseEntriesResponse>'
'</soapenv:Body>'
'</soapenv:Envelope>')


class SoapAdapterTests(TestCase):

def test_malformed_exception(self):
mocked_obj = Mock()
mocked_obj.version = vim.version.version3
deserializer = SoapAdapter.SoapResponseDeserializer(mocked_obj)

tree = ElementTree()
version_url = 'https://{0}:443/sdk/vimServiceVersions.xml'.format(
self.host)
httpretty.register_uri(httpretty.GET,
version_url,
body='<?xml version=\'1.0\' encoding=\'UTF-8\'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><soapenv:Fault><faultcode>ServerFaultCode</faultcode><faultstring/><detail><LicenseUsageFaultFault xsi:type="LicenseUsageFault"><reason>dataTampered</reason></LicenseUsageFaultFault></detail></soapenv:Fault></soapenv:Body></soapenv:Envelope>',
code=200)
with closing(urllib.urlopen(version_url)) as sock:
if sock.getcode() == 200:
tree.parse(sock)
return tree
obj = SoapAdapter.SoapResponseDeserializer(self).Deserialize(LICENSE_QUERY_RESPONSE_BODY, info.result)
result = deserializer.Deserialize(LICENSE_QUERY_RESPONSE_BODY, )
print result
68 changes: 68 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# VMware vSphere Python SDK
# Copyright (c) 2008-2014 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.

from unittest import TestCase
from mock import Mock

import requests
import httpretty

from pyVmomi import vim
from pyVmomi import vmodl
from pyVmomi import SoapAdapter

# 'https://test.com:443//sdk/vimServiceVersions.xml'
VIM_SERVICE_VERSIONS = """<!--
Copyright 2008-2012 VMware, Inc. All rights reserved.
-->
<namespaces version="1.0">
<namespace>
<name>urn:vim25</name>
<version>5.5</version>
<priorVersions>
<version>5.1</version>
<version>5.0</version>
<version>4.1</version>
<version>4.0</version>
<version>2.5u2</version>
<version>2.5</version>
</priorVersions>
</namespace>
<namespace>
<name>urn:vim2</name>
<version>2.0</version>
</namespace>
</namespaces>"""

class BaseTest(TestCase):

@property
def host(self):
return self.test_host

def setUp(self):
self.test_host = '172.16.16.131'
httpretty.enable()
version_url = 'https://{0}//sdk/vimServiceVersions.xml'.format(
self.host)
httpretty.register_uri(httpretty.GET,
version_url,
body=VIM_SERVICE_VERSIONS,
code=200)

def tearDown(self):
httpretty.disable()
httpretty.reset()

0 comments on commit 52a032b

Please sign in to comment.