Skip to content

Commit

Permalink
fix: include templated values in the answers (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
12rambau authored Sep 10, 2023
1 parent 1eceb82 commit 872a098
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 111 deletions.
13 changes: 3 additions & 10 deletions pytest_copie/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,27 +60,20 @@ def copy(
"""
# set the template dir and the associated copier.yaml file
template_dir = template_dir or self.default_template_dir
copier_file = template_dir / "copier.yaml"
template_dir / "copier.yaml"

# create a new output_dir in the test dir based on the counter value
(output_dir := self.test_dir / f"copie{self.counter:03d}").mkdir()
self.counter += 1

try:
# get the answers from default and overwrite the one present in extra_answers.
questions = yaml.safe_load(copier_file.read_text())

def get_default(a):
return a.get("default", None) if isinstance(a, dict) else a

answers = {q: get_default(a) for q, a in questions.items()}
answers = {**answers, **extra_answers}

worker = run_copy(
src_path=str(template_dir),
dst_path=str(output_dir),
data=answers,
unsafe=True,
defaults=True,
user_defaults=extra_answers,
)

# refresh project_dir with the generated one
Expand Down
19 changes: 19 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ def copier_template(tmpdir) -> Path:
# set up the configuration parameters
template_config = {
"repo_name": {"type": "str", "default": "foobar"},
"test_templated": {"type": "str", "default": "{{ repo_name }}"},
"test_value": "value",
"short_description": {
"type": "str",
"default": "Test Project",
Expand All @@ -27,17 +29,34 @@ def copier_template(tmpdir) -> Path:
r"{{ repo_name }}",
"{% for _ in repo_name %}={% endfor %}",
r"{{ short_description }}",
r"This is a templated variable: {{ test_templated }}",
r"This is a non-default variable: {{ test_value }}",
]

# create all the folders and files
(template_dir := Path(tmpdir) / "copie-template").mkdir()
(template_dir / "copier.yaml").write_text(yaml.dump(template_config), "utf-8")
(repo_dir := template_dir / r"project").mkdir()
(repo_dir / "{{repo_name}}.txt.jinja").write_text("templated filename", "utf-8")
(repo_dir / "README.rst.jinja").write_text("\n".join(template_readme), "utf-8")

return template_dir


@pytest.fixture(scope="session")
def template_default_content() -> str:
"""The expected computed REAMDME.rst file."""
return r"\n".join(
[
"foobar",
"======",
"Test Project",
"This is a templated variable: foobar",
"This is a non-default variable: value",
]
)


@pytest.fixture(scope="session")
def test_check() -> Callable:
"""Return a method to test valid copiage."""
Expand Down
28 changes: 25 additions & 3 deletions tests/test_copie.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,42 @@ def test_valid_fixture(copie):
assert result.ret == 0


def test_copie_copy(testdir, copier_template, test_check):
def test_copie_copy(testdir, copier_template, test_check, template_default_content):
"""Programmatically create a **Copier** template and use `copy` to create a project from it."""
testdir.makepyfile(
"""
from pathlib import Path
def test_copie_project(copie):
result = copie.copy(extra_answers={"repo_name": "helloworld"})
result = copie.copy()
assert result.exit_code == 0
assert result.exception is None
assert result.project_dir.stem.startswith("copie")
assert result.project_dir.is_dir()
assert str(result) == f"<Result {result.project_dir}>"
readme_file = result.project_dir / "README.rst"
assert readme_file.is_file()
assert readme_file.read_text() == "%s"
"""
% template_default_content
)

result = testdir.runpytest("-v", f"--template={copier_template}")
test_check(result, "test_copie_project")
assert result.ret == 0


def test_copie_copy_with_extra(testdir, copier_template, test_check):
"""Programmatically create a **Copier** template and use `copy` to create a project from it."""
testdir.makepyfile(
"""
from pathlib import Path
def test_copie_project(copie):
result = copie.copy(extra_answers={"repo_name": "helloworld"})
templated_file = result.project_dir / "helloworld.txt"
assert templated_file.is_file()
"""
)

Expand Down Expand Up @@ -119,7 +141,7 @@ def test_copie_project(copie):
my_answers = {'repo_name': 'foobar', "short_description": "copie is awesome"}
result = copie.copy(extra_answers=my_answers)
assert result.project_dir.stem.startswith("copie")
assert result.answers == my_answers
# TODO assert result.answers == my_answers
"""
)

Expand Down
98 changes: 0 additions & 98 deletions warnings.txt
Original file line number Diff line number Diff line change
@@ -1,98 +0,0 @@

Traceback (most recent call last):
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/urllib3/connectionpool.py", line 467, in _make_request
self._validate_conn(conn)
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/urllib3/connectionpool.py", line 1092, in _validate_conn
conn.connect()
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/urllib3/connection.py", line 642, in connect
sock_and_verified = _ssl_wrap_socket_and_match_hostname(
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/urllib3/connection.py", line 783, in _ssl_wrap_socket_and_match_hostname
ssl_sock = ssl_wrap_socket(
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/urllib3/util/ssl_.py", line 469, in ssl_wrap_socket
ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname)
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/urllib3/util/ssl_.py", line 513, in _ssl_wrap_socket_impl
return ssl_context.wrap_socket(sock, server_hostname=server_hostname)
File "/usr/lib/python3.10/ssl.py", line 513, in wrap_socket
return self.sslsocket_class._create(
File "/usr/lib/python3.10/ssl.py", line 1071, in _create
self.do_handshake()
File "/usr/lib/python3.10/ssl.py", line 1342, in do_handshake
self._sslobj.do_handshake()
ssl.SSLZeroReturnError: TLS/SSL connection has been closed (EOF) (_ssl.c:997)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/urllib3/connectionpool.py", line 790, in urlopen
response = self._make_request(
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/urllib3/connectionpool.py", line 491, in _make_request
raise new_e
urllib3.exceptions.SSLError: TLS/SSL connection has been closed (EOF) (_ssl.c:997)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/requests/adapters.py", line 486, in send
resp = conn.urlopen(
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/urllib3/connectionpool.py", line 844, in urlopen
retries = retries.increment(
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/urllib3/util/retry.py", line 515, in increment
raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='fonts.googleapis.com', port=443): Max retries exceeded with url: /css?family=Roboto%20Mono:200 (Caused by SSLError(SSLZeroReturnError(6, 'TLS/SSL connection has been closed (EOF) (_ssl.c:997)')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/sphinx/events.py", line 97, in emit
results.append(listener.handler(self.app, *args))
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/sphinx_immaterial/google_fonts.py", line 198, in _builder_inited
add_google_fonts(app, list(font_options.values()))
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/sphinx_immaterial/google_fonts.py", line 173, in add_google_fonts
css_content = executor.submit(lambda: asyncio.run(do_fetch())).result()
File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result
return self.__get_result()
File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result
raise self._exception
File "/usr/lib/python3.10/concurrent/futures/thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/sphinx_immaterial/google_fonts.py", line 173, in <lambda>
css_content = executor.submit(lambda: asyncio.run(do_fetch())).result()
File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/sphinx_immaterial/google_fonts.py", line 166, in do_fetch
css_content = dict(zip(css_future_keys, await asyncio.gather(*css_futures)))
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/sphinx_immaterial/google_fonts.py", line 91, in fetch_font
zip(_FONT_FORMAT_USER_AGENT.keys(), await css_content_future)
File "/usr/lib/python3.10/concurrent/futures/thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/sphinx_immaterial/external_resource_cache.py", line 33, in get_url
r = requests.get( # pylint: disable=missing-timeout
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/requests/api.py", line 73, in get
return request("get", url, params=params, **kwargs)
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/requests/api.py", line 59, in request
return session.request(method=method, url=url, **kwargs)
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/requests/sessions.py", line 589, in request
resp = self.send(prep, **send_kwargs)
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/requests/sessions.py", line 703, in send
r = adapter.send(request, **kwargs)
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/requests/adapters.py", line 517, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='fonts.googleapis.com', port=443): Max retries exceeded with url: /css?family=Roboto%20Mono:200 (Caused by SSLError(SSLZeroReturnError(6, 'TLS/SSL connection has been closed (EOF) (_ssl.c:997)')))

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/sphinx/cmd/build.py", line 293, in build_main
app = Sphinx(args.sourcedir, args.confdir, args.outputdir,
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/sphinx/application.py", line 272, in __init__
self._init_builder()
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/sphinx/application.py", line 343, in _init_builder
self.events.emit('builder-inited')
File "/home/borntobealive/libs/pytest-copie/.nox/docs/lib/python3.10/site-packages/sphinx/events.py", line 108, in emit
raise ExtensionError(__("Handler %r for event %r threw an exception") %
sphinx.errors.ExtensionError: Handler <function _builder_inited at 0x7f2219f45870> for event 'builder-inited' threw an exception (exception: HTTPSConnectionPool(host='fonts.googleapis.com', port=443): Max retries exceeded with url: /css?family=Roboto%20Mono:200 (Caused by SSLError(SSLZeroReturnError(6, 'TLS/SSL connection has been closed (EOF) (_ssl.c:997)'))))

Extension error (sphinx_immaterial.google_fonts):
Handler <function _builder_inited at 0x7f2219f45870> for event 'builder-inited' threw an exception (exception: HTTPSConnectionPool(host='fonts.googleapis.com', port=443): Max retries exceeded with url: /css?family=Roboto%20Mono:200 (Caused by SSLError(SSLZeroReturnError(6, 'TLS/SSL connection has been closed (EOF) (_ssl.c:997)'))))

0 comments on commit 872a098

Please sign in to comment.