[PYTHON] pytest
Test berechne.py mit pytest
calculation.py
import os
class Cal(object):
def add_num_and_double(self, x, y):
if type(x) is not int or type(y) is not int:
raise ValueError
result = x + y
result *= 2
return result
def save(self, dir_path, file_name):
if not os.path.exists(dir_path):
os.mkdir(dir_path)
file_path = os.path.join(dir_path, file_name)
with open(file_path, 'w') as f:
f.write('test')
conftest.py
import os
import pytest
#Einzigartige Leuchte
@pytest.fixture
def csv_file(tmpdir):
with open(os.path.join(tmpdir, 'test.csv'), 'w+') as c:
print('before test')
yield c
print('after test')
def pytest_addoption(parser):
parser.addoption('--os-name', default='linux', help='os name')
test_calculation.py
#pip install pytest
import pytest
import calculation
import os
is_release = True
#Wenn Sie mit einer Funktion testen, testen Sie zu Beginn_tragen
#def test_add_num_and_double():
# cal = calculation.Cal()
# assert cal.add_num_and_double(1, 1) != 4
#Wenn Sie in der Klasse testen, fügen Sie am Anfang TEST hinzu
class TestCal(object):
@classmethod
def setup_class(cls):
print('start')
cls.cal = calculation.Cal()
cls.test_dir = '/tmp/test_dir'
cls.test_file_name = 'test.txt'
def test_save_no_dir(self):
self.cal.save(self.test_dir, self.test_file_name)
test_file_path = os.path.join(self.test_dir, self.test_file_name)
assert os.path.exists(test_file_path) is True
@classmethod
def teardown_class(cls):
print('end')
del cls.cal
#Eigentlich oben schreiben
import shutil
if os.path.exists(cls.test_dir):
shutil.rmtree(cls.test_dir)
#Wird aufgerufen, bevor der Test ausgeführt wird
def setup_method(self, method):
print('method={}'.format(method.__name__))
#self.cal = calculation.Cal()
#Wird nach dem Test aufgerufen
def teardown_method(self, method):
print('method={}'.format(method.__name__))
#del self.cal
#csv_Datei ist ein eigenes Gerät
def test_add_num_and_double(self, csv_file):
print(csv_file)
#Wenn das Gerät angefordert wird
#os_name = request.config.getoption('--os-name')
#print(os_name)
#if os_name == 'mac':
# print('ls')
#elif os_name == 'windows':
#print('dir')
#cal = calculation.Cal()
assert self.cal.add_num_and_double(1, 1) == 4
def test_save(self, tmpdir):
self.cal.save(tmpdir, self.test_file_name)
test_file_path = os.path.join(tmpdir, self.test_file_name)
assert os.path.exists(test_file_path) is True
#Ausnahmetest(Kann übersprungen werden)
#@pytest.mark.skip(reason='skip!')
@pytest.mark.skipif(is_release==True, reason='skip!')
def test_add_num_and_double_raise(self):
with pytest.raises(ValueError):
#cal = calculation.Cal()
self.cal.add_num_and_double('1', '1')