how to define helper functions

Re: how to define helper functions

by Richard Lobb -
Number of replies: 0
There are several possible solutions here.

The easiest is probably to click the Customise checkbox and insert the functions you want directly into the template, just before the test section. For example, the template might become:

{{ STUDENT_ANSWER }}

SEPARATOR = "#<ab@17943918#@>#"

def my_test_func():
    # Whatever you declare here is available to all the tests
    ...
    return ...

{% for TEST in TESTCASES %}
{{ TEST.testcode }}
{% if not loop.last %}
print(SEPARATOR)
{% endif %}
{% endfor %}

A more elegant and general solution is to instead modify the template to insert the global extra field before the tests, then you can insert the test code you want into the global extra.

{{ STUDENT_ANSWER }}

SEPARATOR = "##"

{{ QUESTION.globalextra }}

{% for TEST in TESTCASES %}
{{ TEST.testcode }}
{% if not loop.last %}
print(SEPARATOR)
{% endif %}
{% endfor %}

That second solution can be made into a new question type if you want to use that idea in multiple questions.

Yet another solution, which doesn't require any customisation, is to create a python module called, say, test_funcs.py, and attach it as a support file for the question. Then each test case could do something like

import test_funcs
test_data = test_funcs.make_data()
result = student_func(test_data)
print(result)

Note that you should do the import for every test, even though it looks like you should be able to get away with doing it only for the first test. The reason is that if there's a run time error in a test, CodeRunner falls back to running tests one by one. In the usual case where all the tests are run in a single sandbox submission the multiple imports of the same file don't cause any problems - only the first one has any effect.

As to what keywords to search for ... I doubt there is one, sorry. I've tried to document how the CodeRunner engine works (think of this as analogous to a programming language reference manual) but I've never attempted to write a manual on how to author questions (analogous to a "how to write programs" book). It would be a tall order because there are so many different languages and so many different types of problems that authors want to write. Plus ... I'm primarily a teacher of programming, not a software developer or textbook writer :-)