diff --git a/src/escpos/config.py b/src/escpos/config.py index d4868f3..f0d249b 100644 --- a/src/escpos/config.py +++ b/src/escpos/config.py @@ -3,6 +3,7 @@ This module contains the implementations of abstract base class :py:class:`Config`. """ import os +import pathlib import appdirs import yaml @@ -56,23 +57,19 @@ class Config(object): config_path = os.path.join( appdirs.user_config_dir(self._app_name), self._config_file ) + if isinstance(config_path, pathlib.Path): + # store string if posixpath + config_path = config_path.as_posix() + if not os.path.isfile(config_path): + # supplied path is not a file --> assume default file + config_path = os.path.join(config_path, self._config_file) try: - # First check if it's file like. If it is, pyyaml can load it. - # I'm checking type instead of catching exceptions to keep the - # exception handling simple - if hasattr(config_path, "read"): - config = yaml.safe_load(config_path) - else: - # If it isn't, it's a path. We have to open it first, otherwise - # pyyaml will try to read it as yaml - with open(config_path, "rb") as config_file: - config = yaml.safe_load(config_file) + with open(config_path, "rb") as config_file: + config = yaml.safe_load(config_file) except EnvironmentError: raise exceptions.ConfigNotFoundError( - "Couldn't read config at {config_path}".format( - config_path=str(config_path), - ) + f"Couldn't read config at {config_path}" ) except yaml.YAMLError: raise exceptions.ConfigSyntaxError("Error parsing YAML") diff --git a/test/test_config.py b/test/test_config.py new file mode 100644 index 0000000..c2474e3 --- /dev/null +++ b/test/test_config.py @@ -0,0 +1,54 @@ +#!/usr/bin/python +"""tests for config module + +:author: `Patrick Kanzler `_ +:organization: `python-escpos `_ +:copyright: Copyright (c) 2023 `python-escpos `_ +:license: MIT +""" + + +def generate_dummy_config(path): + """Generate a dummy config in path""" + dummy_config_content = "printer:\n type: Dummy\n" + path.write_text(dummy_config_content) + assert path.read_text() == dummy_config_content + + +def test_config_load_with_file(tmp_path): + """Test the loading of a config with a config file.""" + # generate a dummy config + config_file = tmp_path / "config.yaml" + generate_dummy_config(config_file) + + # test the config loading + from escpos import config + + c = config.Config() + c.load(config_path=config_file) + print(c._printer_config) + + # test the resulting printer object + p = c.printer() + p._raw(b"1234") + + assert p.output == b"1234" + + +def test_config_load_with_path(tmp_path): + """Test the loading of a config with a config path.""" + # generate a dummy config + config_file = tmp_path / "config.yaml" + generate_dummy_config(config_file) + + # test the config loading + from escpos import config + + c = config.Config() + c.load(config_path=tmp_path) + + # test the resulting printer object + p = c.printer() + p._raw(b"1234") + + assert p.output == b"1234"