Select Git revision
SFCondition.h
unittest_examples.py 2.72 KiB
import pytest
from unittest.mock import Mock
import os
### Some Examples, how to write test functions ###
###### Simple Test ######
def f1(): #function to test
return 3
def test_f1(): #test function
assert f1() == 3
#########################
##### Parameterization #####
# Usage: call the test-function several times with different parameters
def f2(x):
return x+1
@pytest.mark.parametrize(
"input,expected",
[(1,2),
(5,6),
(8,9)])
def test_f2(input, expected):
assert f2(input) == expected
###########################
##### Test Exceptions #####
# Usage: The function to test returns an exception
def f3():
raise SystemExit(1)
def test_f3():
with pytest.raises(SystemExit):
f3()
###########################
##### Mocking Objects #####
# Usage: the function to test needs complex arguments.
# These arguments can be mocked via Mock-objects.
# Note: More complex examples can be found in error_estimator_test.py (using MagicMock to mock an oject of Main)
def f4(reference):
return reference.get_result()
def test_f4():
mock_ref = Mock()
mock_ref.get_result.return_value = 'xyz'
actual = f4(mock_ref)
assert actual == 'xyz'
###########################
##### Monkey-Patching #####
# Usage: The function to test calls functions of an outside module, uses environmental variables,...
# Monkey-Patching substitutes the behavior/variable with a predefined value
def f5():
return os.getcwd() #returns current working directory (very specific for each computer) -> monkey-patch it
def test_f5(monkeypatch):
def monkey_return(): #function which shall be called instead of os.getcwd()
return 'home/name/'
monkeypatch.setattr(os, 'getcwd', monkey_return) #choose module and function which shall be substituted
assert f5() == 'home/name/'
############################
##### Fixture #####
# Usage: Multiple usages (see documentation); one use case is to execute an expensive calculation once and use it in several tests
# Note: aggregrator_test.py shows an example of a fixture (the instance of Aggregator is a fixture in some tests)
# Beware: If the fixture is an instance of a class, it can happen that "changing the fixture" in one test, can influence another test.
# That is not the case here
@pytest.fixture(scope="module") #calc fixture once per module
def calc():
return True #here, we could have a creation of an instance of some class -> this instance can be used in several tests
def test(calc): #the fixture is given to the test-function
assert calc == True #here, we could call functions for this class and assert their value,...
calc = False
def test2(calc):
assert calc == True
###################