|
| 1 | +import traceback |
| 2 | +from pathlib import Path |
| 3 | +from unittest import TestCase |
| 4 | + |
| 5 | +from pyttman.core.decorators import LifeCycleHookType |
| 6 | +from pyttman.core.exceptions import PyttmanProjectInvalidException |
| 7 | +from pyttman.tools.pyttmancli import bootstrap_app |
| 8 | + |
| 9 | + |
| 10 | +class PyttmanTestCase(TestCase): |
| 11 | + devmode = False |
| 12 | + application_abspath = None |
| 13 | + app_name = None |
| 14 | + override_devmode_warning = False |
| 15 | + |
| 16 | + def __init__(self, *args, **kwargs): |
| 17 | + if self.application_abspath is None: |
| 18 | + self.application_abspath = self.find_app_path() |
| 19 | + if self.app_name is None: |
| 20 | + self.app_name = self.application_abspath.name |
| 21 | + |
| 22 | + try: |
| 23 | + self.app = bootstrap_app( |
| 24 | + devmode=self.devmode, |
| 25 | + module=self.app_name, |
| 26 | + application_abspath=self.application_abspath.parent) |
| 27 | + except Exception as e: |
| 28 | + print(traceback.format_exc()) |
| 29 | + raise PyttmanProjectInvalidException( |
| 30 | + "\n\nPyttman could not boostrap the application for " |
| 31 | + "testing. Full traceback above" |
| 32 | + ) from e |
| 33 | + |
| 34 | + super().__init__(*args, **kwargs) |
| 35 | + if not any((self.devmode, self.app.settings.DEV_MODE, self.override_devmode_warning)): |
| 36 | + raise Warning("Warning! This test class does not declare 'devmode' as a " |
| 37 | + "True, and 'DEV_MODE' in settings.py for " |
| 38 | + "this app is False. This could potentially lead to " |
| 39 | + "a test executing to production environment. " |
| 40 | + "To override this warning, set 'override_devmode_warning = True' " |
| 41 | + "as a class variable in this unit test.") |
| 42 | + self.app.settings.DEV_MODE = self.devmode |
| 43 | + self.app.hooks.trigger(LifeCycleHookType.before_start) |
| 44 | + |
| 45 | + @staticmethod |
| 46 | + def find_app_path(start_dir: Path = None) -> Path: |
| 47 | + """ |
| 48 | + Look for signature catalog which looks like a |
| 49 | + Pyttman app root directory. |
| 50 | +
|
| 51 | + Walk up the file structure until the directory is found. |
| 52 | + :raise ModuleNotFoundError: The file hierarchy was exhausted |
| 53 | + and no pyttman app directory wasn't found |
| 54 | + """ |
| 55 | + sought_file = "settings.py" |
| 56 | + start_dir = start_dir or Path.cwd() |
| 57 | + next_dir = start_dir |
| 58 | + while not next_dir.joinpath(sought_file).exists(): |
| 59 | + if next_dir.parent == start_dir: |
| 60 | + raise ModuleNotFoundError( |
| 61 | + "Could not find a Pyttman app in the " |
| 62 | + "same directory as the test, or in any " |
| 63 | + "parent folder above it. Is the test " |
| 64 | + "module placed in a Pyttman application?") |
| 65 | + next_dir = next_dir.parent |
| 66 | + return next_dir |
0 commit comments