Skip to content
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

Refactor: table wrap validation #765

Merged
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
a4ee1c0
Adiciona níveis de erro para 'table-wrap'
Rossi-Luciano Nov 26, 2024
5764ab3
Remove código obsoleto
Rossi-Luciano Nov 26, 2024
e892f5d
Adiciona classe
Rossi-Luciano Nov 26, 2024
1574f8b
Adiciona construtor com tratamento de exceções para cada parâmetro
Rossi-Luciano Nov 26, 2024
f67a1c5
Adiciona função de validação
Rossi-Luciano Nov 26, 2024
29e803d
Verifica se não há tabelas no artigo
Rossi-Luciano Nov 26, 2024
dda73ac
Valida cada tabela encontrada
Rossi-Luciano Nov 26, 2024
0752a97
Remove código obsoleto
Rossi-Luciano Nov 26, 2024
975c88d
Adiciona classe para validação de cada tabela individualmente
Rossi-Luciano Nov 26, 2024
607e943
Adiciona construtor com tratamento de exceção para 'data'
Rossi-Luciano Nov 26, 2024
efcf989
Adiciona função para validar os atributos individualmente
Rossi-Luciano Nov 26, 2024
c828c0c
Adiciona validação de atributos
Rossi-Luciano Nov 26, 2024
65a62ec
Atualiza importações
Rossi-Luciano Nov 26, 2024
c474cb4
Adiciona teste para ausência de tabela
Rossi-Luciano Nov 26, 2024
471de20
Adiciona teste para validação de 'id'
Rossi-Luciano Nov 26, 2024
fbe39d0
Adiciona teste para validação de 'label'
Rossi-Luciano Nov 26, 2024
7fc2e55
Adiciona teste para a validação de 'caption'
Rossi-Luciano Nov 26, 2024
da7488b
Corrige chave do dicionário
Rossi-Luciano Nov 27, 2024
e259282
Adiciona 'title'
Rossi-Luciano Nov 27, 2024
b0c7854
Adapta teste
Rossi-Luciano Nov 27, 2024
6fa5770
Corrige para o uso de lxml
Rossi-Luciano Dec 7, 2024
6eef98e
Adiciona 'table' e 'graphic'
Rossi-Luciano Dec 7, 2024
b51679c
Complementa os dados
Rossi-Luciano Dec 7, 2024
15b8329
Simplifica os exemplos de teste e adiciona 'table' e 'graphic'
Rossi-Luciano Dec 7, 2024
bbff647
Individualiza as chamadas para as validações
Rossi-Luciano Dec 7, 2024
6a8ae19
Individualiza as validações
Rossi-Luciano Dec 7, 2024
4758356
Complementa 'tablewrap.json'
Rossi-Luciano Dec 7, 2024
eb0c5bc
Adapta e adiciona testes
Rossi-Luciano Dec 7, 2024
e11048c
Aplica formatação (black)
Rossi-Luciano Dec 7, 2024
0d4890b
Atualiza importações
Rossi-Luciano Dec 22, 2024
4fa154a
Remove funções obsoletas
Rossi-Luciano Dec 22, 2024
473c894
Adiciona 'table_wrap_foot'
Rossi-Luciano Dec 22, 2024
1189d3d
Corrige retorno da função
Rossi-Luciano Dec 22, 2024
89ce1a1
Atualiza 'data'
Rossi-Luciano Dec 22, 2024
9e0ed08
Adiciona exemplo mais real
Rossi-Luciano Dec 22, 2024
27bc861
Corrige nome dos atributos
Rossi-Luciano Dec 22, 2024
0965c5e
Adequa nome de atributo
Rossi-Luciano Dec 22, 2024
7c1c09b
Adequa nome de atributo
Rossi-Luciano Dec 22, 2024
d7203b4
Adequa nome de atributo
Rossi-Luciano Dec 22, 2024
58cad6d
Adiciona exemplo mais real
Rossi-Luciano Dec 22, 2024
4849aff
Adequa nome de atributo
Rossi-Luciano Dec 22, 2024
4cefeb8
Modifica para lista de 'footnotes'
Rossi-Luciano Dec 22, 2024
6f71ae1
Modifica validação de 'alternatives'
Rossi-Luciano Dec 22, 2024
1308c13
Adequa testes de validação
Rossi-Luciano Dec 22, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 87 additions & 52 deletions packtools/sps/validation/tablewrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,41 @@
from packtools.sps.validation.utils import format_response


