aboutsummaryrefslogtreecommitdiffstats
path: root/tests
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2020-06-21 11:12:26 -0500
committerEugene Triguba <eugenetriguba@gmail.com>2020-06-21 11:12:26 -0500
commit2c293cc0ac6678253c6af8101ba93866785f64c0 (patch)
tree04e74630e02fadac0bdcbe15d51975a1fe0197b6 /tests
parentUse lowercase action name (diff)
downloadconfig-file-2c293cc0ac6678253c6af8101ba93866785f64c0.zip
WIP for refactoring tests
Diffstat (limited to 'tests')
-rw-r--r--tests/conftest.py67
-rw-r--r--tests/templates/ini/default.ini7
-rw-r--r--tests/templates/json/default.json13
-rw-r--r--tests/templates/json/glossary.json35
-rw-r--r--tests/templates/json/invalid.json1
-rw-r--r--tests/test_base_parser.py2
-rw-r--r--tests/test_config_file.py195
-rw-r--r--tests/test_json_parser.py201
8 files changed, 294 insertions, 227 deletions
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..bb16405
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,67 @@
+from pathlib import Path
+from typing import Callable, Type
+
+import pytest
+
+from config_file.parsers import BaseParser, IniParser, JsonParser
+from config_file.utils import create_config_path
+
+
+@pytest.fixture
+def tmp_file(tmp_path) -> Callable[[str, str], Path]:
+ def func(file_name: str, file_contents: str) -> Path:
+ file = tmp_path / file_name
+ file.touch()
+ file.write_text(file_contents, encoding="utf-8")
+ return file
+
+ return func
+
+
+@pytest.fixture
+def template_file(tmp_file: Callable[[str, str], Path]) -> Callable[[str, str], Path]:
+ template_dir = Path(__file__).parent / "templates"
+
+ def func(file_type: str, template_name: str = "default") -> Path:
+ file_name = f"{template_name}.{file_type}"
+ template = template_dir / file_type / file_name
+
+ return tmp_file(file_name, template.read_text(encoding="utf-8"))
+
+ return func
+
+
+@pytest.fixture
+def template_original_file() -> Callable[[Path], Path]:
+ def func(template_path: str):
+ original_path = create_config_path(template_path, original=True)
+ original_path.touch()
+ original_path.write_text(template_path.read_text(encoding="utf-8"))
+
+ return original_path
+
+ return func
+
+
+@pytest.fixture
+def template_and_parser(template_file: Callable[[str, str], Path]) -> tuple:
+ def func(
+ file_type: str, template_name: str = "default"
+ ) -> Callable[[str, str], Type[BaseParser]]:
+ test_file = template_file(file_type, template_name)
+ text = test_file.read_text(encoding="utf-8")
+
+ if file_type == "ini":
+ return test_file, IniParser(text)
+ elif file_type == "json":
+ return test_file, JsonParser(text)
+
+ return func
+
+
+@pytest.fixture
+def templated_parser(template_and_parser) -> Callable[[str, str], Type[BaseParser]]:
+ def func(file_type: str, template_name: str = "default") -> Type[BaseParser]:
+ return template_and_parser(file_type, template_name)[1]
+
+ return func
diff --git a/tests/templates/ini/default.ini b/tests/templates/ini/default.ini
new file mode 100644
index 0000000..4f711db
--- /dev/null
+++ b/tests/templates/ini/default.ini
@@ -0,0 +1,7 @@
+[header_one]
+number_key = 0
+
+[header_two]
+str_key = "string"
+list_key = [1, 2, 3]
+
diff --git a/tests/templates/json/default.json b/tests/templates/json/default.json
new file mode 100644
index 0000000..83d9b1e
--- /dev/null
+++ b/tests/templates/json/default.json
@@ -0,0 +1,13 @@
+{
+ "header_one": {
+ "number_key": 0
+ },
+ "header_two": {
+ "str_key": "string",
+ "list_key": [
+ 1,
+ 2,
+ 3
+ ]
+ }
+} \ No newline at end of file
diff --git a/tests/templates/json/glossary.json b/tests/templates/json/glossary.json
new file mode 100644
index 0000000..189d8a4
--- /dev/null
+++ b/tests/templates/json/glossary.json
@@ -0,0 +1,35 @@
+{
+ "glossary": {
+ "title": "str_value",
+ "GlossDiv": {
+ "title": "5",
+ "GlossList": {
+ "GlossEntry": {
+ "ID": "false",
+ "SortAs": "SGML",
+ "GlossTerm": "Standard Generalized Markup Language",
+ "Acronym": "SGML",
+ "Abbrev": "ISO 8879:1986",
+ "GlossDef": {
+ "para": "A meta-markup language, used to create markup languages such as DocBook.",
+ "GlossSeeAlso": ["GML", "XML"]
+ },
+ "GlossSee": "5.5"
+ }
+ }
+ },
+ "dict": {
+ "key": "str_value",
+ "str_number": "5"
+ },
+ "dict_within_dict": {
+ "str_number": "16",
+ "another_dict": {
+ "str_bool": "false",
+ "list_of_values": [
+ "5", "false", "trUe"
+ ]
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/tests/templates/json/invalid.json b/tests/templates/json/invalid.json
new file mode 100644
index 0000000..8e12c39
--- /dev/null
+++ b/tests/templates/json/invalid.json
@@ -0,0 +1 @@
+{'test': } \ No newline at end of file
diff --git a/tests/test_base_parser.py b/tests/test_base_parser.py
index 1127a61..6bb58e7 100644
--- a/tests/test_base_parser.py
+++ b/tests/test_base_parser.py
@@ -1,6 +1,6 @@
import pytest
-from config_file.parsers.base_parser import BaseParser
+from config_file import BaseParser
class ConcreteParser(BaseParser):
diff --git a/tests/test_config_file.py b/tests/test_config_file.py
index 861b169..d89edc6 100644
--- a/tests/test_config_file.py
+++ b/tests/test_config_file.py
@@ -5,61 +5,98 @@ import pytest
from config_file import BaseParser, ConfigFile
+SUPPORTED_FILE_TYPES = ["ini", "json"]
-@pytest.mark.parametrize(
- "file_contents, file_name", [("[calendar]\nsunday_index = 0\n\n", "config.ini")]
-)
-def test_that_config_file_initializes_correctly(tmp_path, file_contents, file_name):
- temp = tmp_path / file_name
- temp.write_text(file_contents)
- config = ConfigFile(temp)
- assert config.path == temp
- assert config.contents == temp.read_text()
- assert isinstance(config.parser, BaseParser)
+@pytest.fixture(params=SUPPORTED_FILE_TYPES)
+def template_and_config_file(request, template_file):
+ def func(template_name: str = "default", parser: BaseParser = None):
+ template = template_file(request.param, template_name)
+ return (template, ConfigFile(template, parser=parser))
+
+ return func
+
+
+@pytest.fixture
+def templated_config_file(template_and_config_file):
+ def func(template_name: str = "default", parser: BaseParser = None):
+ return template_and_config_file(template_name, parser)[1]
+
+ return func
+
+
+def test_that_config_file_is_initialized_correctly(template_and_config_file):
+ template_file, config = template_and_config_file()
+
+ assert config.path == template_file
+ assert config.stringify() == template_file.read_text()
+ assert isinstance(config._ConfigFile__parser, BaseParser)
+
+
+def test_that_a_tidle_in_the_config_path_expands_to_the_absolute_path():
+ config_name = "temp.ini"
+ config_path = "~/" + config_name
+
+ try:
+ Path(config_path).expanduser().touch()
+ assert ConfigFile(config_path).path == Path.home() / config_name
+ finally:
+ Path(config_path).expanduser().unlink()
+
+
+@pytest.mark.skip(msg="needs fixing up")
+@pytest.mark.parametrize("path", ["", "invalid", "invalid.conf"])
+def test_invalid_config_paths(path):
+ with pytest.raises(ValueError):
+ ConfigFile(path)
+
+
+def test_that_config_file_can_save(template_and_config_file):
+ template_file, config = template_and_config_file()
+
+ config.set("header_one.number_key", 25)
+ config.save()
+
+ assert config.stringify() == template_file.read_text()
-@pytest.mark.parametrize(
- "file_contents, file_name, original_file_name",
- [("[calendar]\nsunday_index = 0\n\n", "config.ini", "config.original.ini")],
-)
def test_that_config_file_can_restore_the_original(
- tmpdir, file_contents, file_name, original_file_name
+ templated_config_file, template_original_file
):
- config_path = Path(tmpdir / file_name)
- config_path.write_text(file_contents, encoding="utf-8")
- original_config_path = Path(tmpdir / original_file_name)
- original_config_path.write_text(file_contents, encoding="utf-8")
+ config = templated_config_file()
+ original_file = template_original_file(config.path)
- config = ConfigFile(config_path)
- config.set("calendar.sunday_index", 5)
+ config.set("header_one.number_key", 5)
config.restore_original()
- assert config.stringify() == ConfigFile(original_config_path).stringify()
+ assert config.stringify() == original_file.read_text()
-def test_missing_config_files_during_restore(tmpdir):
- config_path = Path(tmpdir / "config.ini")
- config_path.write_text("")
- config = ConfigFile(config_path)
+def test_missing_config_file_during_restore(templated_config_file):
+ config = templated_config_file()
with pytest.raises(FileNotFoundError) as error:
- config.restore_original(original_file_path="jhklasdfhjlkasjej")
+ config.restore_original()
assert "file to restore to does not exist" in str(error)
@pytest.mark.parametrize(
- "file_contents, file_name", [("[calendar]\nsunday_index = 0\n\n", "config.ini")]
+ "file_extension, file_contents, section_key, expected_result",
+ [
+ ("ini", "[calendar]\nsunday_index = 0\n\n", "calendar.sunday_index", True),
+ ("ini", "[calendar]\nsunday_index = 0\n\n", "calendar.blah", False),
+ ("ini", "[calendar]\nsunday_index = 0\n\n", "calendar", True),
+ ("json", json.dumps({"calendar": {"sunday_index": 0}}), "calendar", True),
+ ("json", json.dumps({"calendar": {"sunday_index": 0}}), "blah", False),
+ ("json", json.dumps({"calendar": {"sunday_index": 0}}), "sunday_index", True),
+ ],
)
-def test_that_config_file_can_save(tmpdir, file_contents, file_name):
- config_path = tmpdir / file_name
- config_path.write_text(file_contents, encoding="utf-8")
-
- config = ConfigFile(str(config_path))
- config.set("calendar.sunday_index", 1)
- config.save()
- assert config.stringify() == Path(config_path).read_text(encoding="utf-8")
+def test_that_config_file_can_find_sections_and_keys(
+ tmp_file, file_extension, file_contents, section_key, expected_result
+):
+ config = ConfigFile(tmp_file(f"file.{file_extension}", file_contents))
+ assert config.has(section_key) == expected_result
@pytest.mark.parametrize(
@@ -124,7 +161,7 @@ def test_that_config_file_can_get(
):
config_path = tmpdir / file_name
config_path.write_text(file_contents, encoding="utf-8")
- config = ConfigFile(str(config_path))
+ config = ConfigFile(config_path)
ret_val = config.get(section_key, parse_types=parse_type, default=default)
if return_type is not None:
@@ -133,68 +170,22 @@ def test_that_config_file_can_get(
assert ret_val == value
-@pytest.mark.parametrize(
- "file_extension, file_contents, section_key, expected_result",
- [
- ("ini", "[calendar]\nsunday_index = 0\n\n", "calendar.sunday_index", True),
- ("ini", "[calendar]\nsunday_index = 0\n\n", "calendar.blah", False),
- ("ini", "[calendar]\nsunday_index = 0\n\n", "calendar", True),
- ("json", json.dumps({"calendar": {"sunday_index": 0}}), "calendar", True),
- ("json", json.dumps({"calendar": {"sunday_index": 0}}), "blah", False),
- ("json", json.dumps({"calendar": {"sunday_index": 0}}), "sunday_index", True),
- ],
-)
-def test_that_config_file_can_find_sections_and_keys(
- tmpdir, file_extension, file_contents, section_key, expected_result
-):
- config_path = tmpdir / f"config.{file_extension}"
- config_path.write_text(file_contents, encoding="utf-8")
- config = ConfigFile(str(config_path))
- assert config.has(section_key) == expected_result
-
-
-@pytest.mark.parametrize(
- "section_key, file_name, file_contents, deleted_file_contents",
- [
- (
- "calendar.sunday_index",
- "config.ini",
- "[calendar]\nsunday_index = 0\n\n",
- "[calendar]\n\n",
- ),
- (
- "calendar.sunday_index",
- "config.json",
- json.dumps({"calendar": {"sunday_index": 0}}),
- json.dumps({"calendar": {}}),
- ),
- ],
-)
-def test_that_config_file_can_delete(
- tmpdir, section_key, file_name, file_contents, deleted_file_contents
-):
- config_path = tmpdir / file_name
- config_path.write_text(file_contents, encoding="utf-8")
- config = ConfigFile(str(config_path))
- config.delete(section_key)
- assert config.stringify() == deleted_file_contents
+def test_that_config_file_can_delete(templated_config_file):
+ config = templated_config_file()
+ config.delete("header_one.number_key")
-@pytest.mark.parametrize(
- "path, is_dir", [("invalid", False), ("invalid", True), ("invalid.conf", False)]
-)
-def test_invalid_config_paths(tmpdir, path, is_dir):
- with pytest.raises(ValueError):
- temp_path = tmpdir / path
- temp_path.write("")
- ConfigFile(str(tmpdir)) if is_dir else ConfigFile(str(temp_path))
+ assert config.has("header_one.number_key") is False
-def test_that_custom_parser_can_be_used(tmpdir):
+def test_that_custom_parser_can_be_used(template_and_config_file):
class CustomParser(BaseParser):
def __init__(self, file_contents):
super().__init__(file_contents)
+ def parse(self, file_contents: str):
+ return file_contents
+
def get(self, key, parse_types=True):
return key
@@ -210,27 +201,11 @@ def test_that_custom_parser_can_be_used(tmpdir):
def stringify(self) -> str:
return str(self.parsed_content)
- def parse(self, file_contents: str):
- return file_contents
-
- config_path = tmpdir / "config.conf"
- config_path.write_text("", encoding="utf-8")
- config = ConfigFile(str(config_path), parser=CustomParser)
+ template_file, config = template_and_config_file(parser=CustomParser)
- assert isinstance(config.parser, CustomParser)
+ assert isinstance(config._ConfigFile__parser, CustomParser)
assert config.get("key") == "key"
assert config.set("key", "value") == ("key", "value")
assert config.delete("section_key") == "section_key"
assert config.has("blah")
- assert config.stringify() == ""
-
-
-def test_that_a_tidle_in_the_config_path_expands_to_the_absolute_path():
- config_name = "fjlajbkfdajfdioanfks.ini"
- config_path = "~/" + config_name
-
- try:
- Path(config_path).expanduser().touch()
- assert ConfigFile(config_path).path == Path.home() / config_name
- finally:
- Path(config_path).expanduser().unlink()
+ assert config.stringify() == template_file.read_text()
diff --git a/tests/test_json_parser.py b/tests/test_json_parser.py
index 42a0ba9..18a2b6f 100644
--- a/tests/test_json_parser.py
+++ b/tests/test_json_parser.py
@@ -6,155 +6,124 @@ from config_file.exceptions import ParsingError
from config_file.parsers.json_parser import JsonParser
-@pytest.mark.parametrize("test_json", ["{'test': }", "[section]\nblah = value\n\n"])
-def test_invalid_json(test_json):
+def test_invalid_json(templated_parser):
with pytest.raises(ParsingError):
- JsonParser(test_json)
+ templated_parser("json", "invalid")
-def test_that_json_parser_can_stringify():
- json_str = '{"test": 5, "blah": true}'
- parser = JsonParser(json_str)
- assert parser.stringify() == json_str
+def test_that_json_parser_can_stringify(template_and_parser):
+ template, parser = template_and_parser("json")
+ assert parser.stringify() == template.read_text()
@pytest.mark.parametrize(
- "test_input,expected_result",
+ "key",
[
- ("glossary", True),
- ("title", True),
- ("example glossary", False),
- ("GlossDiv", True),
- ("title", True),
- ("5", False),
- ("GlossList", True),
- ("GlossEntry", True),
- ("ID", True),
- ("false", False),
- ("GlossTerm", True),
- ("Standard Generalized Markup Language", False),
- ("Acronym", True),
- ("ISO 8879:1986", False),
- ("GlossDef", True),
- ("para", True),
- (
- "A meta-markup language, used to create markup languages "
- "such as DocBook.",
- False,
- ),
- ("GlossSeeAlso", True),
- ("GML", False),
- ("XML", False),
- ("GlossSee", True),
- ("5.5", False),
+ "glossary",
+ "title",
+ "GlossDiv",
+ "title",
+ "GlossList",
+ "GlossEntry",
+ "ID",
+ "GlossTerm",
+ "Acronym",
+ "GlossDef",
+ "para",
+ "GlossSeeAlso",
+ "GlossSee",
],
)
-def test_that_json_parser_can_find_keys(test_input, expected_result):
- test_json = {
- "glossary": {
- "title": "example glossary",
- "GlossDiv": {
- "title": "5",
- "GlossList": {
- "GlossEntry": {
- "ID": "false",
- "SortAs": "SGML",
- "GlossTerm": "Standard Generalized Markup Language",
- "Acronym": "SGML",
- "Abbrev": "ISO 8879:1986",
- "GlossDef": {
- "para": "A meta-markup language, used to create markup "
- + "languages such as DocBook.",
- "GlossSeeAlso": ["GML", "XML"],
- },
- "GlossSee": "5.5",
- }
- },
- },
- }
- }
+def test_that_json_parser_can_find_keys(key, templated_parser):
+ parser = templated_parser("json", "glossary")
+ assert parser.has(key)
- parser = JsonParser(json.dumps(test_json))
- assert parser.has(test_input) == expected_result
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "str_value",
+ "5",
+ "false",
+ "Standard Generalized Markup Language",
+ "ISO 8879:1986",
+ "A meta-markup language, used to create markup languages such as DocBook.",
+ "GML",
+ "XML",
+ "5.5",
+ ],
+)
+def test_that_json_parser_does_not_find_value_with_has(value, templated_parser):
+ parser = templated_parser("json", "glossary")
+ assert not parser.has(value)
@pytest.mark.parametrize(
- "test_json, section_key, parse_type, expected_result",
+ "key, value",
[
+ ("glossary.title", "str_value"),
+ ("glossary.dict", {"key": "str_value", "str_number": "5"}),
+ ],
+)
+def test_that_json_parser_can_get_keys_without_parsing_types(
+ templated_parser, key, value
+):
+ parser = templated_parser("json", "glossary")
+ assert parser.get(key) == value
+
+
+@pytest.mark.parametrize(
+ "key, value",
+ [
+ ("glossary.title", "str_value"),
+ ("glossary.dict.str_number", 5),
(
- {"glossary": {"title": "example glossary"}},
- "glossary.title",
- False,
- "example glossary",
- ),
- (
- {"glossary": {"title": "example glossary"}},
- "glossary.title",
- True,
- "example glossary",
- ),
- (
- {"glossary": {"title": "example glossary", "dict": {"blah": "5"}}},
- "glossary.dict",
- False,
- {"blah": "5"},
- ),
- (
- {"glossary": {"title": "example glossary", "dict": {"blah": "5"}}},
- "glossary.dict",
- True,
- {"blah": 5},
- ),
- (
+ "glossary.dict_within_dict",
{
- "glossary": {
- "title": "example glossary",
- "dict": {"blah": "5", "second": {"third": "5"}},
- }
+ "str_number": 16,
+ "another_dict": {"str_bool": False, "list_of_values": [5, False, True]},
},
- "glossary.dict",
- True,
- {"blah": 5, "second": {"third": 5}},
),
],
)
-def test_that_json_parser_can_get_keys(
- test_json, section_key, parse_type, expected_result
-):
- parser = JsonParser(json.dumps(test_json))
- assert parser.get(section_key, parse_types=parse_type) == expected_result
+def test_that_json_parser_can_get_keys_with_parsing_types(templated_parser, key, value):
+ parser = templated_parser("json", "glossary")
+ assert parser.get(key, parse_types=True) == value
@pytest.mark.parametrize(
"key, value", [("zip", "zipzip"), ("foo.bar.foobar", 5), ("foo.baz", "bar")]
)
-def test_that_json_parser_can_set_keys(key, value):
- test_json = {
- "foo": {
- "baz": 5,
- "boo": "4.4",
- "bar": {"test_key": "foobar", "foobar": {"test": True}},
- },
- "bar": {"baz": 10},
- "zip": "piz",
- }
+def test_that_json_parser_can_set_keys(templated_parser, key, value):
+ parser = templated_parser("json")
+
+ # test_json = {
+ # "foo": {
+ # "baz": 5,
+ # "boo": "4.4",
+ # "bar": {"test_key": "foobar", "foobar": {"test": True}},
+ # },
+ # "bar": {"baz": 10},
+ # "zip": "piz",
+ # }
+ # parser = JsonParser(json.dumps(test_json))
- parser = JsonParser(json.dumps(test_json))
parser.set(key, value)
assert parser.get(key) == value
@pytest.mark.parametrize(
- "key, test_json, expected_json",
- [
- ("foo", {"foo": "bar", "baz": 5}, {"baz": 5}),
- ("foo.bar", {"foo": {"bar": 5}}, {"foo": {}}),
- ],
+ "key",
+ ["glossary", "dict_within_dict", "glossary.GlossDiv.GlossList.GlossEntry.Abbrev"],
)
-def test_that_json_parser_can_delete_keys(key, test_json, expected_json):
- parser = JsonParser(json.dumps(test_json))
+def test_that_json_parser_can_delete_keys(
+ template_and_parser, key, test_json, expected_json
+):
+ template, parser = template_and_parser("json", "glossary")
+
parser.delete(key)
- assert parser.stringify() == json.dumps(expected_json)
+
+ assert parser.stringify() == template.read_text(encoding="utf-8")
@pytest.mark.parametrize(