A versatile object mocking utility for unit testing.
For example, assuming a function that uses a connection utility:
def find_python_files_at(connection):
try:
status, stdout, stderr = connection.send_command("ls /my/path", shell=True)
files = output.split("\n")
return [F for F in files if F.endswith(".py")]
except Exception:
return []
A unit test can be written with a mock instances:
fake = Mocker()
def test_find_python_files():
# the return value itself
intedned_result = (0, "file.py\nfile2.txt\nfile3.py", "")
# Use all the parameters as they would be passed , and set the return value at the end
fake.set__send_command("ls /my/path", shell=True, intended_result)
# When this function calls `connection.send_command(...) , it will do so on the Mocker
# Because the parameters match, the pre-seeded result will be returned
res = find_python_files_at(fake)
assert res == ["file.py", "file3.py"], res
# Test the scenario where an exception is thrown
# Instead of a value, pass a callable
def _raiser():
raise RuntimeError("test error")
fake.set__send_command("ls /my/path", shell=True, _raiser)
res = find_python_files_at(fake)
assert res == [], f"Should have been empty, got: {res}"