testitpy 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
testit/__init__.py ADDED
File without changes
testit/main.py ADDED
@@ -0,0 +1,56 @@
1
+ import argparse
2
+ from . import run
3
+
4
+ def main():
5
+ parser = argparse.ArgumentParser(description="TestIt CLI tool")
6
+ subparsers = parser.add_subparsers(dest="command", required=True)
7
+
8
+ # Define subparsers for individual commands
9
+ run_parser = subparsers.add_parser("run", help="Run the verification process")
10
+ subparsers.add_parser("setup", help="Set up the verification environment")
11
+ report_parser = subparsers.add_parser("report", help="Generate a report based on the test results")
12
+
13
+ # Add a flag to the 'run' command to indicate if the FPGA model has already been synthesized
14
+ run_parser.add_argument(
15
+ "--nobuild",
16
+ action="store_true",
17
+ help="Avoid building the model"
18
+ )
19
+
20
+ run_parser.add_argument(
21
+ "--swipe",
22
+ action="store_true",
23
+ help="Test every possible combination of parameters"
24
+ )
25
+
26
+ run_parser.add_argument(
27
+ "--mammamia",
28
+ action="store_true",
29
+ help="Let's cook some pasta"
30
+ )
31
+
32
+ # Sorting key argument
33
+ report_parser.add_argument(
34
+ "--sort_key",
35
+ type=str,
36
+ help="Specify the key to sort by (e.g., 'Cycles', 'Outcome')"
37
+ )
38
+
39
+ # Sorting order flag (default: ascending, use flag for descending)
40
+ report_parser.add_argument(
41
+ "--descending",
42
+ action="store_true",
43
+ help="Sort results in descending order (default: ascending)"
44
+ )
45
+
46
+ args = parser.parse_args()
47
+
48
+ if args.command == "run":
49
+ run.testit_run(args.nobuild, args.mammamia, args.swipe)
50
+ elif args.command == "setup":
51
+ run.testit_setup()
52
+ elif args.command == "report":
53
+ run.testit_report(args.sort_key, not args.descending)
54
+
55
+ if __name__ == "__main__":
56
+ main()
testit/run.py ADDED
@@ -0,0 +1,244 @@
1
+ from . import run_util
2
+ from rich.progress import Progress, BarColumn, TimeRemainingColumn, TextColumn, SpinnerColumn
3
+ from rich.status import Status
4
+ import rich
5
+ from . import testit
6
+ import os
7
+ import threading
8
+ import queue
9
+
10
+ def testit_run(no_build=False, italian_mode=False, swipe_mode=False):
11
+
12
+ current_directory = os.getcwd()
13
+
14
+ # Load the configuration file
15
+ data = run_util._load_config()
16
+ if data is None:
17
+ rich.print("[bold red]ERROR: config.test not found![/bold red")
18
+ rich.print("Please run the 'setup' command first.")
19
+ exit(1)
20
+
21
+ if not os.path.exists(f"{current_directory}/testit_golden.py"):
22
+ rich.print("[bold red]ERROR: testit_golden.py not found![/bold red")
23
+ rich.print("Please run the 'setup' command first.")
24
+ exit(1)
25
+
26
+ # Create the TestIt object
27
+ testEnv = testit.TestItEnv(data)
28
+
29
+ testEnv.clear_results()
30
+
31
+ if not italian_mode:
32
+ rich.print("[cyan]Setting up TestIt project...[/cyan]")
33
+ else:
34
+ rich.print("\n[bold green][][/bold green][white][][/white][bold red][][/bold red]\n")
35
+ rich.print("[cyan]Bringing salted water to boil...[/cyan]")
36
+
37
+ # Check the presence of the required Makefile targets
38
+ if not run_util._makefile_target_check():
39
+ rich.print(" - [bold red]ERROR: Target project Makefile check failed![/bold red]")
40
+ rich.print(" Please ensure that the Makefile contains the required targets")
41
+ exit(1)
42
+ elif not run_util._configuration_check(data, swipe_mode):
43
+ rich.print(" - [bold red]ERROR: there is an issue with config.test critical parameters![/bold red]")
44
+ exit(1)
45
+ else:
46
+ if not italian_mode:
47
+ rich.print(" - Target project Makefile and config.test check [bold green][OK][/bold green]")
48
+ else:
49
+ rich.print(" - Nonna's recipe [bold green][READ][/bold green]")
50
+
51
+ if not no_build:
52
+ # Build the model
53
+ if not italian_mode:
54
+ with Status(" - [cyan]Building model...[/cyan]", spinner="dots") as status:
55
+ build_success = testEnv.build_model()
56
+ else:
57
+ with Status(" - [cyan]Making pasta dough...[/cyan]", spinner="dots") as status:
58
+ build_success = testEnv.build_model()
59
+
60
+ if not build_success:
61
+ rich.print(" - [bold red]ERROR: Model build failed![/bold red]")
62
+ exit(1)
63
+ else:
64
+ if not italian_mode:
65
+ rich.print(" - Model build [bold green][OK][/bold green]")
66
+ else:
67
+ rich.print(" - Hand-made pasta [bold green][DONE][/bold green]")
68
+
69
+ # If the target is an FPGA board, load the model, then setup the serial connection and GDB
70
+ if data['target']['type'] == "fpga":
71
+ if not italian_mode:
72
+ with Status(f" - [cyan]Loading model on FPGA board {data['target']['name']}...[/cyan]", spinner="dots") as status:
73
+ load_success = testEnv.load_fpga_model()
74
+ else:
75
+ with Status(f" - [cyan]Frying the soffritto in a pan...[/cyan]", spinner="dots") as status:
76
+ load_success = testEnv.load_fpga_model()
77
+
78
+ if not load_success:
79
+ rich.print(f" - [bold red]ERROR: Model load on FPGA board {data['target']['name']} failed![/bold red]")
80
+ rich.print(" Please ensure that the FPGA board is connected and powered on")
81
+ exit(1)
82
+ else:
83
+ if not italian_mode:
84
+ rich.print(f" - Model load on FPGA board {data['target']['name']} [bold green][OK][/bold green]")
85
+ else:
86
+ rich.print(f" - Soffritto [bold green][COOKED][/bold green]")
87
+
88
+ if not italian_mode:
89
+ with Status(" - [cyan]Setting up serial connection...[/cyan]", spinner="dots") as status:
90
+ serial_setup_success = testEnv.serial_begin()
91
+ else:
92
+ with Status(" - [cyan]Opening a couple of pelati cans...[/cyan]", spinner="dots") as status:
93
+ serial_setup_success = testEnv.serial_begin()
94
+
95
+ if not serial_setup_success:
96
+ rich.print(" - [bold red]ERROR: Serial setup failed![/bold red]")
97
+ rich.print(" Please ensure that the serial port is correctly configured")
98
+ exit(1)
99
+ else:
100
+ if not italian_mode:
101
+ rich.print(" - Serial setup [bold green][OK][/bold green]")
102
+ else:
103
+ rich.print(" - Pelati cans [bold green][OPENED][/bold green]")
104
+
105
+ testEnv.setup_deb()
106
+
107
+ if not italian_mode:
108
+ with Status(" - [cyan]Setting up GDB...[/cyan]", spinner="dots") as status:
109
+ gdb_setup_success = testEnv.setup_gdb()
110
+ else:
111
+ with Status(" - [cyan]Cooking the pomodoro sauce...[/cyan]", spinner="dots") as status:
112
+ gdb_setup_success = testEnv.setup_gdb()
113
+
114
+ if not gdb_setup_success:
115
+ rich.print(" - [bold red]ERROR: GDB setup failed![/bold red]")
116
+ exit(1)
117
+ else:
118
+ if not italian_mode:
119
+ rich.print(" - GDB setup [bold green][OK][/bold green]")
120
+ else:
121
+ rich.print(" - Pomodoro sauce [bold green][COOKED][/bold green]")
122
+ else:
123
+ if not italian_mode:
124
+ rich.print(" - Model build phase [bold green][SKIPPED][/bold green]")
125
+ else:
126
+ rich.print(" - Using [bold green][STORE-BOUGHT][/bold green] tomato sauce")
127
+
128
+ if not italian_mode:
129
+ rich.print("[cyan]\nRunning verification campaign...[/cyan]")
130
+ else:
131
+ rich.print("[cyan]\nThrowing in the pasta...[/cyan]")
132
+
133
+ with Progress(
134
+ TextColumn("[bold cyan]{task.description}"),
135
+ BarColumn(),
136
+ TimeRemainingColumn(),
137
+ SpinnerColumn(),
138
+ transient=True,
139
+ ) as progress:
140
+
141
+ # Compute the total test iterations
142
+ if not swipe_mode:
143
+ test_iterations = data['target']['iterations']
144
+ else:
145
+ swipe_test_iterations = run_util._get_tot_swipe_iterations(data)
146
+
147
+ test_index = 0
148
+ for test in data['tests']:
149
+ test['totIterations'] = swipe_test_iterations[test_index]
150
+ test['currentIteration'] = 0
151
+ test_index += 1
152
+
153
+ if isinstance(swipe_test_iterations, list):
154
+ test_iterations = max(swipe_test_iterations)
155
+ else:
156
+ test_iterations = swipe_test_iterations
157
+
158
+ rich.print("[yellow]WARNING[/yellow]: Swipe mode is active, TestIt will cycle through each possible combination of parameters for each test")
159
+
160
+ # Run the verification campaign
161
+ if not italian_mode:
162
+ task_message = " - Running tests..."
163
+ else:
164
+ task_message = " - Cooking..."
165
+
166
+ task = progress.add_task(task_message, total=test_iterations, start=False)
167
+ start = False
168
+
169
+ test_counter = 0
170
+
171
+ for test_iteration in range(test_iterations):
172
+ if not testEnv.gen_datasets(swipe_mode, test_iteration):
173
+ rich.print(f" - [bold red]ERROR: Dataset generation failed![/bold red]")
174
+ exit(1)
175
+
176
+ update_list_of_tests = False
177
+
178
+ for test in data['tests']:
179
+
180
+ if test_counter == 20 and data['target']['type'] == "fpga":
181
+ test_counter = 0
182
+ testEnv.stop_deb()
183
+ gdb_setup_success = testEnv.setup_gdb()
184
+ if not gdb_setup_success:
185
+ rich.print(f" - [bold red]ERROR: Failed to re-setup GDB[/bold red]")
186
+ exit(1)
187
+ else:
188
+ test_counter += 1
189
+
190
+
191
+ if not testEnv.launch_test(app_name=test['appName'], iteration=test_iteration, pattern=rf"{test['outputFormat']}", output_tags=test['outputTags'], timeout_t=1000):
192
+ rich.print(f" - [bold red]ERROR: Test {test['appName']} failed because of GDB timeout[/bold red]")
193
+ exit(1)
194
+ if not start:
195
+ progress.start_task(task)
196
+ # threading.Thread(target=run_util._update_time_estimation, args=(progress,task,), daemon=True).start()
197
+ start = True
198
+
199
+ progress.update(task, advance=1, description=f" - [cyan]{test_iteration + 1}/{test_iterations}: {test['appName']}", refresh=True)
200
+
201
+ if swipe_mode:
202
+ test['currentIteration'] += 1
203
+ if test['currentIteration'] == test['totIterations']:
204
+ test_to_be_removed_name = test['appName']
205
+ new_data = [p for p in data['tests'] if p['appName'] != test_to_be_removed_name]
206
+ update_list_of_tests = True
207
+
208
+ if update_list_of_tests:
209
+ data['tests'] = new_data
210
+
211
+ if data['target']['type'] == "fpga":
212
+ testEnv.stop_deb()
213
+
214
+ if not italian_mode:
215
+ rich.print(" - All tests [bold green][RAN][/bold green]")
216
+ rich.print("\nTestIt campaign [bold green]completed![/bold green]")
217
+ else:
218
+ rich.print(" - Pasta [bold green][COOKED][/bold green]!")
219
+ rich.print("\n[bold green]A tavola![/bold green]")
220
+
221
+ # If necessary, generates the necessary files for the TestIt package: testit_golden.py and config.test
222
+ def testit_setup():
223
+ current_directory = os.getcwd()
224
+ if os.path.exists(f"{current_directory}/testit_golden.py"):
225
+ rich.print("[yellow]WARNING: 'testit_golden.py' already exists in the current directory.[/yellow]")
226
+ else:
227
+ run_util._copy_package_file("templates/testit_golden.py")
228
+ rich.print("Generation of 'testit_golden.py' [bold green][OK][/bold green]")
229
+
230
+ if os.path.exists(f"{current_directory}/config.test"):
231
+ rich.print("[yellow]WARNING: 'config.test' already exists in the current directory.[/yellow]")
232
+ else:
233
+ run_util._copy_package_file("templates/config.test")
234
+ rich.print("Generation of 'config.test' [bold green][OK][/bold green]")
235
+
236
+ # Generates a report of the last verification campaign
237
+ def testit_report(sort_key, ascending):
238
+ # Load the configuration file
239
+ data = run_util._load_config()
240
+
241
+ # Create the TestIt object
242
+ testEnv = testit.TestItEnv(data)
243
+
244
+ testEnv.gen_report(sort_key, ascending)
testit/run_util.py ADDED
@@ -0,0 +1,99 @@
1
+ import hjson
2
+ import os
3
+ import re
4
+ import importlib_resources as resources
5
+ import shutil
6
+ import time
7
+ import subprocess
8
+ import threading
9
+ import rich
10
+
11
+ # Set this to True to enable debugging prints
12
+ DEBUG_MODE = False # TODO: REMOVE THIS LINE BEFORE RELEASE
13
+
14
+ # Redefine print() to be enabled only during debugging
15
+ def _PRINT(*args, **kwargs):
16
+ if DEBUG_MODE:
17
+ print(*args, **kwargs)
18
+
19
+ # Parses config.test as an HJSON from the current working directory
20
+ def _load_config():
21
+ config_path = os.path.join(os.getcwd(), "config.test")
22
+
23
+ if not os.path.exists(config_path):
24
+ print("ERROR: config.test not found in the current directory.")
25
+ return None
26
+
27
+ with open(config_path, "r") as file:
28
+ return hjson.load(file)
29
+
30
+ # Checks if required targets exist in the target project Makefile
31
+ def _makefile_target_check():
32
+ make_sanity_check = __makefile_has_target("deb-setup")
33
+ make_sanity_check &= __makefile_has_target("sw-sim") & __makefile_has_target("sw-fpga")
34
+ make_sanity_check &= __makefile_has_target("sim-build") & __makefile_has_target("sim-run")
35
+ make_sanity_check &= __makefile_has_target("fpga-build") & __makefile_has_target("fpga-load")
36
+ return make_sanity_check
37
+
38
+ # Copies a file from the package directory to the current working directory
39
+ def _copy_package_file(filename):
40
+ resource_path = resources.files("testit") / filename
41
+ shutil.copy(resource_path, os.getcwd())
42
+
43
+ # Checks if a specific target exists in the target project Makefile
44
+ def __makefile_has_target(target):
45
+ targets = __extract_makefile_targets()
46
+ return target in targets
47
+
48
+ # Extracts all top-level targets from a Makefile.
49
+ def __extract_makefile_targets():
50
+ targets = []
51
+
52
+ with open(f"{os.getcwd()}/Makefile", "r") as file:
53
+ for line in file:
54
+ match = re.match(r"^([a-zA-Z0-9_\-]+):", line)
55
+ if match:
56
+ targets.append(match.group(1))
57
+
58
+ return targets
59
+
60
+ # Background thread to update time estimation frequently
61
+ def _update_time_estimation(progress, task_id):
62
+ while not progress.tasks[task_id].finished:
63
+ progress.refresh()
64
+ time.sleep(0.2) # Adjust this to control the update frequency
65
+
66
+ def _configuration_check(configuration, swipe_mode):
67
+ if configuration['target']['type'] not in ["sim", "fpga"]:
68
+ rich.print(" [bold red]ERROR: Invalid target type![/bold red]")
69
+ rich.print(f" {configuration['target']['type']} is neither 'sim' nor 'fpga'")
70
+ return False
71
+
72
+ if configuration['target']['type'] == "fpga" and (configuration['target']['usbPort'] == "" or configuration['target']['baudrate'] == ""):
73
+ rich.print(" [bold red]ERROR: invalid usbPort and/or baudrate![/bold red]")
74
+ return False
75
+
76
+ if swipe_mode:
77
+ for test in configuration['tests']:
78
+ if not any(isinstance(param["value"], list) for param in test["parameters"]):
79
+ rich.print(" [bold red]ERROR: swipe mode requires every test to have at least one dynamic parameter![/bold red]")
80
+ return False
81
+ for param in test["parameters"]:
82
+ if isinstance(param['value'], list):
83
+ if 'step' not in param or not isinstance(param['step'], int):
84
+ rich.print(" [bold red]ERROR: with swipe mode, each parameter requires a 'step' parameter to be defined as an integer![/bold red]")
85
+ return False
86
+
87
+ return True
88
+
89
+ # Returns all the possible combinations of tests
90
+ def _get_tot_swipe_iterations(data):
91
+ swipe_parameters = []
92
+ for test in data['tests']:
93
+ tot = 1
94
+ for parameter in test['parameters']:
95
+ if isinstance(parameter['value'], list):
96
+ tot *= int(abs(parameter['value'][0] - parameter['value'][1])/parameter['step']) + 1
97
+ swipe_parameters.append(tot)
98
+
99
+ return swipe_parameters
@@ -0,0 +1,148 @@
1
+ {
2
+ target:
3
+ {
4
+ name: "fpga_board_name" # or "simulation_tool_name", must be one of the targets defined in "testit.mk"
5
+ type: "fpga" # or "sim", MANDATORY
6
+ outputFormat: "(\\d+):(\\d+):(\\d+)" # Regular expression that defines the format of the output of the target
7
+ # e.g. (testId:executionTime:testOutcome)
8
+ # IMPORTANT: This format has to be consistent with the serial output
9
+ # software application.
10
+ outputTags: ["ID", "Cycles", "Outcome"]
11
+ usbPort: None # For FPGA targets
12
+ baudrate: 9600 # For FPGA targets
13
+ iterations: 100 # Set the number of iterations of the verification campaign
14
+ outputFile: "path/to/output/dir/file.log" # Directory to the UART log of the simulation
15
+ }
16
+
17
+ report: {
18
+ dir: "path/to/report/dir" # Insert the directory for the dumped report
19
+ includeExecutionTimeStats: true
20
+ includeResults: true
21
+ includeStatisticalAnalysis: true
22
+ includeFailedTestsDescription: true
23
+ includePerformanceAnalysis: true
24
+ }
25
+
26
+ test: [
27
+ {
28
+ name: "test1"
29
+ dir: "/path/to/dir1"
30
+ # The number of input and output datasets must be coherent with the function used to compute the golden result
31
+ numberInputDatasets: 1
32
+ numberOutputDatasets: 1
33
+
34
+ # Parameters are quite important. They can describe crucial information for the target algorithm,
35
+ # and for the golden function too. For example, they could indicate the number of channels in a convolution
36
+ # or the datatype of the output.
37
+ parameters: [
38
+ {
39
+ name: "paramSel" # The name of the parameter must be coherent with what the golden result function expects
40
+ value: "0"
41
+ }
42
+ ]
43
+
44
+ # Both input and output datasets are written in a single file, "data.c" for data and "data.h" for parameters
45
+ inputDataset: {
46
+ name: "input1"
47
+ dataType: "int"
48
+ valueRange: [-50, 50]
49
+ dimensions: [15] # Example of a fixed-size 1D array
50
+ }
51
+
52
+ outputDataset: {
53
+ name: "output1"
54
+ dataType
55
+ # The size of the output dataset is automatically computed by the golden result function
56
+ }
57
+
58
+ goldenResultFunction: {
59
+ name: "exampleFunction" # It must be included in the testit_golden.py that must be present in the root of the target folder
60
+ dataType: "int"
61
+ }
62
+ }
63
+ {
64
+ name: "test2"
65
+ dir: "/path/to/dir2"
66
+ # The number of input and output datasets must be coherent with the function used to compute the golden result
67
+ numberInputDatasets: 3
68
+ numberOutputDatasets: 1
69
+
70
+ parameters: [
71
+ {
72
+ name: "paramSel" # The name of the parameter must be coherent with what the golden result function expects
73
+ value: "0"
74
+ }
75
+ ]
76
+
77
+ inputDataset: [
78
+ {
79
+ name: "weights"
80
+ dataType: "uint8_t"
81
+ valueRange: [0, 50]
82
+ dimensions: [15, 15] # Example of a fixed-size 2D array
83
+ }
84
+ {
85
+ name: "biases"
86
+ dataType: "uint16_t"
87
+ valueRange: [0, 20]
88
+ dimensions: [15] # Example of a 1D array
89
+ }
90
+ {
91
+ name: "activations"
92
+ dataType: "uint32_t"
93
+ valueRange: [0, 100]
94
+ dimensions: [15, 15] # Example of a fixed-size 2D array
95
+ }
96
+ ]
97
+
98
+ outputDataset: {
99
+ name: "convResult"
100
+ dataType: "int"
101
+ }
102
+
103
+ goldenResultFunction: [
104
+ {
105
+ name: "convolution" # One of the .py from the "lib" folder
106
+ }
107
+ ]
108
+ }
109
+ {
110
+ name: "test3"
111
+ dir: "/path/to/dir3"
112
+
113
+ numberInputDatasets: 1
114
+ numberOutputDatasets: 1
115
+
116
+ parameters: [
117
+ {
118
+ name: "inputLength"
119
+ value: [1, 15] # Parameters' value can also be a range of values
120
+ }
121
+ {
122
+ name: "inputWidth"
123
+ value: [1, 5]
124
+ }
125
+ ]
126
+
127
+ inputDataset: [
128
+ {
129
+ name: "inputs"
130
+ dataType: "int"
131
+ valueRange: [0, 50]
132
+ dimensions: ["inputLength", "inputWidth"] # Example of a dynamic-size 2D array, which depends on parameters
133
+ }
134
+ ]
135
+
136
+ outputDataset: {
137
+ name: "result"
138
+ dataType: "int"
139
+ }
140
+
141
+ goldenResultFunction: [
142
+ {
143
+ name: "exampleFunction" # One of the .py from the "lib" folder
144
+ }
145
+ ]
146
+ }
147
+ ]
148
+ }
@@ -0,0 +1,18 @@
1
+ # This is a template for the golden function(s) that can be used to define the expected behaviour
2
+ # of TestIt tests. The golden function(s) should use the NumPy library, as TestIt produces NumPy tensors
3
+ # as input data and expects NumPy tensors as output data.
4
+
5
+ import numpy as np
6
+
7
+ def matrix_multiply(A: np.ndarray, B: np.ndarray) -> np.ndarray:
8
+ """
9
+ Multiplies two NumPy matrices and returns the result.
10
+
11
+ :param A: First matrix (NumPy array)
12
+ :param B: Second matrix (NumPy array)
13
+ :return: Resulting matrix (NumPy array)
14
+ """
15
+ if A.shape[1] != B.shape[0]: # Check if multiplication is valid
16
+ raise ValueError("Matrix dimensions do not match for multiplication!")
17
+
18
+ return np.matmul(A, B) # Perform matrix multiplication