From 9ef187014875577fd62ca2b5454355c34cd22708 Mon Sep 17 00:00:00 2001
From: ZhiQiang Fan <zhiqiang.fan@huawei.com>
Date: Mon, 24 Mar 2014 15:29:01 +0800
Subject: [PATCH] Avoid AttributeError in servers.Server.__repr__
servers.Server represents various object now, and some of them may
don't have attribute 'name', for example, the interface_list() result
object. It will cause AttributeError when we try to format string with
such object, so I add a check for the 'name' attribute in __repr__
method, it will use 'unknown-name' instead when 'name' is not found.
Change-Id: If4757d5d73721774543d58a4cc875710a6013f34
Closes-Bug: #1280453
---
novaclient/tests/v1_1/test_servers.py | 26 ++++++++++++++++++++++++++
novaclient/v1_1/servers.py | 2 +-
2 files changed, 27 insertions(+), 1 deletion(-)
diff --git a/novaclient/tests/v1_1/test_servers.py b/novaclient/tests/v1_1/test_servers.py
index a48204c..b70964a 100644
--- a/novaclient/tests/v1_1/test_servers.py
+++ b/novaclient/tests/v1_1/test_servers.py
@@ -582,6 +582,32 @@ class ServersTest(utils.TestCase):
s.interface_list()
cs.assert_called('GET', '/servers/1234/os-interface')
+ def test_interface_list_result_string_representable(self):
+ """Test for bugs.launchpad.net/python-novaclient/+bug/1280453."""
+ # According to https://github.com/openstack/nova/blob/master/
+ # nova/api/openstack/compute/contrib/attach_interfaces.py#L33,
+ # the attach_interface extension get method will return a json
+ # object partly like this:
+ interface_list = [{
+ 'net_id': 'd7745cf5-63f9-4883-b0ae-983f061e4f23',
+ 'port_id': 'f35079da-36d5-4513-8ec1-0298d703f70e',
+ 'mac_addr': 'fa:16:3e:4c:37:c8',
+ 'port_state': 'ACTIVE',
+ 'fixed_ips': [{
+ 'subnet_id': 'f1ad93ad-2967-46ba-b403-e8cbbe65f7fa',
+ 'ip_address': '10.2.0.96'
+ }]
+ }]
+ # If server is not string representable, it will raise an exception,
+ # because attribute named 'name' cannot be found.
+ # Parameter 'loaded' must be True or it will try to get attribute
+ # 'id' then fails (lazy load detail), this is exactly same as
+ # novaclient.base.Manager._list()
+ s = servers.Server(servers.ServerManager, interface_list[0],
+ loaded=True)
+ # Trigger the __repr__ magic method
+ self.assertEqual('<Server: unknown-name>', '%r' % s)
+
def test_interface_attach(self):
s = cs.servers.get(1234)
s.interface_attach(None, None, None)
diff --git a/novaclient/v1_1/servers.py b/novaclient/v1_1/servers.py
index cf284d9..d4ac6a7 100644
--- a/novaclient/v1_1/servers.py
+++ b/novaclient/v1_1/servers.py
@@ -36,7 +36,7 @@ class Server(base.Resource):
HUMAN_ID = True
def __repr__(self):
- return "<Server: %s>" % self.name
+ return '<Server: %s>' % getattr(self, 'name', 'unknown-name')
def delete(self):
"""