Testing And Benchmarking in OpenSCAD

Here’s the translation of the Go testing and benchmarking example to OpenSCAD, formatted in Markdown suitable for Hugo:

OpenSCAD does not have built-in unit testing or benchmarking capabilities like some other programming languages. However, we can create a simple testing framework and demonstrate how to test functions in OpenSCAD.

First, let’s create a simple function to test:

function IntMin(a, b) = (a < b) ? a : b;

Now, let’s create a simple testing framework:

function runTest(testName, actual, expected) =
    let(result = actual == expected)
    let(message = str(testName, ": ", result ? "PASS" : "FAIL", 
                      " (Expected: ", expected, ", Got: ", actual, ")"))
    echo(message);

module testIntMin() {
    echo("Running IntMin tests...");
    runTest("Test 1", IntMin(2, -2), -2);
    runTest("Test 2", IntMin(0, 1), 0);
    runTest("Test 3", IntMin(1, 0), 0);
    runTest("Test 4", IntMin(0, -1), -1);
    runTest("Test 5", IntMin(-1, 0), -1);
}

testIntMin();

In this example, we’ve created a runTest function that compares the actual result with the expected result and prints a message indicating whether the test passed or failed. The testIntMin module runs a series of tests on our IntMin function.

To run the tests, you would simply include this file in your OpenSCAD project and run it. The test results will be displayed in the console output.

OpenSCAD doesn’t have a built-in benchmarking system, but you could create a simple timing mechanism if needed:

function benchmark(func, iterations) =
    let(start = millis())
    let(dummy = [for(i = [0:iterations-1]) func()])
    let(end = millis())
    let(duration = end - start)
    echo(str("Benchmark: ", iterations, " iterations took ", duration, " milliseconds"));

benchmark(function() IntMin(1, 2), 1000000);

This benchmark function runs the given function a specified number of times and reports how long it took. Note that this is not as sophisticated as dedicated benchmarking tools in other languages, and the results may not be as precise.

To run this in OpenSCAD:

  1. Save the code in a file (e.g., intmin_test.scad).
  2. Open the file in OpenSCAD.
  3. Look at the console output to see the test results and benchmark information.

Remember that OpenSCAD is primarily designed for creating 3D models, not for general-purpose programming or testing. These testing and benchmarking approaches are basic approximations of what you might find in more traditional programming languages.