-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Categorize cli errors with fix suggestions (us01/us02) #12414
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
arthur-wolff
wants to merge
8
commits into
inventree:master
Choose a base branch
from
Kelvinmilagres:categorize-CLI-errors-with-fix-suggestions-(US01/US02)
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+187
−12
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2746b0f
adding folders
Kelvinmilagres cd00728
adding documentation
Kelvinmilagres 5b92331
adding
Kelvinmilagres b0f9eb8
Merge branch 'inventree:master' into master
arthur-wolff 1b46e33
`feat(cli): categorizar erros da CLI com sugestão de correção (US01/U…
arthur-wolff 29de116
Update tasks.py
arthur-wolff 0313d0a
Delete documentacao directory
arthur-wolff 3670813
Merge branch 'master' into categorize-CLI-errors-with-fix-suggestions…
matmair File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
| from enum import Enum | ||
| from typing import Optional | ||
|
|
||
|
|
||
| class ErrorCategory(str, Enum): | ||
|
|
||
|
|
||
| BANCO_DE_DADOS = 'BANCO_DE_DADOS' | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please use English for these error categories |
||
| REDE = 'REDE' | ||
| PERMISSAO = 'PERMISSAO' | ||
| AMBIENTE = 'AMBIENTE' | ||
| SISTEMA_DESCONHECIDO = 'SISTEMA_DESCONHECIDO' | ||
|
|
||
|
|
||
|
|
||
| _DEFAULT_MESSAGES = { | ||
| ErrorCategory.SISTEMA_DESCONHECIDO: 'Ocorreu uma falha interna inesperada', | ||
| } | ||
|
|
||
|
|
||
| _SUGGESTIONS = { | ||
| ErrorCategory.PERMISSAO: "Execute 'chmod +w <arquivo>' ou ajuste as permissoes do diretorio", | ||
| ErrorCategory.AMBIENTE: "Execute 'invoke install' para reinstalar as dependencias corretas", | ||
| ErrorCategory.BANCO_DE_DADOS: 'Verifique se o servico de banco de dados esta ativo e acessivel', | ||
| ErrorCategory.REDE: 'Verifique a conectividade de rede e as credenciais do endpoint remoto', | ||
| } | ||
|
|
||
|
|
||
| @dataclass | ||
| class StructuredError: | ||
|
|
||
|
|
||
| category: ErrorCategory | ||
| message: str | ||
| suggestion: Optional[str] = None | ||
|
|
||
|
|
||
| class ExceptionCategorizer: | ||
|
|
||
| _TYPE_NAME_MAP = { | ||
| 'OperationalError': ErrorCategory.BANCO_DE_DADOS, | ||
| 'InterfaceError': ErrorCategory.BANCO_DE_DADOS, | ||
| 'DatabaseError': ErrorCategory.BANCO_DE_DADOS, | ||
| 'PermissionError': ErrorCategory.PERMISSAO, | ||
| 'ModuleNotFoundError': ErrorCategory.AMBIENTE, | ||
| 'ImportError': ErrorCategory.AMBIENTE, | ||
| 'ConnectionError': ErrorCategory.REDE, | ||
| 'ConnectionRefusedError': ErrorCategory.REDE, | ||
| 'TimeoutError': ErrorCategory.REDE, | ||
| 'URLError': ErrorCategory.REDE, | ||
| } | ||
|
|
||
|
|
||
| _KEYWORD_MAP = ( | ||
| (('porta', 'connection refused', 'database', 'banco de dados'), ErrorCategory.BANCO_DE_DADOS), | ||
| (('network', 'rede', 'timeout', 'dns'), ErrorCategory.REDE), | ||
| (('permission', 'permissao', 'read-only', 'access is denied'), ErrorCategory.PERMISSAO), | ||
| ) | ||
|
|
||
| def classify(self, exc: BaseException) -> ErrorCategory: | ||
|
|
||
| type_name = type(exc).__name__ | ||
| if type_name in self._TYPE_NAME_MAP: | ||
| return self._TYPE_NAME_MAP[type_name] | ||
|
|
||
| message = str(exc).lower() | ||
| for keywords, category in self._KEYWORD_MAP: | ||
| if any(keyword in message for keyword in keywords): | ||
| return category | ||
|
|
||
| return ErrorCategory.SISTEMA_DESCONHECIDO | ||
|
|
||
|
|
||
| class SuggestionProvider: | ||
|
|
||
|
|
||
| def get_suggestion(self, category: ErrorCategory) -> Optional[str]: | ||
|
|
||
| return _SUGGESTIONS.get(category) | ||
|
|
||
|
|
||
| def build_structured_error( | ||
| exc: BaseException, | ||
| categorizer: Optional[ExceptionCategorizer] = None, | ||
| suggestion_provider: Optional[SuggestionProvider] = None, | ||
| ) -> StructuredError: | ||
|
|
||
| categorizer = categorizer or ExceptionCategorizer() | ||
| suggestion_provider = suggestion_provider or SuggestionProvider() | ||
|
|
||
| category = categorizer.classify(exc) | ||
| message = str(exc).strip() or _DEFAULT_MESSAGES.get( | ||
| category, 'Ocorreu uma falha inesperada' | ||
| ) | ||
|
|
||
| return StructuredError( | ||
| category=category, | ||
| message=message, | ||
| suggestion=suggestion_provider.get_suggestion(category), | ||
| ) | ||
|
|
||
|
|
||
| def format_structured_error(error: StructuredError) -> str: | ||
|
|
||
| lines = [f'[ERRO: {error.category.value}] {error.message}'] | ||
| if error.suggestion: | ||
| lines.append(f'SUGESTAO: {error.suggestion}') | ||
| return '\n'.join(lines) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| """Tests for cli_error_handling.py (US01 / US02). | ||
|
|
||
| These mirror the test scenarios documented in | ||
| documentacao/cenarios_de_teste. | ||
| """ | ||
|
|
||
| from cli_error_handling import ( | ||
| ErrorCategory, | ||
| build_structured_error, | ||
| format_structured_error, | ||
| ) | ||
|
|
||
|
|
||
| class FakeOperationalError(Exception): | ||
| """Stand-in for a DB driver's OperationalError (avoids a psycopg2 dependency in tests).""" | ||
|
|
||
|
|
||
| FakeOperationalError.__name__ = 'OperationalError' | ||
|
|
||
|
|
||
| def test_us01_dados_validos_categoriza_erro_de_banco(): | ||
| """Cenario: queda do banco simulada -> [ERRO: BANCO_DE_DADOS] ...""" | ||
| exc = FakeOperationalError('Falha de conexao na porta 5432') | ||
| result = build_structured_error(exc) | ||
|
|
||
| assert result.category == ErrorCategory.BANCO_DE_DADOS | ||
| output = format_structured_error(result) | ||
| assert output.startswith('[ERRO: BANCO_DE_DADOS] Falha de conexao na porta 5432') | ||
|
|
||
|
|
||
| def test_us01_excecao_nao_mapeada_cai_em_sistema_desconhecido(): | ||
| """Cenario: erro desconhecido -> [ERRO: SISTEMA_DESCONHECIDO] ...""" | ||
| exc = RuntimeError('') # sem mensagem, tipo nao mapeado | ||
| result = build_structured_error(exc) | ||
|
|
||
| assert result.category == ErrorCategory.SISTEMA_DESCONHECIDO | ||
| assert format_structured_error(result) == ( | ||
| '[ERRO: SISTEMA_DESCONHECIDO] Ocorreu uma falha interna inesperada' | ||
| ) | ||
|
|
||
|
|
||
| def test_us02_categoria_com_solucao_conhecida_exibe_sugestao(): | ||
| """Cenario: erro de escrita -> linha SUGESTAO: ... e' anexada.""" | ||
| exc = PermissionError('Arquivo de config ilegivel') | ||
| result = build_structured_error(exc) | ||
| output = format_structured_error(result) | ||
|
|
||
| assert output == ( | ||
| '[ERRO: PERMISSAO] Arquivo de config ilegivel\n' | ||
| "SUGESTAO: Execute 'chmod +w <arquivo>' ou ajuste as permissoes do diretorio" | ||
| ) | ||
|
|
||
|
|
||
| def test_us02_categoria_sem_solucao_omite_linha_de_sugestao(): | ||
| """Cenario: erro sem tratativa cadastrada -> omite a linha de sugestao.""" | ||
| exc = RuntimeError('falha nao mapeada qualquer') | ||
| result = build_structured_error(exc) | ||
| output = format_structured_error(result) | ||
|
|
||
| assert 'SUGESTAO' not in output | ||
|
|
||
|
|
||
| def test_ambiente_reaproveita_categoria_ja_tratada_pelo_task_exception_handler(): | ||
| """ModuleNotFoundError ja era tratado manualmente em tasks.py; garante | ||
| que a nova categorizacao cobre o mesmo caso sem duplicar logica. | ||
| """ | ||
| exc = ModuleNotFoundError("No module named 'invoke'") | ||
| result = build_structured_error(exc) | ||
|
|
||
| assert result.category == ErrorCategory.AMBIENTE |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This code should be refactored into
tasks.pyto reduce the number of top-level files