How did you test in COMP1511?
#include <stdio.h>
#include <assert.h>
double sum(double a, double b) {
return a + b;
}
int main() {
assert(sum(1, 2) == 3);
assert(sum(2, 2) == 4);
assert(sum(3, 2) == 5);
printf("All tests passed\n");
}
ctest.c
Let's first look at python functions
double sum(double a, double b) {
return a + b;
}
def sum(a, b):
return a + b
Q. What are the key differences?
Let's first look at python functions
double sum(double a, double b) {
return a + b;
}
def sum(a, b):
return a + b
Q. What are the key differences?
Q. How would we test this python function?
def sum(a, b):
return a + b
Q. How would we test this python function?
def sum(a, b):
return a + b
assert sum(1, 4) == 3
cstyletest.c
Let's clean this up and wrap it in a function, though!
def sum(a, b):
return a + b
def testSmallNumbers():
assert sum(1, 4) == 3
testSmallNumbers()
Let's take a look at pytest
What is pytest?
def sum(x, y):
return x * y
def test_sum1():
assert sum(1, 2) == 3
test_sum1()
$ python3 test1_nopytest.py
test1_nopytest.py
import pytest
def sum(x, y):
return x * y
def test_sum1():
assert sum(1, 2) == 3, "1 + 2 == 3"
$ pytest test1_pytest.py
test1_pytest.py
import pytest
def sum(x, y):
return x + y
def test_small():
assert sum(1, 2) == 3, "1, 2 == "
assert sum(3, 5) == 8, "3, 5 == "
assert sum(4, 9) == 13, "4, 9 == "
def test_small_negative():
assert sum(-1, -2) == -3, "-1, -2 == "
assert sum(-3, -5) == -8, "-3, -5 == "
assert sum(-4, -9) == -13, "-4, -9 == "
def test_large():
assert sum(84*52, 99*76) == 84*52 + 99*76, "84*52, 99*76 == "
assert sum(23*98, 68*63) == 23*98 + 68*63, "23*98, 68*63 == "
A more complicated test
test_multiple.py
If you just run
$ pytest
Without any files, it will automatically look for any files in that directory in shape:
You can run specific functions without your test files with the -k command. For example, we if want to run the following:
We could run
$ pytest -k small
or try
$ pytest -k small -v
We can also use a range of decorators to specify tests in python:
import pytest
def pointchange(point, change):
x, y = point
x += change
y += change
return (x, y)
@pytest.fixture
def supply_point():
return (1, 2)
@pytest.mark.up
def test_1(supply_point):
assert pointchange(supply_point, 1) == (2, 3)
@pytest.mark.up
def test_2(supply_point):
assert pointchange(supply_point, 5) == (6, 7)
@pytest.mark.up
def test_3(supply_point):
assert pointchange(supply_point, 100) == (101, 102)
@pytest.mark.down
def test_4(supply_point):
assert pointchange(supply_point, -5) == (-4, -3)
@pytest.mark.skip
def test_5(supply_point):
assert False == True, "This test is skipped"
@pytest.mark.xfail
def test_6(supply_point):
assert False == True, "This test's output is muted"
There are a number of tutorials online for pytest. This is a very straightforward one.