@@ -17,6 +17,13 @@ def mock_libvirt_exception(self, *args, **kwargs):
1717
1818 raise libvirtError ('Something went wrong!' )
1919
20+ def mock_kvm_exception (self , * args , ** kwargs ):
21+ """
22+ Mock raising a VmException
23+ """
24+
25+ raise VmException ('Something went wrong!' )
26+
2027 class TestPylibKvmUnderTest (Hypervisor ):
2128 """
2229 Inherited class to mock the init function
@@ -77,6 +84,42 @@ def test_kvm_context_manager(
7784 # Hypervisor object upon contextmanager enter
7885 assert conn is not None
7986
87+ @patch ('stack.kvm.Hypervisor.connect' , autospec = True )
88+ @patch ('stack.kvm.Hypervisor.close' , autospec = True )
89+ def test_kvm_context_manager_exception_open (
90+ self ,
91+ mock_kvm_close ,
92+ mock_kvm_connect ,
93+ ):
94+ """
95+ Test when entering the context manager that if the an exception
96+ is raised it will be output
97+ """
98+
99+ expect_exception = 'Something went wrong!'
100+ mock_kvm_connect .side_effect = self .mock_kvm_exception
101+ with pytest .raises (VmException , match = expect_exception ), Hypervisor ('hypervisor-foo' ) as conn :
102+ mock_kvm_connect .assert_called_once ()
103+ mock_kvm_close .assert_called_once ()
104+
105+ @patch ('stack.kvm.Hypervisor.connect' , autospec = True )
106+ @patch ('stack.kvm.Hypervisor.close' , autospec = True )
107+ def test_kvm_context_manager_exception_close (
108+ self ,
109+ mock_kvm_close ,
110+ mock_kvm_connect ,
111+ ):
112+ """
113+ Test when entering the context manager that if the an exception
114+ is raised it will be output
115+ """
116+
117+ expect_exception = 'Something went wrong!'
118+ mock_kvm_close .side_effect = self .mock_kvm_exception
119+ with pytest .raises (VmException , match = expect_exception ), Hypervisor ('hypervisor-foo' ) as conn :
120+ mock_kvm_connect .assert_called_once ()
121+ mock_kvm_close .assert_called_once ()
122+
80123 @patch ('libvirt.open' , autospec = True )
81124 def test_kvm_connect (self , mock_libvirt_open ):
82125 """
@@ -135,6 +178,11 @@ def test_kvm_close_exception(self):
135178 mock_libvirt .close .assert_called_once ()
136179
137180 def test_kvm_close_no_conn (self ):
181+ """
182+ Test the close method catches the case
183+ when a hypervisor connection is no longer available
184+ """
185+
138186 mock_hypervisor = self .TestPylibKvmUnderTest ()
139187 mock_hypervisor .kvm = None
140188 expect_exception = 'Cannot find hypervisor connection to hypervisor-foo'
0 commit comments