Skip to content

Commit 431a22e

Browse files
flask8 fixes 4
1 parent 8c9a4ba commit 431a22e

7 files changed

Lines changed: 66 additions & 68 deletions

tests/test_deep_simulation.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,11 @@ def tearDown(self):
2323
# -------------------------------------------------------------------------
2424
def _timeout_handler(self, signum, frame):
2525
raise TimeoutError(
26-
f"Test {self._testMethodName} took longer than 30s! Infinite Loop suspected.")
27-
def run_module_safely(self, module_name, mock_modules): """Imports and runs a module with a strict 30-second timeout."""
28-
with patch.dict('sys.modules', mock_modules):
26+
f"Test {self._testMethodName} took longer than 30s! Infinite Loop suspected.")
27+
28+
def run_module_safely(self, module_name, mock_modules):
29+
"""Imports and runs a module with a strict 30-second timeout."""
30+
with patch.dict('sys.modules', mock_modules): # type: ignore
2931
# Set an alarm for 30 seconds (Works on Linux/GitHub Actions)
3032
if hasattr(signal, 'SIGALRM'):
3133
# Ensure any previous alarm is cleared
@@ -54,7 +56,7 @@ def run_module_safely(self, module_name, mock_modules): """Imports and ru
5456
raise e # Re-raise to fail the test
5557
else:
5658
print(f" -> [INFO] Script stopped with: {e}", flush=True)
57-
59+
5860
finally:
5961
if hasattr(signal, 'SIGALRM'):
6062
signal.alarm(0) # Disable the alarm
@@ -143,9 +145,9 @@ def test_02_lakeshore_backend(self):
143145
with patch('builtins.input', side_effect=['10', '300', '10', '350']), \
144146
patch('builtins.open', mock_open()), \
145147
patch('matplotlib.pyplot.show'), \
146-
patch('matplotlib.pyplot.subplots', return_value=(mock_fig, mock_ax)):
148+
patch('matplotlib.pyplot.subplots', return_value=(mock_fig, mock_ax)): # noqa
147149
self.run_module_safely("Lakeshore_350_340.Backends.T_Control_L350_Simple_Backend_v10", mock_modules)
148-
150+
149151
def test_03_k6517b_pyro_backend(self):
150152
mock_modules = {
151153
'tkinter': MagicMock(),
@@ -252,7 +254,8 @@ def test_06_delta_sensing(self):
252254
with patch('builtins.input', side_effect=inputs), \
253255
patch('pandas.DataFrame.to_csv'):
254256
try:
255-
self.run_module_safely("Delta_mode_Keithley_6221_2182.Backends.Delta_K6221_K2182_L350_T_Sensing_Backend_v1", mock_modules)
257+
self.run_module_safely(
258+
"Delta_mode_Keithley_6221_2182.Backends.Delta_K6221_K2182_L350_T_Sensing_Backend_v1", mock_modules)
256259
except ModuleNotFoundError:
257260
print(" [SKIP] Module not found, skipping.")
258261

@@ -319,7 +322,8 @@ def test_08_combined_2400_2182(self):
319322
inputs = ['10', '1', 'test_file', 'y', 'y', 'y', 'y']
320323
with patch('builtins.input', side_effect=inputs), \
321324
patch('pandas.DataFrame.to_csv'):
322-
self.run_module_safely("Keithley_2400_Keithley_2182.Backends.IV_K2400_K2182_Backend_v1", mock_modules)
325+
self.run_module_safely(
326+
"Keithley_2400_Keithley_2182.Backends.IV_K2400_K2182_Backend_v1", mock_modules)
323327
mock_pymeasure.stop()
324328

325329
def test_09_poling(self):
@@ -414,9 +418,8 @@ def test_12_gpib_rescue(self):
414418
rm = MockRM.return_value
415419
rm.list_resources.return_value = ('GPIB0::1::INSTR',)
416420
self.run_module_safely(
417-
"Utilities.GPIB_Interface_Rescue_Simple_Backened_v2_", mock_modules)
418-
419-
420-
if __name__ == '__main__':
421-
unittest.main()
422-
421+
"Utilities.GPIB_Interface_Rescue_Simple_Backened_v2_", mock_modules)
422+
423+
424+
if __name__ == '__main__':
425+
unittest.main()

tests/test_fixes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ def test_iv_k2400_fix(self, mock_to_csv, mock_plt_show, mock_keithley_class, moc
1515
IV_K2400_Loop_Backend_v10 script, preventing real hardware calls.
1616
"""
1717
from Keithley_2400.Backends import IV_K2400_Loop_Backend_v10 as iv_backend
18-
1918
mock_keithley_instance = MagicMock()
2019
mock_keithley_class.return_value = mock_keithley_instance
2120
mock_keithley_instance.query.return_value = "KEITHLEY INSTRUMENTS INC., MODEL 2400"
@@ -25,6 +24,7 @@ def test_iv_k2400_fix(self, mock_to_csv, mock_plt_show, mock_keithley_class, moc
2524

2625
@patch('Lakeshore_350_340.Backends.T_Control_L350_Simple_Backend_v10.Lakeshore350')
2726
def test_t_control_l350_fix(self, mock_ls_class):
27+
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

tests/test_gui_iv_k2400.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def setUp(self):
1313
Set up a root Tk window and instantiate the GUI class.
1414
This runs before each test.
1515
"""
16-
# We need a root window for the GUI to be instantiated, but we don't need to see it.
16+
# We need a root window for the GUI to be instantiated, but we don't need to see it
1717
self.root = tk.Tk()
1818
self.root.withdraw() # Hide the window
1919

@@ -41,11 +41,10 @@ def test_start_measurement_logic(self, mock_fig_subplots, MockBackend):
4141
# Mock the backend instance that the GUI will create
4242
mock_backend_instance = MockBackend.return_value
4343
# --- Simulate User Input ---
44-
# We directly set the values that would be entered into the GUI's Entry widgets.
45-
app.entries["Sample Name"].insert(0, "TestSample")
46-
app.entries["Max Current"].insert(0, "100") # 100 µA
47-
app.entries["Step Current"].insert(0, "10") # 10 µA
48-
app.entries["Compliance"].insert(0, "20") # 20 V
44+
# We directly set the values that would be entered into the GUI's Entry widgets
45+
app.entries["Sample Name"].insert(0, "TestSample") # 100 µA
46+
app.entries["Max Current"].insert(0, "100") # 10 µA
47+
app.entries["Step Current"].insert(0, "10") # 20 V
4948
app.entries["Delay"].insert(0, "0.5") # 0.5 s
5049
app.keithley_combobox.set("GPIB0::24::INSTR")
5150
app.file_location_path = "/fake/path" # Simulate browsing for a file

tests/test_iv_k2400_loop_backend.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def ramp_side_effect(current):
4747

4848
# --- ASSERTIONS ---
4949
# 1. Check instrument initialization
50-
mock_keithley_class.assert_called_once_with("GPIB::4")
50+
mock_keithley_class.assert_called_once_with("GPIB::4", adapter_args={'py_library': '@sim'})
5151
mock_keithley_instance.disable_buffer.assert_called_once()
5252

5353
# 2. Check instrument configuration

tests/test_iv_k6517b_simple_backend.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import unittest
22
from unittest.mock import patch, MagicMock, mock_open
3-
43
# Import the main function from the script we want to test
54
from Keithley_6517B.High_Resistance.Backends.IV_K6517B_Simple_Backend_v10 import main as iv_simple_main
65

76

87
class TestIVK6517BSimpleBackend(unittest.TestCase):
8+
99
@patch('time.sleep', MagicMock())
1010
@patch('builtins.input', side_effect=['-10', '10', '5', '0.1', 'test_iv_simple.csv'])
1111
@patch('pymeasure.instruments.keithley.Keithley6517B')
@@ -33,7 +33,7 @@ def test_full_run(self, mock_show, mock_file, mock_keithley_class, mock_input):
3333

3434
# --- Assertions ---
3535
# 1. Was the instrument initialized correctly?
36-
mock_keithley_class.assert_called_once_with("GPIB1::27::INSTR")
36+
mock_keithley_class.assert_called_once_with("GPIB1::27::INSTR", adapter_args={'py_library': '@sim'})
3737

3838
# 2. Was the zero-check and correction sequence performed?
3939
mock_instrument.reset.assert_called_once()

tests/test_live_plotter.py

Lines changed: 36 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -3,46 +3,44 @@
33
# This issue appears to be an environmental configuration problem rather than a bug in the code
44
# being tested. Until the environment can correctly resolve matplotlib.animation, this test
55
# cannot run.
6+
import unittest
67

7-
# import os
8-
# import unittest
9-
# import pandas as pd
10-
# import matplotlib.pyplot as plt
11-
# from unittest import mock
12-
# # from Utilities.LivePlotter_v10 import live_plot_from_csv # Commented out due to import error
13-
# import pytest
8+
import pandas as pd
9+
from unittest import mock
10+
import pytest
1411

15-
# @pytest.fixture
16-
# def dummy_csv_file(tmp_path):
17-
# # Create a dummy CSV file for testing
18-
# data = {
19-
# 'Time (s)': [0, 1, 2, 3, 4],
20-
# 'Temperature (K)': [100, 110, 105, 115, 120],
21-
# 'Voltage (V)': [1, 1.1, 1.05, 1.15, 1.2]
22-
# }
23-
# df = pd.DataFrame(data)
24-
# csv_path = tmp_path / "test_data.csv"
25-
# df.to_csv(csv_path, index=False)
26-
# return csv_path
12+
@pytest.fixture
13+
def dummy_csv_file(tmp_path):
14+
# Create a dummy CSV file for testing
15+
data = {
16+
'Time (s)': [0, 1, 2, 3, 4],
17+
'Temperature (K)': [100, 110, 105, 115, 120],
18+
'Voltage (V)': [1, 1.1, 1.05, 1.15, 1.2]
19+
}
20+
df = pd.DataFrame(data)
21+
csv_path = tmp_path / "test_data.csv"
22+
df.to_csv(csv_path, index=False)
23+
return csv_path
2724

28-
# class TestLivePlotter(unittest.TestCase):
29-
# @mock.patch('Utilities.LivePlotter_v10.select_file')
30-
# @mock.patch('matplotlib.pyplot.show')
31-
# @mock.patch('matplotlib.animation.FuncAnimation')
32-
# def test_live_plot_from_csv(self, mock_animation, mock_show, mock_select_file, dummy_csv_file):
33-
# """
34-
# Tests that the live_plot_from_csv function can be called and attempts to plot.
35-
# """
36-
# # Have the mocked select_file return the path to our dummy file
37-
# mock_select_file.return_value = str(dummy_csv_file)
3825

39-
# # We need to run the script's main execution block.
40-
# # Since it's under `if __name__ == '__main__':`, we can import it.
41-
# # The import itself will trigger the logic.
42-
# with mock.patch('Utilities.LivePlotter_v10.live_plot_from_csv') as mock_live_plot:
43-
# import Utilities.LivePlotter_v10
44-
# # The main block calls live_plot_from_csv, so we check that
45-
# mock_live_plot.assert_called_once()
26+
class TestLivePlotter(unittest.TestCase):
27+
@mock.patch('Utilities.LivePlotter_v10.select_file')
28+
@mock.patch('matplotlib.pyplot.show')
29+
@mock.patch('matplotlib.animation.FuncAnimation')
30+
def test_live_plot_from_csv(self, mock_animation, mock_show, mock_select_file, dummy_csv_file):
31+
"""
32+
Tests that the live_plot_from_csv function can be called and attempts to plot.
33+
"""
34+
# Have the mocked select_file return the path to our dummy file
35+
mock_select_file.return_value = str(dummy_csv_file)
4636

47-
# if __name__ == '__main__':
48-
# unittest.main()
37+
# We need to run the script's main execution block.
38+
# Since it's under `if __name__ == '__main__':`, we can import it.
39+
with mock.patch('Utilities.LivePlotter_v10.live_plot_from_csv') as mock_live_plot:
40+
from Utilities import LivePlotter_v10 # noqa
41+
# The main block calls live_plot_from_csv, so we check that
42+
mock_live_plot.assert_called_once()
43+
44+
45+
if __name__ == '__main__':
46+
unittest.main()

tests/test_t_control_l350_backend.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def test_close(self):
7878

7979
class TestMainFunctionAndUserInput(unittest.TestCase):
8080
@patch('builtins.input', side_effect=['100', '200', '10', '300',
81-
'not-a-number', '50', '350', '10', '400'])
81+
'not-a-number', '50', '350', '10', '400'])
8282
def test_get_user_parameters(self, mock_input):
8383
# First call: Valid input
8484
start, end, rate, cutoff = get_user_parameters()
@@ -97,10 +97,9 @@ def test_get_user_parameters(self, mock_input):
9797
@patch('matplotlib.pyplot.show')
9898
@patch('builtins.open', new_callable=mock_open)
9999
@patch('time.sleep', MagicMock())
100-
# Simulate time passing
101100
@patch('time.time', side_effect=[1000, 1002, 1004, 1006, 1008, 1010])
102-
def test_main_runs_and_completes(self, mock_time, mock_open_file,
103-
mock_plt_show, mock_ls_class, mock_input, mock_file_dialog, mock_tk):
101+
def test_main_runs_and_completes(self, mock_time, mock_open_file, mock_plt_show, mock_ls_class,
102+
mock_input, mock_file_dialog, mock_tk):
104103
# --- MOCK SETUP ---
105104
mock_controller = MagicMock()
106105
mock_ls_class.return_value = mock_controller
@@ -116,8 +115,7 @@ def test_main_runs_and_completes(self, mock_time, mock_open_file,
116115

117116
# --- ASSERTIONS ---
118117
# Check initialization
119-
mock_ls_class.assert_called_once_with(
120-
"GPIB0::13::INSTR", adapter_args={'py_library': '@sim'})
118+
mock_ls_class.assert_called_once_with("GPIB0::13::INSTR", adapter_args={'py_library': '@sim'})
121119
mock_controller.reset_and_clear.assert_called_once()
122120
mock_controller.setup_heater.assert_called_once()
123121

0 commit comments

Comments
 (0)