|
1 | 1 | import unittest |
2 | 2 | import sys |
3 | 3 | import os |
4 | | -import types |
5 | | -from unittest.mock import MagicMock, patch, call |
| 4 | +from unittest.mock import MagicMock, patch, mock_open |
6 | 5 |
|
7 | 6 | # ------------------------------------------------------------------------- |
8 | | -# 1. SETUP & GLOBAL MOCKS |
9 | | -# We mock the GUI libraries so they don't interfere with the backend logic. |
| 7 | +# 1. GLOBAL MOCKS |
10 | 8 | # ------------------------------------------------------------------------- |
11 | 9 | sys.modules['tkinter'] = MagicMock() |
12 | 10 | sys.modules['tkinter.ttk'] = MagicMock() |
|
18 | 16 | class TestDeepSimulation(unittest.TestCase): |
19 | 17 |
|
20 | 18 | def setUp(self): |
21 | | - # Add project root to path so we can import your scripts |
22 | 19 | self.root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) |
23 | 20 | if self.root_dir not in sys.path: |
24 | 21 | sys.path.insert(0, self.root_dir) |
25 | 22 |
|
26 | 23 | # ========================================================================= |
27 | | - # TEST 1: KEITHLEY 2400 I-V SWEEP LOGIC |
28 | | - # Purpose: Verify the exact sequence of current sourcing and voltage measuring. |
| 24 | + # TEST 1: KEITHLEY 2400 (PASSED previously, kept same) |
29 | 25 | # ========================================================================= |
30 | 26 | def test_keithley2400_iv_protocol(self): |
31 | 27 | print("\n[SIMULATION] Testing Keithley 2400 I-V Protocol...") |
32 | | - |
33 | | - # A. Mock the PyMeasure Keithley object |
34 | 28 | with patch('pymeasure.instruments.keithley.Keithley2400') as MockK2400: |
35 | | - |
36 | | - # Create the 'Spy' instrument |
37 | 29 | spy_inst = MockK2400.return_value |
38 | | - # Simulate a voltage reading of 1.23 Volts whenever asked |
39 | 30 | spy_inst.voltage = 1.23 |
40 | | - |
41 | | - # B. Mock User Inputs (Current Limit=100uA, Step=10uA, File='test') |
42 | 31 | fake_inputs = ['100', '10', 'test_output'] |
43 | 32 |
|
44 | | - # C. Mock File Saving (Prevent creating real .txt files) |
45 | 33 | with patch('builtins.input', side_effect=fake_inputs), \ |
46 | 34 | patch('pandas.DataFrame.to_csv') as mock_save: |
47 | 35 |
|
48 | | - # D. Run the Backend Script |
49 | 36 | module_name = "Keithley_2400.Backends.IV_K2400_Loop_Backend_v10" |
50 | 37 | if module_name in sys.modules: del sys.modules[module_name] |
51 | 38 | try: |
52 | 39 | __import__(module_name) |
53 | | - except Exception as e: |
54 | | - print(f" [Note] Script finished with: {e} (Expected if script exits)") |
| 40 | + except Exception: |
| 41 | + pass |
55 | 42 |
|
56 | | - # ============================================================= |
57 | | - # THE "HARD" TESTS (Behavior Verification) |
58 | | - # ============================================================= |
59 | | - |
60 | | - # 1. Did we turn the output ON? |
61 | 43 | spy_inst.enable_source.assert_called() |
62 | 44 | print(" -> Verified: Source Output Enabled") |
63 | | - |
64 | | - # 2. Did we ramp current? |
65 | | - self.assertTrue(spy_inst.ramp_to_current.called, "Failed to ramp current") |
| 45 | + self.assertTrue(spy_inst.ramp_to_current.called) |
66 | 46 | print(" -> Verified: Current Ramping Active") |
67 | | - |
68 | | - # 3. Did we turn it OFF safely at the end? |
69 | 47 | spy_inst.shutdown.assert_called() |
70 | 48 | print(" -> Verified: Safety Shutdown Triggered") |
71 | 49 |
|
72 | 50 | # ========================================================================= |
73 | | - # TEST 2: LAKESHORE 350 TEMPERATURE CONTROL |
74 | | - # Purpose: Verify it reads temperature and sets heater ranges via PyVISA. |
| 51 | + # TEST 2: LAKESHORE 350 (FIXED with Circuit Breaker) |
75 | 52 | # ========================================================================= |
76 | 53 | def test_lakeshore_visa_communication(self): |
77 | 54 | print("\n[SIMULATION] Testing Lakeshore 350 SCPI Commands...") |
78 | 55 |
|
79 | | - # A. Mock PyVISA Resource Manager |
80 | 56 | with patch('pyvisa.ResourceManager') as MockRM: |
81 | 57 | mock_rm_instance = MockRM.return_value |
82 | 58 | spy_instr = MagicMock() |
83 | 59 | mock_rm_instance.open_resource.return_value = spy_instr |
84 | 60 |
|
85 | | - # Simulate the Instrument responding to "*IDN?" |
86 | | - spy_instr.query.return_value = "LSCI,MODEL350,123456,1.0" |
87 | | - |
88 | | - # B. Run the Lakeshore Module |
89 | | - module_name = "Lakeshore_350_340.Backends.T_Control_L350_Simple_Backend_v10" |
90 | | - |
91 | | - # --- FIX IS HERE: Valid inputs (Start < End < Cutoff) --- |
92 | | - # Inputs: Start=10, End=300, Rate=10, Safety=350 |
93 | | - fake_inputs = ['10', '300', '10', '350'] |
| 61 | + # 1. Mock Instrument Responses |
| 62 | + # We provide a sequence of responses: IDN, then Temperature readings |
| 63 | + spy_instr.query.side_effect = [ |
| 64 | + "LSCI,MODEL350,123456,1.0", # *IDN? response |
| 65 | + "10.0", # Initial Temp |
| 66 | + "10.0", # Loop 1 Temp |
| 67 | + "10.1", # Loop 2 Temp |
| 68 | + "10.1", # Loop 3 Temp |
| 69 | + "10.1", # Loop 4 Temp |
| 70 | + "10.1", # Loop 5 Temp |
| 71 | + "300.0" # Ramp Target (if it gets there) |
| 72 | + ] |
| 73 | + |
| 74 | + # 2. Mock Inputs (Start=10, End=300, Rate=10, Cutoff=350) |
| 75 | + fake_inputs = ['10', '300', '10', '350'] |
94 | 76 |
|
| 77 | + # 3. Configure File Dialog Mock to return a valid string (Not a Mock Object) |
| 78 | + sys.modules['tkinter'].filedialog.asksaveasfilename.return_value = "dummy_log.csv" |
| 79 | + |
| 80 | + # 4. THE TRICK: Mock time.sleep to break the infinite loop |
| 81 | + # After 3 calls, it raises an exception to exit the script gracefully |
| 82 | + mock_sleep = MagicMock(side_effect=[None, None, Exception("Force Test Exit")]) |
| 83 | + |
| 84 | + # 5. Mock open() so no CSV is actually created |
95 | 85 | with patch('builtins.input', side_effect=fake_inputs), \ |
96 | | - patch('pandas.DataFrame.to_csv'): |
| 86 | + patch('builtins.open', mock_open()), \ |
| 87 | + patch('time.sleep', mock_sleep): |
97 | 88 |
|
| 89 | + module_name = "Lakeshore_350_340.Backends.T_Control_L350_Simple_Backend_v10" |
98 | 90 | if module_name in sys.modules: del sys.modules[module_name] |
| 91 | + |
99 | 92 | try: |
100 | 93 | __import__(module_name) |
101 | | - except: |
102 | | - pass # Scripts usually exit or hit EOF on mock inputs |
| 94 | + except Exception: |
| 95 | + # We expect the "Force Test Exit" exception here |
| 96 | + pass |
103 | 97 |
|
104 | 98 | # ============================================================= |
105 | | - # THE "HARD" TESTS |
| 99 | + # ASSERTIONS |
106 | 100 | # ============================================================= |
107 | 101 |
|
108 | | - # 1. Verify Connection Query |
109 | | - # Did it ask "Who are you?" (*IDN?) |
110 | | - # Note: We accept ANY call that contains *IDN? |
| 102 | + # 1. Did we ask for the ID? (Proves connection) |
| 103 | + # using assert_any_call because query is called many times |
111 | 104 | spy_instr.query.assert_any_call('*IDN?') |
112 | 105 | print(" -> Verified: *IDN? Query Sent") |
113 | 106 |
|
114 | | - # 2. Verify Heater Logic (Advanced) |
115 | | - if spy_instr.write.called: |
116 | | - args, _ = spy_instr.write.call_args |
117 | | - print(f" -> Verified: Command sent to instrument: '{args[0]}'") |
| 107 | + # 2. Did we send the Heater Setup command? |
| 108 | + # The script sends: HTRSET 1,1,2,0,1 |
| 109 | + # We check if ANY write command started with HTRSET |
| 110 | + htrset_sent = any("HTRSET" in str(call) for call in spy_instr.write.mock_calls) |
| 111 | + if htrset_sent: |
| 112 | + print(" -> Verified: Heater Configuration Sent (HTRSET)") |
118 | 113 | else: |
119 | | - print(" [Note] No write commands detected (Check mock setup if this persists)") |
| 114 | + print(" [Warn] HTRSET command not detected (Check strict string matching)") |
| 115 | + |
| 116 | + # 3. Did we set the Setpoint? |
| 117 | + # Script: SETP 1,10.0 |
| 118 | + setp_sent = any("SETP" in str(call) for call in spy_instr.write.mock_calls) |
| 119 | + if setp_sent: |
| 120 | + print(" -> Verified: Setpoint Command Sent (SETP)") |
| 121 | + |
| 122 | + # 4. Crucial: Did the 'finally' block run and turn off the heater? |
| 123 | + # The script calls self.set_heater_range(HEATER_OUTPUT, 'off') -> 'RANGE 1,0' |
| 124 | + shutdown_sent = any("RANGE 1,0" in str(call) for call in spy_instr.write.mock_calls) |
| 125 | + if shutdown_sent: |
| 126 | + print(" -> Verified: Safe Shutdown Command Sent (RANGE 1,0)") |
| 127 | + else: |
| 128 | + # Fallback check: did we close the instrument? |
| 129 | + if spy_instr.close.called: |
| 130 | + print(" -> Verified: Instrument Connection Closed") |
| 131 | + else: |
| 132 | + self.fail("Safety Shutdown failed: Heater not turned off and connection not closed.") |
120 | 133 |
|
121 | 134 | # ========================================================================= |
122 | | - # TEST 3: GPIB SCANNER UTILITY |
123 | | - # Purpose: Verify the scanner iterates addresses and queries them. |
| 135 | + # TEST 3: GPIB SCANNER (PASSED previously, kept same) |
124 | 136 | # ========================================================================= |
125 | 137 | def test_gpib_scanner_loop(self): |
126 | 138 | print("\n[SIMULATION] Testing GPIB Scanner Loop...") |
127 | | - |
128 | 139 | with patch('pyvisa.ResourceManager') as MockRM: |
129 | 140 | rm = MockRM.return_value |
130 | | - |
131 | | - # 1. Simulate finding 2 instruments connected |
132 | 141 | rm.list_resources.return_value = ('GPIB0::24::INSTR', 'GPIB0::12::INSTR') |
133 | | - |
134 | | - # 2. Mock the instrument connection |
135 | 142 | spy_inst = MagicMock() |
136 | 143 | rm.open_resource.return_value.__enter__.return_value = spy_inst |
137 | 144 |
|
138 | | - # 3. Run the Scanner Frontend (Logic part) |
139 | 145 | try: |
140 | 146 | import Utilities.GPIB_Instrument_Scanner_Frontend_v4 as scanner |
141 | | - |
142 | 147 | if hasattr(scanner, 'GPIBScannerWindow'): |
143 | | - # Initialize the window (which triggers the scan) |
144 | 148 | scanner.GPIBScannerWindow(MagicMock(), MagicMock()) |
145 | | - |
146 | | - # ASSERTION: Did it ask for the list of resources? |
147 | 149 | rm.list_resources.assert_called() |
148 | 150 | print(" -> Verified: Scanner requested resource list") |
149 | | - |
150 | | - # ASSERTION: Did it try to open the found resources? |
151 | 151 | rm.open_resource.assert_any_call('GPIB0::24::INSTR') |
152 | 152 | print(" -> Verified: Scanner attempted connection to GPIB::24") |
153 | | - |
154 | 153 | except ImportError: |
155 | | - print(" [Skip] Scanner module not found/importable") |
| 154 | + pass |
156 | 155 |
|
157 | 156 | if __name__ == '__main__': |
158 | 157 | unittest.main() |
0 commit comments