| 1 | import unittest |
| 2 | import libvirt |
| 3 | import tempfile |
| 4 | import contextlib |
| 5 | import os |
| 6 | |
| 7 | |
| 8 | class TestLibvirtConn(unittest.TestCase): |
| 9 | def setUp(self): |
| 10 | self.conn = libvirt.open("test:///default") |
| 11 | |
| 12 | def tearDown(self): |
| 13 | self.conn = None |
| 14 | |
| 15 | def testConnDomainList(self): |
| 16 | doms = self.conn.listAllDomains() |
| 17 | self.assertEqual(len(doms), 1) |
| 18 | self.assertEqual(type(doms[0]), libvirt.virDomain) |
| 19 | self.assertEqual(doms[0].name(), "test") |
| 20 | |
| 21 | class TestLibvirtConnAuth(unittest.TestCase): |
| 22 | connXML = """ |
| 23 | <node> |
| 24 | <auth> |
| 25 | <user password="2147483647">marin</user> |
| 26 | <user password="87539319">srinivasa</user> |
| 27 | </auth> |
| 28 | </node>""" |
| 29 | def setUp(self): |
| 30 | def noop(msg, opaque): |
| 31 | pass |
| 32 | libvirt.registerErrorHandler(noop, None) |
| 33 | |
| 34 | @contextlib.contextmanager |
| 35 | def tempxmlfile(content): |
| 36 | try: |
| 37 | fp = tempfile.NamedTemporaryFile(delete=False, |
| 38 | prefix="libvirt-python-test", |
| 39 | suffix=".xml") |
| 40 | fname = fp.name |
| 41 | fp.write(content.encode("utf8")) |
| 42 | fp.close() |
| 43 | yield fname |
| 44 | finally: |
| 45 | os.unlink(fname) |
| 46 | |
| 47 | def authHelper(self, username, password): |
| 48 | with TestLibvirtConnAuth.tempxmlfile(self.connXML) as fname: |
| 49 | magic = 142857 |
| 50 | def authCB(creds, opaque): |
| 51 | if opaque != magic: |
| 52 | return -1 |
| 53 | |
| 54 | for cred in creds: |
| 55 | if (cred[0] == libvirt.VIR_CRED_AUTHNAME and |
| 56 | username is not None): |
| 57 | cred[4] = username |
| 58 | return 0 |
| 59 | elif (cred[0] == libvirt.VIR_CRED_PASSPHRASE and |
| 60 | password is not None): |
| 61 | cred[4] = password |
| 62 | return 0 |
| 63 | return -1 |
| 64 | return 0 |
| 65 | |
| 66 | auth = [[libvirt.VIR_CRED_AUTHNAME, |
| 67 | libvirt.VIR_CRED_ECHOPROMPT, |
| 68 | libvirt.VIR_CRED_REALM, |
| 69 | libvirt.VIR_CRED_PASSPHRASE, |
| 70 | libvirt.VIR_CRED_NOECHOPROMPT, |
| 71 | libvirt.VIR_CRED_EXTERNAL], |
| 72 | authCB, magic] |
| 73 | |
| 74 | return libvirt.openAuth("test://" + fname, |
| 75 | auth, 0) |
| 76 | |
| 77 | def testOpenAuthGood(self): |
| 78 | conn = self.authHelper("srinivasa", "87539319") |
| 79 | |
| 80 | def testOpenAuthBad(self): |
| 81 | try: |
| 82 | conn = self.authHelper("srinivasa", "2147483647") |
| 83 | raise Exception("Unexpected open success") |
| 84 | except libvirt.libvirtError as ex: |
| 85 | pass |
| 86 | |
| 87 | def testOpenAuthNone(self): |
| 88 | try: |
| 89 | conn = self.authHelper(None, None) |
| 90 | raise Exception("Unexpected open success") |
| 91 | except libvirt.libvirtError as ex: |
| 92 | pass |