Skip to content

Commit 3319197

Browse files
test fixes 1
1 parent 2eea91f commit 3319197

7 files changed

Lines changed: 81 additions & 91 deletions

tests/test_fixes.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,19 @@ def test_iv_k2400_fix(self, mock_to_csv, mock_plt_show, mock_keithley_class, moc
2323
iv_backend.main()
2424
self.assertIn("Force Test Exit", str(context.exception))
2525

26-
@patch('Lakeshore_350_340.Backends.T_Control_L350_Simple_Backend_v10.Lakeshore350')
27-
def test_t_control_l350_fix(self, mock_ls_class): # type: ignore
26+
@patch('Lakeshore_350_340.Backends.T_Control_L350_Simple_Backend_v10.pyvisa.ResourceManager')
27+
def test_t_control_l350_fix(self, MockResourceManager): # type: ignore
2828
from Lakeshore_350_340.Backends.T_Control_L350_Simple_Backend_v10 import main
2929

3030
# Configure the mock Lakeshore350 instance that main() will receive
31+
mock_rm = MagicMock()
32+
MockResourceManager.return_value = mock_rm
3133
mock_controller_instance = MagicMock()
32-
mock_ls_class.return_value = mock_controller_instance
33-
# Simulate temp increase
34-
mock_controller_instance.get_temperature.side_effect = [10.0, 10.0, 10.0, 15.0, 21.0]
34+
mock_rm.open_resource.return_value = mock_controller_instance
35+
36+
# Simulate temp increase and force test exit
37+
mock_controller_instance.get_temperature.side_effect = [
38+
10.0, 10.0, 10.0, 15.0, 21.0, Exception("Force Test Exit")]
3539
mock_controller_instance.get_heater_output.return_value = 25.0 # Simulate heater output
3640

3741
with patch('builtins.input', side_effect=['10', '20', '5', '30']), \

tests/test_full_stack_simulation.py

Lines changed: 65 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,7 @@
1313
sys.modules['tkinter.filedialog'] = MagicMock()
1414

1515
# Matplotlib Mocks
16-
sys.modules['matplotlib'] = MagicMock()
17-
sys.modules['matplotlib.pyplot'] = MagicMock()
18-
sys.modules['matplotlib.figure'] = MagicMock()
19-
sys.modules['matplotlib.backends'] = MagicMock()
20-
sys.modules['matplotlib.backends.backend_tkagg'] = MagicMock()
16+
2117

2218

2319
class TestDeepSimulation(unittest.TestCase):
@@ -92,78 +88,73 @@ def test_keithley2400_iv_protocol(self):
9288
# =========================================================================
9389
# TEST 2: LAKESHORE 350 (Complex Logic with Loop)
9490
# =========================================================================
95-
def test_lakeshore_visa_communication(self):
91+
@patch('Lakeshore_350_340.Backends.T_Control_L350_Simple_Backend_v10.pyvisa.ResourceManager')
92+
@patch('Lakeshore_350_340.Backends.T_Control_L350_Simple_Backend_v10.plt')
93+
def test_lakeshore_visa_communication(self, MockPlot, MockResourceManager):
9694
print("\n[SIMULATION] Testing Lakeshore 350 SCPI Commands...")
9795

98-
with patch('pyvisa.ResourceManager') as MockRM:
99-
mock_rm_instance = MockRM.return_value
100-
spy_instr = MagicMock()
101-
mock_rm_instance.open_resource.return_value = spy_instr
102-
103-
# 1. Mock Responses (IDN, then temperature readings)
104-
spy_instr.query.side_effect = [
105-
"LSCI,MODEL350,123456,1.0", # *IDN?
106-
"10.0", # Initial Temp
107-
"10.0", # Stabilize check 1
108-
"10.1", # Stabilize check 2
109-
"10.1", # Loop 1
110-
"10.2", # Loop 2
111-
"300.0" # Safety Fallback
112-
] * 5
113-
114-
# 2. Mock Inputs: Start=10, End=300, Rate=10, Cutoff=350
115-
# (Logic: 10 < 300 < 350 is Valid)
116-
fake_inputs = ['10', '300', '10', '350']
117-
118-
# 3. Mock File Dialog (Must return string)
119-
sys.modules['tkinter'].filedialog.asksaveasfilename.return_value = "dummy.csv"
120-
121-
# 4. Circuit Breaker: Force script to exit after 5 sleep calls
122-
mock_sleep = MagicMock(
123-
side_effect=[
124-
None,
125-
None,
126-
None,
127-
None,
128-
None,
129-
Exception("Force Test Exit")])
130-
131-
# 5. Run It
132-
with patch('builtins.input', side_effect=fake_inputs), \
133-
patch('builtins.open', mock_open()), \
134-
patch('time.sleep', mock_sleep):
135-
136-
self.run_module_safely(
137-
"Lakeshore_350_340.Backends.T_Control_L350_Simple_Backend_v10")
138-
139-
# --- ASSERTIONS ---
140-
141-
# Did we ask for ID?
142-
try:
143-
spy_instr.query.assert_any_call('*IDN?')
144-
print(" -> Verified: *IDN? Query Sent")
145-
except AssertionError:
146-
print(" [FAIL] Connection was not established.")
147-
148-
# Get all write commands sent
149-
write_calls = [str(c) for c in spy_instr.write.mock_calls]
96+
# Mock matplotlib components
97+
mock_fig = MagicMock()
98+
mock_ax = MagicMock()
99+
MockPlot.subplots.return_value = (mock_fig, mock_ax)
100+
MockPlot.ion.return_value = None
101+
MockPlot.ioff.return_value = None
102+
MockPlot.show.return_value = None
103+
104+
mock_rm_instance = MockResourceManager.return_value
105+
spy_instr = MagicMock()
106+
mock_rm_instance.open_resource.return_value = spy_instr
107+
108+
# 1. Mock Responses (IDN, then temperature readings)
109+
# Add the "Force Test Exit" exception to the side_effect for the query,
110+
# ensuring the loop breaks and cleanup is called.
111+
spy_instr.query.side_effect = [
112+
"LSCI,MODEL350,123456,1.0", # *IDN?
113+
"10.0", # Initial Temp
114+
"10.0", # Stabilize check 1
115+
"10.1", # Stabilize check 2
116+
"10.1", # Loop 1
117+
"10.2", # Loop 2
118+
"300.0", # Safety Fallback
119+
Exception("Force Test Exit") # Force exit after some iterations
120+
] * 5
121+
122+
# 2. Mock Inputs: Start=10, End=300, Rate=10, Cutoff=350
123+
# (Logic: 10 < 300 < 350 is Valid)
124+
fake_inputs = ['10', '300', '10', '350']
125+
126+
# 3. Mock File Dialog (Must return string)
127+
sys.modules['tkinter'].filedialog.asksaveasfilename.return_value = "dummy.csv"
128+
129+
# 4. Circuit Breaker: We now let the spy_instr.query raise the exception
130+
# mock_sleep = MagicMock(side_effect=[None, None, None, None, None, Exception("Force Test Exit")])
131+
132+
# 5. Run It
133+
with patch('builtins.input', side_effect=fake_inputs), \
134+
patch('builtins.open', mock_open()), \
135+
patch('time.sleep', MagicMock()): # We mock sleep to prevent delays
136+
137+
self.run_module_safely(
138+
"Lakeshore_350_340.Backends.T_Control_L350_Simple_Backend_v10")
139+
140+
# --- ASSERTIONS ---
141+
142+
# Did we ask for ID?
143+
spy_instr.query.assert_any_call('*IDN?')
144+
print(" -> Verified: *IDN? Query Sent")
145+
146+
# Get all write commands sent
147+
write_calls = [str(c) for c in spy_instr.write.mock_calls]
148+
149+
# Did we configure the heater? (HTRSET)
150+
self.assertTrue(any("HTRSET" in c for c in write_calls), "HTRSET command not found")
151+
print(" -> Verified: Heater Configured (HTRSET)")
152+
153+
# Did we turn it off at the end? (RANGE ... 0) or close the instrument
154+
self.assertTrue(any("RANGE 1,0" in c for c in write_calls) or spy_instr.close.called,
155+
"Safety Shutdown Failed: Heater not off and connection not closed.")
156+
print(" -> Verified: Safety Shutdown (Heater Off or Connection Closed)")
150157

151-
# Did we configure the heater? (HTRSET)
152-
if any("HTRSET" in c for c in write_calls):
153-
print(" -> Verified: Heater Configured (HTRSET)")
154-
else:
155-
print(
156-
f" [Warn] HTRSET command not found. Commands sent: {write_calls[:2]}...")
157-
158-
# Did we turn it off at the end? (RANGE ... 0)
159-
# The script calls: set_heater_range(..., 'off') -> 'RANGE 1,0'
160-
if any("RANGE 1,0" in c for c in write_calls):
161-
print(" -> Verified: Heater Turned Off (RANGE 1,0)")
162-
elif spy_instr.close.called:
163-
print(" -> Verified: Instrument Connection Closed")
164-
else:
165-
self.fail(
166-
"Safety Shutdown Failed: Heater not off and connection not closed.")
167158

168159
# =========================================================================
169160
# TEST 3: GPIB SCANNER

tests/test_gui_iv_k2400.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def tearDown(self):
2424
self.root.destroy()
2525

2626
@patch('Keithley_2400.IV_K2400_GUI_v5.Keithley2400_IV_Backend')
27-
@patch('matplotlib.figure.Figure.subplots')
27+
@patch('Keithley_2400.IV_K2400_GUI_v5.Figure.subplots')
2828
def test_start_measurement_logic(self, mock_fig_subplots, MockBackend):
2929
"""
3030
Tests the core logic of the 'Start' button click.

tests/test_iv_k2400_loop_backend.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
class TestIVK2400LoopBackend(unittest.TestCase):
1010

1111
@patch('builtins.input', side_effect=['10', '2', 'test_output'])
12-
@patch('pymeasure.instruments.keithley.Keithley2400')
12+
@patch('Keithley_2400.Backends.IV_K2400_Loop_Backend_v10.Keithley2400')
1313
@patch('matplotlib.pyplot.show')
1414
@patch('pandas.DataFrame.to_csv')
1515
def test_main_full_run(self, mock_to_csv, mock_plt_show, mock_keithley_class, mock_input):

tests/test_iv_k6517b_simple_backend.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ class TestIVK6517BSimpleBackend(unittest.TestCase):
88

99
@patch('time.sleep', MagicMock())
1010
@patch('builtins.input', side_effect=['-10', '10', '5', '0.1', 'test_iv_simple.csv'])
11-
@patch('pymeasure.instruments.keithley.Keithley6517B')
11+
@patch('Keithley_6517B.High_Resistance.Backends.IV_K6517B_Simple_Backend_v10.Keithley6517B')
1212
@patch('builtins.open', new_callable=mock_open)
1313
@patch('matplotlib.pyplot.show')
1414
def test_full_run(self, mock_show, mock_file, mock_keithley_class, mock_input):

tests/test_live_plotter.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,9 @@
1-
# This test is temporarily commented out due to a persistent ModuleNotFoundError related to
2-
# 'matplotlib.animation' in the testing environment, specifically "matplotlib is not a package".
3-
# This issue appears to be an environmental configuration problem rather than a bug in the code
4-
# being tested. Until the environment can correctly resolve matplotlib.animation, this test
5-
# cannot run.
61
import unittest
7-
8-
import pandas as pd
92
from unittest import mock
103
import pytest
114

5+
import pandas as pd
6+
127

138
@pytest.fixture
149
def dummy_csv_file(tmp_path):

tests/test_pica_launcher.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ class TestPicaLauncher(unittest.TestCase):
5353
"""
5454

5555
# We patch the actual method that is called by the button to ensure it fires.
56-
@patch('test_pica_launcher.MockPicaLauncher.open_iv_sweep')
56+
@patch('tests.test_pica_launcher.MockPicaLauncher.open_iv_sweep')
5757
def test_iv_sweep_button_click_calls_function(self, mock_open_iv_sweep):
5858
"""Tests that clicking the IV Sweep button calls its launch function once."""
5959
launcher = MockPicaLauncher()
@@ -65,7 +65,7 @@ def test_iv_sweep_button_click_calls_function(self, mock_open_iv_sweep):
6565
# Assert the internal counter was incremented
6666
self.assertEqual(launcher.open_gui_calls['iv_sweep'], 1)
6767

68-
@patch('test_pica_launcher.MockPicaLauncher.open_temp_control')
68+
@patch('tests.test_pica_launcher.MockPicaLauncher.open_temp_control')
6969
def test_temp_control_button_click_calls_function(self, mock_open_temp_control):
7070
"""Tests that clicking the Temp Control button calls its launch function once."""
7171
launcher = MockPicaLauncher()

0 commit comments

Comments
 (0)