I have a function which requires all parameters to be positive:
def calc_energy(n, hbar=1, w=1): if hbar <= 0: raise ValueError(" hbar must be positive") if w <= 0: raise ValueError(" w must be positive") if n < 0: raise ValueError(" n must not be negative") return hbar * w * (n + 1 / 2)
To test that this produces the correct behavior, I wrote the following test function in the same file and a main function to call it:
def test_calc_energy(): try: calc_energy(0, hbar=0) except ValueError: assert True else: assert False try: calc_energy(-1) except ValueError: assert True else: assert False try: calc_energy(0, hbar=1, w=-1) except ValueError: assert True else: assert False if __name__ == "__main__": test_calc_energy()
Is there a better way to write the calc_energy()
function or the test_calc_energy()
function? Both seem rather lengthy to me.
On my laptop, I have the test in a separate file, from which I import the file with the calc_energy
function, and I run pytest
. One would just need to put all the code in a file, say named energy.py
, then run python energy.py
. It will return assertion error if the tests fail.