Home > other >  Running Test Cases in Django, just like testcases in leetcode, codesignal and codewar
Running Test Cases in Django, just like testcases in leetcode, codesignal and codewar

Time:07-19

Does anybody knows, how we can run test cases on a data(function) sent by the user in Django, (as implemented by leetcode, codesignals and codewar) How my function(solution) is tested against these test, how can I implement this functionality at backend using django, django rest framework (click on this link to see the image)

CodePudding user response:

import subprocess


def test_submission():
    compiled_code = "test.out"
    test_input = open("path/to/test_input.txt")
    submission_output = open("path/to/submission_output.txt")
    
    cmd = [f"./{compiled_code}"]
    subprocess.run(cmd, stdin=test_input, stdout=submission_output)
    
    
    # At this point the output of executed code with test_input is stored in "path/to/submission_output.txt"
    return
    

The test_program can be any file be it C, C or Python.

CodePudding user response:

If you don't need test support, you should be able to run code easily by just using the official container images for the language and the Docker CLI.

and there is a tool too which was used by codewar and qualified, and you can also see this clone of codewar too for better understanding, I think it's bit simplified and a practical implementation of this codewar CLI too,

and one last thing, if you are in python use can also use eval but the prob with using this, some malicious user can insert rogue script that could be harmful, so I think you should avoid using it,

personally I think, you should use the simple docker option with a bit of sandboxing, because in our case, It's mostly just a thin wrapper around Docker API that takes the submitted code, prepares the environment and executes them. It's so simple that the original PoC was just few lines of shell script and a tiny tool written in Go.

  • Related