How to Write Tests
In the previous section, we discussed some basic tests. However, it is important to note that this approach may not always be ideal or satisfying.
To streamline your testing process and enhance efficiency, we have developed a method known as ‘functional chaining’. This approach allows you to link multiple test functions together in a single, cohesive operation.
htmlwhat uses the .
to “chain together” SCT/test functions. Every chain starts with the Ex()
function call, which holds exercise state. Hence it automatically take cares about State
.
Let’s have a look on it.
- test_exercise(sct: str, student_code: str, solution_code: str) dict
Test an exercise with a student’s code and a solution code directly.
- Parameters:
sct (str) – The SCT (Submission Correctness Test) code to evaluate the student’s code against.
student_code (str) – The code written by the student.
solution_code (str) – The correct solution code.
- Returns:
Test result, a dictionary with the keys
'correct'
and'message'
.- Return type:
dict
- Raises:
InstructorError – If anything wrong in the solution code.
- Example:
>>> from htmlwhat import test_exercise >>> userhtml = """ ... <!DOCTYPE html> ... <html> ... <head> ... <title>Title</title> ... </head> ... <body class="hello"> ... <h1>My First Heading</h1> ... </body> ... </html> ... """ >>> solutionhtml = """ ... <!DOCTYPE html> ... <html> ... <head> ... <title>Title</title> ... </head> ... <body class="example"> ... <h1>My First Heading</h1> ... </body> ... </html> ... """ >>> test = "Ex().check_body().has_equal_attr()" >>> test_exercise(test, userhtml, solutionhtml) { 'correct': False, 'message': 'Inspect the <code><body></code> tag. Expected attribute <code>class</code> to be <code>"example"</code>, but found <code>"hello"</code>.' }
In case if the student’s code is correct then the result will be:
{'correct': True, 'message': 'Great work!'}
This function automatically convert feedback into html.
Tip
You can use
from htmlwhat.failure import InstructorError, TestFail
to handle exceptions.Also, you can use
to_html
function of thefrom htmlwhat.Reporter import Reporter
to convert your test report into html.
from htmlwhat.Reporter import Reporter
from htmlwhat.failure import InstructorError, TestFail
from htmlwhat import test_exercise
try:
test_exercise()
except InstructorError as e:
Reporter.to_html(str(e))