Search code examples
pythonpytest

Is there a way to assert that someone entered the correct code with pytest?


For the past two years, I've used a program called CodeKeyz in my classroom to teach code syntax while I was freed up to exclusively teach the computational thinking aspect of python.

Welp. They're gone. I still have the modules, but I can't actually edit them or change anything, and I'm anticipating them being gone forever soon.

So I'm building a new suite with pytest.

(If you have alternative ideas for doing this kind of teaching, I'm all ears. It's very effective at getting them able to code in python, and I really don't want to give it up, but I don't have a choice.)

I've used TDD in the past, but I'm not sure how to go about this one. I'm looking to see if what a student adds to the code is identical to what I want it to be.

This is the code I have in main.py

def print1(x):
 return print("Hello world")

This is what I have in the testing page.

def test_print1():
  assert print1 is "Hello world"

I'm fairly certain this is wrong.

What I want it to do is show me that they've put in

print("Hello world")

Once I get one of these successful, I can get the rest of them. It shouldn't be hard. Any ideas?


Solution

  • I want to check that executing will output the string

    Then you have to temporarily redirect the standard output stream of your program to a temporary string and execute the function and compare the result..

    def test_print1():
       with contextlib.redirect_stdout(io.StringIO()) as f:
           print1()
       assert f.getvalue() == "Hello world"
    

    See https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout