1+ import unittest
2+ from unittest.mock import patch, MagicMock, mock_open, call
3+
4+ # Import the main function from the script we want to test
5+ from Keithley_6517B.High_Resistance.Backends.IV_K6517B_Simple_Backend_v10 import main as iv_simple_main
6+
7+ class TestIVK6517BSimpleBackend(unittest.TestCase):
8+ @patch('time.sleep', MagicMock())
9+ @patch('builtins.input', side_effect=['-10', '10', '5', '0.1', 'test_iv_simple.csv'])
10+ @patch('pymeasure.instruments.keithley.Keithley6517B')
11+ @patch('builtins.open', new_callable=mock_open)
12+ @patch('matplotlib.pyplot.show')
13+ def test_full_run(self, mock_show, mock_file, mock_keithley_class, mock_input):
14+ """
15+ Tests a complete, successful run of the IV_K6517B_Simple_Backend script.
16+ """
17+ # --- Setup Mocks for Keithley6517B ---
18+ mock_instrument = MagicMock()
19+ mock_keithley_class.return_value = mock_instrument
20+ # Set a mock ID for the connection message
21+ mock_instrument.id = "Mocked Keithley 6517B"
22+ # Simulate resistance measurement
23+ mock_instrument.resistance = 1.23e9
24+
25+ # --- Run the main function and catch exceptions ---
26+ try:
27+ iv_simple_main()
28+ except Exception as e:
29+ # The script might exit or raise an error after plotting, which is fine for this test
30+ if "no display name" not in str(e): # Ignore matplotlib display errors in CI
31+ pass
32+
33+ # --- Assertions ---
34+ # 1. Was the instrument initialized correctly?
35+ mock_keithley_class.assert_called_once_with(
36+ "GPIB1::27::INSTR", adapter_args={"py_library": "@sim"})
37+
38+ # 2. Was the zero-check and correction sequence performed?
39+ mock_instrument.reset.assert_called_once()
40+ mock_instrument.measure_resistance.assert_called_once()
41+ mock_instrument.write.assert_any_call(':SYSTem:ZCHeck ON')
42+ mock_instrument.write.assert_any_call(':SYSTem:ZCORrect:ACQuire')
43+ mock_instrument.write.assert_any_call(':SYSTem:ZCHeck OFF')
44+ mock_instrument.write.assert_any_call(':SYSTem:ZCORrect ON')
45+
46+ # 3. Was the source configured and enabled?
47+ self.assertEqual(mock_instrument.current_nplc, 1)
48+ mock_instrument.enable_source.assert_called_once()
49+
50+ # 4. Was the voltage sweep performed correctly?
51+ # Based on inputs: start=-10, stop=10, steps=5 -> [-10., -5., 0., 5., 10.]
52+ self.assertEqual(mock_instrument.source_voltage_set.call_count, 5)
53+ mock_instrument.source_voltage_set.assert_any_call(-10.0)
54+ mock_instrument.source_voltage_set.assert_any_call(10.0)
55+
56+ # 5. Was the data file written to?
57+ mock_file.assert_called_with('test_iv_simple.csv', 'w', newline='')
58+ # Header (2) + Data (5)
59+ self.assertTrue(mock_file().write.call_count >= 7)
60+
61+ # 6. Was the instrument shut down safely?
62+ mock_instrument.shutdown.assert_called_once()
63+
64+ # 7. Was the plot shown?
65+ mock_show.assert_called_once()
0 commit comments