Delete/overwrite imports
I’m trying to set up a scoring script for an starter CS class using unittest
. Essentially, students submit a python file student.py
containing some functions that are usually interdependent (meaning func3() can use func1( )
in its calculations).
I’m writing unit tests for each method by comparing the output of student.func1
with the output of correct.func1
, which is a known correct method implementation (from file correct.py
).
For example, suppose func2
uses func1
in its calculation.
So whether by default or student.func1 fails some tests, I want to override student.func1 with correct.func1, so student.func2
uses a known correct implementation (so it’s not just wrong by default).
What should I do about it? It looks like
setUp
() and tearDown()
are similar to what I want, but I don’t know how to “unimport” a module in python, and haven’t found any resources about it so far.
I’m interested in both the case where student.py contains classes and func1, func2
is a method of a particular class, when func1 and func2
are just defined in general
in student.py
.
Solution
The easiest way to do this is to import student
into your module, then catch AssertionError
when the test fails, and replace the error code in the student module with your own code:
import student
import unittest
def safe_f1():
print("Safe f1")
return 1
class TestSomething(unittest. TestCase):
def test_f1(self):
try:
self.assertEqual(student.func1(), 1)
except AssertionError:
student.func1 = safe_f1
raise
def test_f2(self):
self.assertEqual(student.func2(), 2)
This is a failed/valid virtual student.py:
def func1():
print("Bad f1")
return 2
def func2():
return func1() + 1
return 2
When I run it, I get:
$ python -m unittest test.py
Bad f1
FSafe f1
.
======================================================================
FAIL: test_f1 (test. TestSomething)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/austin/Code/so/test.py", line 13, in test_f1
self.assertEqual(student.func1(), 1)
AssertionError: 2 != 1
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (failures=1)