-
Notifications
You must be signed in to change notification settings - Fork 5
[MVP1][tk116] Alteração do módulo catalogmanager.persistence #117
base: master
Are you sure you want to change the base?
Conversation
- Criação de `insert_file` nos DBManagers - Criação de `ChangesService.register` com o novo conteúdo do registro de mudança - Criação de `DatabaseService.add_file` para persistir arquivos usando o DBManager e registrando a mudança com `ChangesService.register` - Ajustes nos fixtures para executar os testes sem duplicação - Testes unitários e de integração do módulo persistence para o novo registro de artigos
persistence/services.py
Outdated
| return change_record['record_id'] | ||
|
|
||
| def register(self, record_id, change_type): | ||
| sequencial = str(self.seqnum_generator.new()) |
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.
@patymori : sendo str, não corre o risco de a ordem válida ser 1, 10, 11 no lugar de 1, 2, 3?
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.
Essa dúvida deveria, idealmente, ser respondida por meio de testes de unidade ;)
| file_id: ID do arquivo | ||
| content: conteúdo do arquivo | ||
| """ | ||
| self.db_manager.insert_file(file_id=file_id, content=content) |
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.
@patymori : está sendo considerado que tanto os arquivos e os manifestos serão gravados usando o mesmo db_manager. Isso será disvinculado futuramente, correto?
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.
@robertatakenaka, isso foi um problema q eu decidi abordar de outra forma: estou pensando em gerenciar 2 db_managers diferentes, 1 para cada database
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.
@patymori ok, minha dúvida é 2 db_service (1 para cada db_manager) ou 1 db_service com 2 db_managers?
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.
Desculpe-me, @robertatakenaka, 2 db_services.
| db_service.db_manager.drop_database() | ||
| db_service.changes_service.changes_db_manager.drop_database() | ||
| try: | ||
| db_service.db_manager.drop_database() |
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.
@patymori : db_service deveria ter um drop_database para apagar em cascata.
|
|
||
|
|
||
| def test_register_create_change(database_service): | ||
| def test_register_change_create(database_service): |
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.
@patymori : sim fica melhor invertido
persistence/tests/test_changes.py
Outdated
| ) | ||
| assert change_id is not None | ||
| check_change = dict( | ||
| database_service.changes_service.changes_db_manager.database[change_id] |
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.
Por esta linha, me parece que deveríamos ter previsto um changes_service.get(change_id)
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.
Penso que não é necessário pois não faz sentido para a solução, visto que a aplicação não oferecerá consulta/leitura de uma mudança pelo ID, certo?
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.
ok
| file_id='href_file1', | ||
| content=xml_test.encode('utf-8') | ||
| ) | ||
| file = db_manager_test.database.get( |
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.
por que a recuperação do file não é db_manager_test.get_file(file_id)?
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.
Porque eu tava implementando só o incluir. Não existe ainda nessa implementação um recuperar arquivo pelo ID. Podemos refatorar esse teste quando ele existir, o que acha?
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.
sim
| changes_list[i]['change_id'] < changes_list[i + 1]['change_id'] | ||
| for i in range(len(changes_list) - 1) | ||
| ]) | ||
|
|
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.
@patymori : Referente às linhas 72 a 75:
Pode-se comparar também usando assert sorted(items) == items
Por curiosidade, fiz um teste de desempenho.
assert sorted(_items) == _items é mais eficiente.
Para 10 items, a diferença é irrelevante: 1s.
Para 100 items, a diferença é 66 - 38.
>>> t1 = datetime.now(); _items = [item['x'] for item in items];assert sorted(_items) == _items;t2 = datetime.now(); t = t2-t1;print(t); print(t1);print(t2)
0:00:00.000038
2018-06-18 08:41:37.630788
2018-06-18 08:41:37.630826
>>> t1 = datetime.now(); assert all([items[i]['x'] < items[i+1]['x'] for i in range(len(items)-1)]);t2 = datetime.now(); t = t2-t1;print(t); print(t1);print(t2)
0:00:00.000066
2018-06-18 08:41:51.818453
2018-06-18 08:41:51.818519
- Ajustes em `managers` para as mudanças em `persistence`. - Alteração do ArticleDocument para prever o registro de versões diferentes do artigo. - Ajuste do ArticleManager para as alterações do ArticleDocument, o gerenciamento de um DBManager para os arquivos brutos, e a implementação do método `add_document`. Ajuste do método post na view de artigo. - Criação de teste funcional para a funcionalidade de registro de novo artigo.
|
@patymori, você poderia resolver os conflitos? |
| from managers.article_manager import ArticleManager | ||
| from managers.exceptions import ManagerFileError | ||
| from managers.models.article_model import ArticleDocument | ||
| from managers.models.article_model import ArticleDocument, InvalidXMLContent |
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.
InvalidXMLContent é uma exceção. Não deveria estar baixo managers.exceptions?
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.
Criei managers.exceptions para ter somente as exceções que serão externalizadas, com o intensão de manter uma interface do que seria o módulo de persistência da aplicação WEB. Não sei se faz sentido.
gustavofonseca
left a comment
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.
Estes são comentários de uma revisão parcial. Vou continuar amanhã. Prometo ;)
Em geral eu diria que a implementação está boa. Só gostaria de chamar à atenção para o excesso de responsabilidades de alguns métodos como o ArticleDocument.add_version por exemplo.
managers/__init__.py
Outdated
|
|
||
|
|
||
| def _get_article_manager(**db_settings): | ||
| database_config = db_settings |
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.
aqui database_config não serve para nada, uma vez que as cópias das linhas 36 e 38 poderiam partir diretamente de db_settings
| codificado em XML | ||
| :rtype: str | ||
| """ | ||
| try: |
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.
Sugiro envolver na estrutura try..except o mínimo de código possível, i.e., apenas o que de fato tem o potencial de lançar a exceção que será tratada. Nessa função seria algo como:
article_manager = _get_article_manager(**db_settings)
article_document = ArticleDocument(article_id)
try:
article_document.add_version(xml_id, xml_file)
except InvalidXMLContent as e:
raise ManagerFileError(message=e.message) from e
else:
return article_manager.add_document(article_document)
| """ | ||
| xml_file = File(file_name="xml_file.xml", content=xml_content) | ||
| article = ArticleDocument(article_id, xml_file) | ||
| article = ArticleDocument(article_id) |
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.
Cheiro de inicialização incompleta de ArticleDocument
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.
ArticleDocument pode ser instanciado sem o conteúdo do XML, como ao recuperar o manifesto. Há a possibilidade de colocá-lo como um parâmetro não obrigatório. Melhor?
| article = ArticleDocument(article_id) | ||
| article.xml_file = xml_file | ||
| for name in article.assets: | ||
| if name in assets_filenames: |
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.
Não entendi a necessidade do argumento assets_filenames. O nome de identificação dos ativos digitais contigos no XML não podem ser obtidos inspecionando o próprio XML?
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.
Esse método só foi alterado por conta da alteração de ArticleDocument e vem de implementações antigas que, provavelmente, serão alteradas. Podemos criar algum comentário nesse ponto para lembrar de revisá-lo ou criamos uma issue de melhoria?
managers/models/article_model.py
Outdated
| self.xml_tree = ArticleXMLTree(xml_content) | ||
| if self.xml_tree.xml_error: | ||
| raise InvalidXMLContent | ||
| checksum = hashlib.sha1(xml_content).hexdigest() |
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.
checksum deveria ser um método de ArticleXMLTree
|
|
||
| def receive_xml_file(self, id, xml_file): | ||
| article = ArticleDocument(id, xml_file) | ||
| article = ArticleDocument(id) |
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.
Inicialização incompleta de ArticleDocument?
- Ajuste do `managers._get_article_manager` - Ajuste em `post_article` no tratamento de exceção e nos testes - Criada property `ArticleXMLTree.checksum`
Fixes #116.
insert_filenos DBManagersChangesService.registercom o novo conteúdo do registrode mudança
DatabaseService.add_filepara persistir arquivos usando oDBManager e registrando a mudança com
ChangesService.registerregistro de artigos