Skip to content

Commit

Permalink
feat: test paths
Browse files Browse the repository at this point in the history
  • Loading branch information
thorwhalen committed Oct 17, 2023
1 parent b57e3fd commit b06a82e
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
22 changes: 22 additions & 0 deletions dol/tests/test_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Tests for paths.py"""


def test_string_template():
from dol.paths import StringTemplate
from collections import namedtuple

st = StringTemplate('{name} is {age} years old.', field_patterns={'name': r'\w+', 'age': r'\d+'})

assert st.str_to_dict('Alice is 30 years old.') == {'name': 'Alice', 'age': '30'}
assert st.dict_to_str({'name': 'Alice', 'age': '30'}) == 'Alice is 30 years old.'
assert st.dict_to_tuple({'name': 'Alice', 'age': '30'}) == ('Alice', '30')
assert st.tuple_to_dict(('Alice', '30')) == {'name': 'Alice', 'age': '30'}
assert st.str_to_tuple('Alice is 30 years old.') == ('Alice', '30')
assert st.tuple_to_str(('Alice', '30')) == 'Alice is 30 years old.'

Person = st.dict_to_namedtuple({'name': 'Alice', 'age': '30'})
assert Person == namedtuple('Person', ['name', 'age'])('Alice', '30')
assert st.namedtuple_to_dict(Person) == {'name': 'Alice', 'age': '30'}

assert st.str_to_simple_str('Alice is 30 years old.', '-') == 'Alice-30'
assert st.simple_str_to_str('Alice-30', '-') == 'Alice is 30 years old.'
61 changes: 61 additions & 0 deletions dol/tests/utils_for_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Utils for tests."""


from dol import TextFiles
import os
from functools import partial


_dflt_keys = (
"pluto",
"planets/mercury",
"planets/venus",
"planets/earth",
"planets/mars",
"fruit/apple",
"fruit/banana",
"fruit/cherry",
)


def mk_test_store_from_keys(
keys=_dflt_keys,
*,
mk_store=dict,
obj_of_key=lambda k: f"Content of {k}",
empty_store_before_writing=False,
):
"""Make some test data for a store from a list of keys.
None of the arguments are required, for the convenience of getting test stores
quickly:
>>> store = mk_test_store_from_keys()
>>> store = mk_test_store_from_keys.for_local() # makes files in temp local dir
>>> store = mk_test_store_from_keys(keys=['one', 'two', 'three'])
"""
if isinstance(mk_store, str):
mk_store = mk_tmp_local_store(mk_store)
store = mk_store()
if empty_store_before_writing:
for k in store:
del store[k]
for k in keys:
store[k] = obj_of_key(k)
return store


def mk_tmp_local_store(
tmp_name="temp_local_store", mk_store=TextFiles, make_dirs_if_missing=True
):
from dol import temp_dir, mk_dirs_if_missing

store = mk_store(temp_dir(tmp_name))
if make_dirs_if_missing:
store = mk_dirs_if_missing(store)
return store


mk_test_store_from_keys.for_local = partial(
mk_test_store_from_keys, mk_store=mk_tmp_local_store
)

0 comments on commit b06a82e

Please sign in to comment.