Pytest - second example beyond hello world
Archive - Originally posted on "The Horse's Mouth" - 2016-01-08 07:03:16 - Graham EllisMoving on from my hello Pytest World example, lets add some more tests and put the code we're testing into a separate file. The test code is [here] and - if working in a TDD (Test Driven Developent) mode it will be written first - forming the specificiation for the class you're writing.
I have brought the code to be tested in with:
from mathstuff import *
Having carefully thought through whether "from" to bring the code into my current namespace or "import" to keep it separate, I've decided (in order to keep the training examples a bit shorter to use import. For a small real-world setup this might be a good decision, for a large and complex setup with lots of classes to be tested, from would be best. The file mathstuff.py is [here]
In addition to the "hello world" example, I've added ...
1. Further tests ... identified by being methods with names starting test_
2. A test which starts with the name another_; in order for this to be picked up by the park of pytest that seeks out the tests, I've provided a configuration file, setup.cfg which may be found [here], as follows:
[pytest]
python_functions = another_* test_*
3. I have decorated one of the tests to indicate that I know it will fail
@pytest.mark.xfail
def test_add_003():
assert addition(10,15) == 26
4. I have provided a setup routine to be run before each and every test (but better ways of doing this are shown in later examples):
def setup_function(summat):
print("The world is round {}".format(summat))
5. I have run my tests with the -s option so that any print statements within are run / displayed (default is that stdout is supressed)
python -m pytest -s test_mathfuncs.py
Full code including sample output from a run ... [here]