I'm making a simple quiz app that asks a user to write a source code. For example, a user is asked to "Given n values, add them and print it". Input is
N
a[0], a[1], ..., a[N-1]
and output is
s
For example, an input is
3
1 3 5
and an output is
9
A user should write
N = int(input())
print(sum(([int(input()) for i input().split()))
The source code should be in string because a user answers in HTML input and submits it to a server.
Given the above context, how would you test source code in string which contains input
and print
?
My work-in-progress code is
# source should be assigned with the payload of from HTTP POST request
source = `print([int(input()) for i in range(N))`
# How to feed an input and validate an output?
assertEqual(correct_answer, exec(source))
I was thinking to use exec
, but not sure how I can feed input for input()
programatically.
At least, you can redirect stdout for print
.