Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Доработка плагина до работоспособного состояния

Добавлен тестовый сценарий
Изменена логика работы проверки по существованию файла
  • Loading branch information...
commit 8c988453021facfb7b1fe727d21edf5976fc2396 1 parent 28ec287
@cgi authored
View
70 build/lib/pytest_filetests.py
@@ -0,0 +1,70 @@
+import py
+import pytest
+import re
+# Origin version of file was taken from:
+# http://pytest.org/example/nonpython.html#non-python-tests
+#
+#
+
+def pytest_collect_file(path, parent):
+ if path.ext in (".yml", ".yaml") and path.basename.startswith("test"):
+ return YamlFile(path, parent)
+
+class YamlFile(pytest.File):
+ def collect(self):
+ import yaml # we need a yaml parser, e.g. PyYAML
+ raw = yaml.load(self.fspath.open())
+ for tc_name, tc_spec in raw.items():
+ yield YamlItem(tc_name, self, tc_spec)
+
+class YamlItem(pytest.Item):
+ def __init__(self, name, parent, spec):
+ super(YamlItem, self).__init__(name, parent)
+ self.spec = spec
+ self.description = spec.get('test_desc', '')
+
+ def runtest(self):
+ for name, value in self.spec.items():
+ # some custom test execution (dumb example follows)
+ if name in ('test_desc'):
+ pass
+ elif name in ('assert_file_exists'):
+ FileExistsItem(**value).test()
+ else:
+ raise TestFileException(self, 0, name, value )
+
+ def repr_failure(self, excinfo):
+ """ called when self.runtest() raises an exception. """
+ if isinstance(excinfo.value, TestFileException):
+ return "\n".join([
+ "Тест проведен:",
+ " результат: {}".format( excinfo.value.args[1] ),
+ " условие: {}".format( excinfo.value.args[2] ),
+ " дополнительная информация: {}".format(excinfo.value.args[3])
+ ])
+ else:
+ super(YamlItem, self).repr_failure(excinfo)
+
+ def reportinfo(self):
+ return self.fspath, 0, "usecase: {0} ({1})".format( self.name, self.description )
+
+class FileExistsItem(object):
+ def __init__(self, file_mask, file_count_eval=None):
+ super(FileExistsItem, self).__init__()
+ if file_count_eval is None:
+ file_count_eval = 'count > 0'
+ self.file_re = re.compile(file_mask, re.IGNORECASE)
+ self.file_count_eval = file_count_eval
+
+ def test(self):
+ start_path = py.path.local('.')
+ files = [p.relto(start_path) for p in start_path.visit()]
+ matches = [p for p in files if self.file_re.search(p) ]
+ count = len(matches)
+ res = eval(self.file_count_eval, {'count':count}, dict())
+ if not res:
+ raise TestFileException(self, count, self.file_count_eval, matches)
+
+class TestFileException(Exception):
+ """ custom exception for error reporting. """
+
View
10 pytest_filetests.egg-info/PKG-INFO
@@ -0,0 +1,10 @@
+Metadata-Version: 1.0
+Name: pytest-filetests
+Version: 0.1
+Summary: Simple plugin for py.test for reading tests from yaml files
+Home-page: http://github.com/cgi/pytest_filetests
+Author: Ermolin Ilya
+Author-email: ermolinis+pytest@gmail.com
+License: UNKNOWN
+Description: UNKNOWN
+Platform: UNKNOWN
View
8 pytest_filetests.egg-info/SOURCES.txt
@@ -0,0 +1,8 @@
+README
+pytest_filetests.py
+setup.py
+pytest_filetests.egg-info/PKG-INFO
+pytest_filetests.egg-info/SOURCES.txt
+pytest_filetests.egg-info/dependency_links.txt
+pytest_filetests.egg-info/entry_points.txt
+pytest_filetests.egg-info/top_level.txt
View
1  pytest_filetests.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
View
3  pytest_filetests.egg-info/entry_points.txt
@@ -0,0 +1,3 @@
+[pytest11]
+filetests = pytest_filetests
+
View
1  pytest_filetests.egg-info/top_level.txt
@@ -0,0 +1 @@
+pytest_filetests
View
47 pytest_filetests.py
@@ -1,12 +1,13 @@
import py
import pytest
+import re
# Origin version of file was taken from:
# http://pytest.org/example/nonpython.html#non-python-tests
#
#
def pytest_collect_file(path, parent):
- if path.ext == ".yml" and path.basename.startswith("test"):
+ if path.ext in (".yml", ".yaml") and path.basename.startswith("test"):
return YamlFile(path, parent)
class YamlFile(pytest.File):
@@ -20,28 +21,50 @@ class YamlItem(pytest.Item):
def __init__(self, name, parent, spec):
super(YamlItem, self).__init__(name, parent)
self.spec = spec
+ self.description = spec.get('test_desc', '')
def runtest(self):
- # !!!TODO: test code
for name, value in self.spec.items():
# some custom test execution (dumb example follows)
- if name in ('assert_file_exists'):
-
- if name != value:
- raise YamlException(self, name, value)
+ if name in ('test_desc'):
+ pass
+ elif name in ('assert_file_exists'):
+ FileExistsItem(**value).test()
+ else:
+ raise TestFileException(self, 0, name, value )
def repr_failure(self, excinfo):
""" called when self.runtest() raises an exception. """
- if isinstance(excinfo.value, YamlException):
+ if isinstance(excinfo.value, TestFileException):
return "\n".join([
- "usecase execution failed",
- " spec failed: %r: %r" % excinfo.value.args[1:3],
- " no further details known at this point."
+ "Тест проведен:",
+ " результат: {}".format( excinfo.value.args[1] ),
+ " условие: {}".format( excinfo.value.args[2] ),
+ " дополнительная информация: {}".format(excinfo.value.args[3])
])
+ else:
+ super(YamlItem, self).repr_failure(excinfo)
def reportinfo(self):
- return self.fspath, 0, "usecase: {}".format( self.name )
+ return self.fspath, 0, "usecase: {0} ({1})".format( self.name, self.description )
+
+class FileExistsItem(object):
+ def __init__(self, file_mask, file_count_eval=None):
+ super(FileExistsItem, self).__init__()
+ if file_count_eval is None:
+ file_count_eval = 'count > 0'
+ self.file_re = re.compile(file_mask, re.IGNORECASE)
+ self.file_count_eval = file_count_eval
+
+ def test(self):
+ start_path = py.path.local('.')
+ files = [p.relto(start_path) for p in start_path.visit()]
+ matches = [p for p in files if self.file_re.search(p) ]
+ count = len(matches)
+ res = eval(self.file_count_eval, {'count':count}, dict())
+ if not res:
+ raise TestFileException(self, count, self.file_count_eval, matches)
-class YamlException(Exception):
+class TestFileException(Exception):
""" custom exception for error reporting. """
View
10 tests/test_01.yaml
@@ -0,0 +1,10 @@
+test_this_file_exists:
+ test_desc: "Проверка существования этого файла"
+ assert_file_exists:
+ file_mask: "tests.test_01.yaml"
+ file_count_eval: "count == 1"
+test_this_file_exists:
+ test_desc: "Проверка возвращает ошибку из-за некорректного количества найденных файлов"
+ assert_file_exists:
+ file_mask: "tests.test_01.yaml"
+ file_count_eval: "count < 1"
Please sign in to comment.
Something went wrong with that request. Please try again.