Changeset - 894f0440934b
[Not reviewed]
0 2 0
Brett Smith - 4 years ago 2020-04-20 18:31:22
brettcsmith@brettcsmith.org
config: Add Config.fiscal_year_begin() method.
2 files changed with 61 insertions and 0 deletions:
0 comments (0 inline, 0 general)
conservancy_beancount/config.py
Show inline comments
...
 
@@ -6,36 +6,39 @@
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU Affero General Public License for more details.
 
#
 
# You should have received a copy of the GNU Affero General Public License
 
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
 

	
 
import configparser
 
import datetime
 
import decimal
 
import functools
 
import os
 
import re
 
import urllib.parse as urlparse
 

	
 
import requests.auth
 
import rt
 

	
 
from pathlib import Path
 
from typing import (
 
    NamedTuple,
 
    Optional,
 
    Tuple,
 
    Type,
 
)
 

	
 
from . import rtutil
 

	
 
class RTCredentials(NamedTuple):
 
    server: Optional[str] = None
 
    user: Optional[str] = None
 
    passwd: Optional[str] = None
 
    auth: Optional[str] = None
 

	
 
    @classmethod
...
 
@@ -75,24 +78,27 @@ class Config:
 
        'XDG_CONFIG_HOME': Path('.config'),
 
    }
 

	
 
    def __init__(self) -> None:
 
        self.file_config = configparser.ConfigParser()
 

	
 
    def load_file(self, config_path: Optional[Path]=None) -> None:
 
        if config_path is None:
 
            config_path = self.config_file_path()
 
        with config_path.open() as config_file:
 
            self.file_config.read_file(config_file)
 

	
 
    def load_string(self, config_str: str) -> None:
 
        self.file_config.read_string(config_str)
 

	
 
    def _dir_or_none(self, path: Path) -> Optional[Path]:
 
        try:
 
            path.mkdir(exist_ok=True)
 
        except OSError:
 
            return None
 
        else:
 
            return path
 

	
 
    def _path_from_environ(self, key: str, default: Optional[Path]=None) -> Path:
 
        try:
 
            retval = Path(os.environ[key])
 
        except (KeyError, ValueError):
...
 
@@ -115,24 +121,42 @@ class Config:
 

	
 
    def cache_dir_path(self, name: str='conservancy_beancount') -> Optional[Path]:
 
        cache_root = self._path_from_environ('XDG_CACHE_HOME')
 
        return (
 
            self._dir_or_none(cache_root)
 
            and self._dir_or_none(cache_root / name)
 
        )
 

	
 
    def config_file_path(self, name: str='conservancy_beancount') -> Path:
 
        config_root = self._path_from_environ('XDG_CONFIG_HOME')
 
        return Path(config_root, name, 'config.ini')
 

	
 
    def fiscal_year_begin(self) -> Tuple[int, int]:
 
        s = self.file_config.get('Beancount', 'fiscal year begin', fallback='3 1')
 
        match = re.match(r'([01]?[0-9])(?:\s*[-./ ]\s*([0-3]?[0-9]))?$', s.strip())
 
        if match is None:
 
            raise ValueError(f"fiscal year begin {s!r} has unknown format")
 
        try:
 
            month = int(match.group(1))
 
            day = int(match.group(2) or 1)
 
            # To check date validity we use an arbitrary year that's
 
            # 1. definitely using the modern calendar
 
            # 2. far enough in the past to not have books (pre-Unix epoch)
 
            # 3. not a leap year
 
            datetime.date(1959, month, day)
 
        except ValueError as e:
 
            raise ValueError(f"fiscal year begin {s!r} is invalid date: {e.args[0]}")
 
        else:
 
            return (month, day)
 

	
 
    def payment_threshold(self) -> decimal.Decimal:
 
        return decimal.Decimal(0)
 

	
 
    def repository_path(self) -> Optional[Path]:
 
        try:
 
            return Path(os.environ['CONSERVANCY_REPOSITORY'])
 
        except (KeyError, ValueError):
 
            return None
 

	
 
    def rt_credentials(self) -> RTCredentials:
 
        all_creds = zip(
 
            RTCredentials.from_env(),
tests/test_config.py
Show inline comments
...
 
@@ -333,12 +333,49 @@ def test_load_file(path):
 
    operator.methodcaller('touch', 0o200),
 
])
 
def test_load_file_error(tmp_path, path_func):
 
    config_path = tmp_path / 'nonexistent.ini'
 
    path_func(config_path)
 
    config = config_mod.Config()
 
    with pytest.raises(OSError):
 
        config.load_file(config_path)
 

	
 
def test_no_books_path():
 
    config = config_mod.Config()
 
    assert config.books_path() is None
 

	
 
@pytest.mark.parametrize('value,month,day', [
 
    ('2', 2, 1),
 
    ('3 ', 3, 1),
 
    ('  4', 4, 1),
 
    (' 5 ', 5, 1),
 
    ('6 1', 6, 1),
 
    ('  06  03  ', 6, 3),
 
    ('6-05', 6, 5),
 
    ('06 - 10', 6, 10),
 
    ('6/15', 6, 15),
 
    ('06  /  20', 6, 20),
 
    ('10.25', 10, 25),
 
    (' 10 . 30 ', 10, 30),
 
])
 
def test_fiscal_year_begin(value, month, day):
 
    config = config_mod.Config()
 
    config.load_string(f'[Beancount]\nfiscal year begin = {value}\n')
 
    assert config.fiscal_year_begin() == (month, day)
 

	
 
@pytest.mark.parametrize('value', [
 
    'text',
 
    '1900',
 
    '13',
 
    '010',
 
    '2 30',
 
    '4-31',
 
])
 
def test_bad_fiscal_year_begin(value):
 
    config = config_mod.Config()
 
    config.load_string(f'[Beancount]\nfiscal year begin = {value}\n')
 
    with pytest.raises(ValueError):
 
        config.fiscal_year_begin()
 

	
 
def test_default_fiscal_year_begin():
 
    config = config_mod.Config()
 
    assert config.fiscal_year_begin() == (3, 1)
0 comments (0 inline, 0 general)