From fc9b03ebd71af05f7956a9cc9f7dad16d571bb01 Mon Sep 17 00:00:00 2001 From: Kasun Herath Date: Tue, 25 Apr 2023 10:10:07 +0530 Subject: [PATCH] Custom configuration support (#792) --- pynecone/compiler/templates.py | 5 ++++- pynecone/utils/prerequisites.py | 4 +++- tests/test_utils.py | 25 +++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/pynecone/compiler/templates.py b/pynecone/compiler/templates.py index 47e97c9a8..a5c24e7ce 100644 --- a/pynecone/compiler/templates.py +++ b/pynecone/compiler/templates.py @@ -8,7 +8,10 @@ from pynecone.utils import path_ops # Template for the Pynecone config file. PCCONFIG = f"""import pynecone as pc -config = pc.Config( +class {{config_name}}(pc.Config): + pass + +config = {{config_name}}( app_name="{{app_name}}", db_url="{constants.DB_URL}", env=pc.Env.DEV, diff --git a/pynecone/utils/prerequisites.py b/pynecone/utils/prerequisites.py index 533f327cd..9b990ee7c 100644 --- a/pynecone/utils/prerequisites.py +++ b/pynecone/utils/prerequisites.py @@ -5,6 +5,7 @@ from __future__ import annotations import json import os import platform +import re import subprocess import sys from pathlib import Path @@ -147,8 +148,9 @@ def create_config(app_name: str): # Import here to avoid circular imports. from pynecone.compiler import templates + config_name = f"{re.sub(r'[^a-zA-Z]', '', app_name).capitalize()}Config" with open(constants.CONFIG_FILE, "w") as f: - f.write(templates.PCCONFIG.format(app_name=app_name)) + f.write(templates.PCCONFIG.format(app_name=app_name, config_name=config_name)) def create_web_directory(root: Path) -> str: diff --git a/tests/test_utils.py b/tests/test_utils.py index c541f9b94..58630cc39 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -312,3 +312,28 @@ def test_format_upload_event(upload_event_spec): 'upload_state.files, "upload_state.handle_upload1",' "UPLOAD)" ) + + +@pytest.mark.parametrize( + "app_name,expected_config_name", + [ + ("appname", "AppnameConfig"), + ("app_name", "AppnameConfig"), + ("app-name", "AppnameConfig"), + ("appname2.io", "AppnameioConfig"), + ], +) +def test_create_config(app_name, expected_config_name, mocker): + """Test templates.PCCONFIG is formatted with correct app name and config class name. + + Args: + app_name: App name. + expected_config_name: Expected config name. + mocker: Mocker object. + """ + mocker.patch("builtins.open") + tmpl_mock = mocker.patch("pynecone.compiler.templates.PCCONFIG") + prerequisites.create_config(app_name) + tmpl_mock.format.assert_called_with( + app_name=app_name, config_name=expected_config_name + )