Files
public/directive_layer/tests/test_directive_layer.py

120 lines
5.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from odoo.tests.common import TransactionCase, tagged
# post_install (НЕ at_install): обе политики опираются на project.task с
# примешанным directive.mixin и на метод action_demo_directive_callback, которые
# определены в companion-модуле directive_common. at_install прогонял бы эти тесты
# в фазе установки directive_layer — ДО загрузки directive_common, когда project.task
# ещё не перехватывает write/callback. post_install гарантирует, что оба модуля уже
# загружены (design 7.2).
@tagged('standard', '-at_install', 'post_install', 'directive_logic')
class TestDirectivePolicy(TransactionCase):
def setUp(self):
"""
Метод запускается перед каждым тестом.
Гарантирует изоляцию данных: каждый тест работает с новой задачей и новой политикой.
"""
super(TestDirectivePolicy, self).setUp()
self.work_type = self.env['directive.work.type'].create({
'name': 'Development',
'code': 'dev'
})
self.stage_draft = self.env['directive.stage'].search([('code', '=', 'draft')], limit=1)
if not self.stage_draft:
self.stage_draft = self.env['directive.stage'].create({'name': 'Draft', 'code': 'draft'})
self.template = self.env['directive.template'].create({
'name': 'Шаблон авто-задачи',
'code': 'T001',
'work_type_id': self.work_type.id,
'planned_hours': 5.0,
})
self.template_group = self.env['directive.template.group'].create({
'name': 'Test Group',
'template_line_ids': [(0, 0, {'template_id': self.template.id})]
})
self.policy_callback = self.env['directive.policy'].create({
'name': 'On Callback Policy',
'origin_model': 'project.task',
'event': 'on_callback',
'trigger_field': 'action_demo_directive_callback',
'mode': 'create_once',
'use_record_template_group': False,
'template_group_id': self.template_group.id,
})
self.policy_write = self.env['directive.policy'].create({
'name': 'On Write Policy',
'origin_model': 'project.task',
'event': 'on_write',
'trigger_field': 'color',
'trigger_value_int': 5,
'mode': 'create_once',
'use_record_template_group': False,
'template_group_id': self.template_group.id,
})
self.task = self.env['project.task'].create({
'name': 'Source Task',
'color': 0,
})
def test_01_policy_on_write(self):
"""Тест генерации директивы при изменении поля (on_write)"""
self.task.write({'color': 5})
directives = self.env['directive.directive'].search([
('origin_id.res_model', '=', 'project.task'),
('origin_id.res_id', '=', self.task.id),
('policy_id', '=', self.policy_write.id)
])
self.assertEqual(len(directives), 1, "Директива не создалась через on_write!")
self.assertEqual(directives.name, 'Шаблон авто-задачи', "Имя перенеслось неверно")
self.assertEqual(directives.planned_hours, 5.0, "Трудоемкость перенеслась неверно")
# Проверка create_once
self.task.write({'color': 0})
self.task.write({'color': 5})
directives_count = self.env['directive.directive'].search_count([
('origin_id.res_model', '=', 'project.task'),
('origin_id.res_id', '=', self.task.id),
('policy_id', '=', self.policy_write.id)
])
self.assertEqual(directives_count, 1, "Сломался create_once! Создался дубль директивы.")
def test_02_policy_on_callback(self):
"""Тест генерации директивы при вызове метода (on_callback).
Механизм теперь ЯВНЫЙ: project.task.action_demo_directive_callback
(directive_common) сам вызывает self._directive_run_callback_policies(
"action_demo_directive_callback") после message_post (FEAT-003) — это НЕ
monkey-patch. Контекст-гард directive_skip_generation не используется.
Ассерты API не изменились относительно as-is.
"""
self.task.action_demo_directive_callback()
directives = self.env['directive.directive'].search([
('origin_id.res_model', '=', 'project.task'),
('origin_id.res_id', '=', self.task.id),
('policy_id', '=', self.policy_callback.id)
])
self.assertEqual(len(directives), 1, "Директива не создалась через on_callback!")
# Проверка create_once
self.task.action_demo_directive_callback()
directives_count = self.env['directive.directive'].search_count([
('origin_id.res_model', '=', 'project.task'),
('origin_id.res_id', '=', self.task.id),
('policy_id', '=', self.policy_callback.id)
])
self.assertEqual(directives_count, 1, "Сломался create_once для методов! Создался дубль.")