class TableWrapValidation:
def __init__(self, xmltree):
self.xmltree = xmltree
self.table_wrappers = list(ArticleTableWrappers(xmltree).get_all_table_wrappers)
class ArticleTableWrapValidation:
"""
Validates the <table-wrap> elements in an XML article.

def validate_tablewrap_existence(self, error_level="WARNING"):
if self.table_wrappers:
for table_wrap_data in self.table_wrappers:
yield format_response(
title="table-wrap presence",
parent=table_wrap_data.get("parent"),
parent_id=table_wrap_data.get("parent_id"),
parent_article_type=table_wrap_data.get("parent_article_type"),
parent_lang=table_wrap_data.get("parent_lang"),
item="table-wrap",
sub_item=None,
validation_type="exist",
is_valid=True,
expected="<table-wrap> element",
obtained=f'<table-wrap id="{table_wrap_data.get("table_wrap_id")}">',
advice=None,
data=table_wrap_data,
error_level="OK",
)
else:
Args:
xml_tree: XML object representing the article.
rules: Dictionary containing validation rules.
"""

def __init__(self, xml_tree, rules):
if not hasattr(xml_tree, "get"):
raise ValueError("xml_tree must be a valid XML object.")
if not isinstance(rules, dict):
raise ValueError("rules must be a dictionary containing error levels.")
try:
self.elements = list(ArticleTableWrappers(xml_tree).get_all_table_wrappers)
except Exception as e:
raise RuntimeError(f"Error processing table-wraps: {e}")
self.xml_tree = xml_tree
self.rules = rules

def validate(self):
"""
Performs validations on the article.
Returns a generator with validation results.
"""
if not self.elements:
yield format_response(
title="table-wrap presence",
parent="article",
parent_id=None,
parent_article_type=self.xmltree.get("article-type"),
parent_lang=self.xmltree.get("{http://www.w3.org/XML/1998/namespace}lang"),
parent_article_type=self.xml_tree.get("article-type"),
parent_lang=self.xml_tree.get(
"{http://www.w3.org/XML/1998/namespace}lang"
),
item="table-wrap",
sub_item=None,
validation_type="exist",
Expand All @@ -41,31 +45,62 @@ def validate_tablewrap_existence(self, error_level="WARNING"):
obtained=None,
advice="Add <table-wrap> element to properly illustrate the content.",
data=None,
error_level=error_level,
error_level=self.rules["absent_error_level"],
)
else:
for element in self.elements:
yield from TableWrapValidation(element, self.rules).validate()


class TableWrapValidation:
"""
Validates the attributes of a <table-wrap> element.

Args:
data: Dictionary containing the element's data.
rules: Dictionary containing validation rules.
"""

def validate_tablewrap_elements(self, error_level="ERROR"):
if self.table_wrappers:
for table_wrap_data in self.table_wrappers:
elements_found = []
for element in ["table_wrap_id", "label", "caption"]:
value = table_wrap_data.get(element)
if value:
elements_found.append(value)
if not bool(elements_found):
yield format_response(
title="table-wrap elements",
parent=table_wrap_data.get("parent"),
parent_id=table_wrap_data.get("parent_id"),
parent_article_type=table_wrap_data.get("parent_article_type"),
parent_lang=table_wrap_data.get("parent_lang"),
item="table-wrap",
sub_item="table-wrap/@id or label or caption",
validation_type="exist",
is_valid=False,
expected="table-wrap/@id or label or caption elements",
obtained=elements_found,
advice="provide table-wrap/@id or label or caption for table-wrap",
data=table_wrap_data,
error_level=error_level,
)
def __init__(self, data, rules):
if not isinstance(data, dict):
raise ValueError("data must be a dictionary.")
self.data = data
self.rules = rules

def validate(self):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Rossi-Luciano crie métodos explícitos para validar cada componente da tabela: validate_label, validate_id, validate_caption, etc

"""
Validates the attributes of the <table-wrap>.
Returns a generator with validation results.
"""
for name, title in (("table_wrap_id", "id"), ("label", "label"), ("caption", "caption")):
if resp := self._validate_item(name, title):
yield resp

def _validate_item(self, name, title):
"""
Validates the presence of an attribute in the <table-wrap>.

Args:
name: Name of the attribute to validate.

Returns:
The validation result in the expected format.
"""
if not self.data.get(name):
key_error_level = f"{title}_error_level"
return format_response(
title=title,
parent=self.data.get("parent"),
parent_id=self.data.get("parent_id"),
parent_article_type=self.data.get("parent_article_type"),
parent_lang=self.data.get("parent_lang"),
item="table-wrap",
sub_item=title,
validation_type="exist",
is_valid=False,
expected=title,
obtained=None,
advice=f"Identify the {title}",
data=self.data,
error_level=self.rules[key_error_level],
)
8 changes: 8 additions & 0 deletions packtools/sps/validation_rules/tablewrap.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"table_wrap_rules": {
"absent_error_level": "WARNING",
"id_error_level": "CRITICAL",
"label_error_level": "CRITICAL",
"caption_error_level": "CRITICAL"
}
}
Loading