File size: 31,537 Bytes
c1f3d83 8d155aa 921d283 c1f3d83 8d155aa 921d283 c1f3d83 8d155aa c1f3d83 6faed22 666f897 0e2212c 5fdf138 d904a25 f6ab2f2 d904a25 f6ab2f2 d904a25 f6ab2f2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 | """What the surroundings of a file say, without asking a model to guess.
This is the layer that used to return PASS having checked nothing, so it is
worth knowing exactly what it can and cannot establish from a real directory
tree rather than from a hand-built dict.
"""
import json
import pytest
import context
def module(tmp_path, version="18.0.1.0.0", manifest=True):
"""A minimal Odoo addon: manifest at the root, source a directory down."""
root = tmp_path / "addons" / "my_module"
(root / "models").mkdir(parents=True)
if manifest:
(root / "__manifest__.py").write_text(
"{'name': 'My Module', 'version': '%s'}" % version, encoding="utf-8")
target = root / "models" / "sale_order_line.py"
target.write_text("from odoo import api, models\n", encoding="utf-8")
return target
def test_the_reviewable_extensions_are_the_ones_the_corpus_has_rules_for(tmp_path):
""".py holds every rule but one; .xml holds the noupdate rule, whose
violation is a <record> in a data file. Both answer with the one stack."""
for name in ("a.py", "views.xml"):
assert context.stack_for(str(tmp_path / name)) == "odoo"
def test_a_file_in_another_language_is_not_routed_anywhere(tmp_path):
"""None, not a stack. Running 27 Odoo rules over a .ts file produces an
empty finding list, and an empty finding list reads as a clean bill of
health -- so the router refuses instead, and subject.route raises."""
for name in ("a.ts", "a.tsx", "a.mts", "a.js", "a.jsx", "a.mjs",
"a.go", "a.unknown"):
assert context.stack_for(str(tmp_path / name)) is None
def test_the_caller_that_read_the_file_can_say_which_stack(tmp_path):
ctx = context.from_file(str(module(tmp_path)), stack="odoo")
assert ctx["stack"] == "odoo"
assert ctx["odoo_series"] == "18.0", "and the odoo facts are still gathered"
def test_manifest_is_found_by_walking_up(tmp_path):
"""The manifest sits two directories above the file being checked."""
ctx = context.from_file(str(module(tmp_path)))
assert ctx["source"] == "file"
assert ctx["odoo_series"] == "18.0"
assert ctx["manifest"].endswith("__manifest__.py")
def test_no_manifest_leaves_the_series_unknown(tmp_path):
"""A plain Python file in no addon at all. The series is not guessed, and
the absence is what `nexa check` now warns about."""
ctx = context.from_file(str(module(tmp_path, manifest=False)))
assert ctx["odoo_series"] is None
assert not ctx["manifest"]
def test_manifest_without_a_version_is_not_a_series(tmp_path):
root = tmp_path / "addons" / "m"
root.mkdir(parents=True)
(root / "__manifest__.py").write_text("{'name': 'M'}", encoding="utf-8")
target = root / "x.py"
target.write_text("x = 1", encoding="utf-8")
ctx = context.from_file(str(target))
assert ctx["odoo_series"] is None
@pytest.mark.parametrize("version,series", [
("18.0.1.0.0", "18.0"),
("17.0.2.1.3", "17.0"),
("16.0.1.0.0", "16.0"),
])
def test_series_is_the_first_two_components(tmp_path, version, series):
ctx = context.from_file(str(module(tmp_path, version=version)))
assert ctx["odoo_series"] == series
def test_empty_context_declares_that_it_has_no_file():
ctx = context.empty("odoo")
assert ctx["source"] == "none"
assert ctx["stack"] == "odoo"
assert ctx["odoo_series"] is None
def test_describe_reports_only_what_was_established(tmp_path):
facts = context.describe(context.from_file(str(module(tmp_path))))
assert any("18.0" in f for f in facts)
assert context.describe(context.empty("odoo")) == []
def test_unreadable_file_does_not_raise(tmp_path):
"""from_file runs before anything else in `nexa check`; an exception here
would take down the command rather than report a gap."""
ctx = context.from_file(str(tmp_path / "does_not_exist.py"))
assert ctx["stack"] == "odoo"
assert ctx["odoo_series"] is None
# -------------------------------------------------------------- tree triggers
MODEL_WITH_A_PARENT = """from odoo import fields, models
class Thing(models.Model):
_name = 'my.thing'
parent_id = fields.Many2one('my.parent')
def label(self):
return self.parent_id.name
"""
PARENT_DECLARED = """from odoo import models
class Parent(models.Model):
_name = 'my.parent'
"""
PARENT_DELETED = PARENT_DECLARED + """
class Cleaner(models.Model):
_name = 'my.cleaner'
def purge(self):
self.env['my.parent'].search([]).unlink()
"""
def tree(tmp_path, files):
root = tmp_path / "addons" / "mod"
root.mkdir(parents=True)
(root / "__manifest__.py").write_text("{'name': 'Mod'}", encoding="utf-8")
for name, body in files.items():
path = root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body, encoding="utf-8")
return root
def paths_under(root):
import os
for dirpath, _dirnames, filenames in os.walk(str(root)):
for name in sorted(filenames):
yield os.path.join(dirpath, name)
def test_a_model_nobody_deletes_reads_absent(tmp_path):
"""The trigger the ondelete rule is conditional on. The tree defines the
parent and never deletes it, so there is no dangling read to have."""
root = tree(tmp_path, {"thing.py": MODEL_WITH_A_PARENT,
"parent.py": PARENT_DECLARED})
facts = context.tree_facts(paths_under(root))
assert context.parent_is_deleted(facts, "my.parent") == context.ABSENT
def test_a_model_the_tree_unlinks_reads_present(tmp_path):
root = tree(tmp_path, {"thing.py": MODEL_WITH_A_PARENT,
"parent.py": PARENT_DELETED})
facts = context.tree_facts(paths_under(root))
assert context.parent_is_deleted(facts, "my.parent") == context.PRESENT
def test_an_access_rule_granting_unlink_counts_as_a_delete(tmp_path):
"""Nothing in the Python deletes it, but somebody can through the UI. That
is the half of the question reading Python can never answer."""
csv = ("id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,"
"perm_unlink\naccess_p,p,model_my_parent,base.group_user,1,1,1,1\n")
root = tree(tmp_path, {"thing.py": MODEL_WITH_A_PARENT,
"parent.py": PARENT_DECLARED,
"security/ir.model.access.csv": csv})
facts = context.tree_facts(paths_under(root))
assert context.parent_is_deleted(facts, "my.parent") == context.PRESENT
def test_an_access_rule_refusing_unlink_leaves_it_absent(tmp_path):
csv = ("id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,"
"perm_unlink\naccess_p,p,model_my_parent,base.group_user,1,1,1,0\n")
root = tree(tmp_path, {"thing.py": MODEL_WITH_A_PARENT,
"parent.py": PARENT_DECLARED,
"security/ir.model.access.csv": csv})
facts = context.tree_facts(paths_under(root))
assert context.parent_is_deleted(facts, "my.parent") == context.ABSENT
def test_a_foreign_model_reads_unknown_however_much_was_walked(tmp_path):
"""res.partner is core Odoo's. The delete could be anywhere in a codebase
this walk never saw, so the honest answer is not 'absent'."""
root = tree(tmp_path, {"thing.py": MODEL_WITH_A_PARENT})
facts = context.tree_facts(paths_under(root))
assert context.parent_is_deleted(facts, "res.partner") == context.UNKNOWN
def test_an_incomplete_walk_can_promote_but_never_suppress(tmp_path):
"""A module-sized walk cannot see the other module doing the deleting, so
it is allowed to raise a finding and never to drop one."""
root = tree(tmp_path, {"thing.py": MODEL_WITH_A_PARENT,
"parent.py": PARENT_DECLARED})
partial = context.tree_facts(paths_under(root), complete=False)
assert context.parent_is_deleted(partial, "my.parent") == context.UNKNOWN
root2 = tree(tmp_path / "other", {"parent.py": PARENT_DELETED})
promoting = context.tree_facts(paths_under(root2), complete=False)
assert context.parent_is_deleted(promoting, "my.parent") == context.PRESENT
def test_no_tree_answers_unknown_to_everything():
"""`nexa check` on a bare path. Nothing was walked, so nothing is claimed."""
facts = context.no_tree()
assert context.parent_is_deleted(facts, "my.parent") == context.UNKNOWN
assert context.multi_company_in_use(facts) == context.UNKNOWN
assert context.parent_is_deleted(None, "my.parent") == context.UNKNOWN
def test_multi_company_needs_more_than_a_company_id(tmp_path):
"""Nearly every Odoo model declares a company_id, in single- and
multi-company deployments alike, so it separates nothing."""
single = tree(tmp_path, {"a.py": "company_id = fields.Many2one('res.company')"})
assert context.multi_company_in_use(
context.tree_facts(paths_under(single))) == context.ABSENT
several = tree(tmp_path / "multi",
{"a.py": "company_ids = fields.Many2many('res.company')"})
assert context.multi_company_in_use(
context.tree_facts(paths_under(several))) == context.PRESENT
def test_a_company_record_rule_in_xml_counts(tmp_path):
"""Multi-company record rules live in XML and nowhere else."""
xml = ("<odoo><record id='r' model='ir.rule'><field name='domain_force'>"
"[('company_id','in',company_ids)]</field></record></odoo>")
root = tree(tmp_path, {"a.py": "x = 1", "security/rules.xml": xml})
assert context.multi_company_in_use(
context.tree_facts(paths_under(root))) == context.PRESENT
def test_module_facts_are_marked_incomplete(tmp_path):
"""So they can promote and never suppress. The flag is the whole safety
property of walking one module instead of the tree."""
root = tree(tmp_path, {"models/thing.py": MODEL_WITH_A_PARENT,
"models/parent.py": PARENT_DECLARED})
facts = context.module_facts(str(root / "models" / "thing.py"), "odoo")
assert facts["walked"] and not facts["complete"]
assert context.parent_is_deleted(facts, "my.parent") == context.UNKNOWN
def test_module_facts_decline_a_file_with_no_module(tmp_path):
loose = tmp_path / "loose.py"
loose.write_text(MODEL_WITH_A_PARENT, encoding="utf-8")
assert context.module_facts(str(loose), "odoo")["walked"] is False
assert context.module_facts(None, "odoo")["walked"] is False
def test_module_facts_are_odoo_only(tmp_path):
"""A TypeScript file has no ir.model.access.csv above it and no model to
ask about, and walking its tree would cost the review nothing but time."""
root = tree(tmp_path, {"models/thing.py": MODEL_WITH_A_PARENT})
target = str(root / "models" / "thing.py")
assert context.module_facts(target, "typescript")["walked"] is False
def test_demo_data_is_read_off_the_manifest(tmp_path):
"""Odoo loads a manifest's demo files with noupdate forced on, so the one
rule that reads XML has nothing to say about them."""
module = tmp_path / "my_module"
(module / "data").mkdir(parents=True)
(module / "__manifest__.py").write_text(
"{'name': 'x', 'data': ['data/params.xml'], 'demo': ['data/demo.xml']}",
encoding="utf-8")
for name in ("params.xml", "demo.xml"):
(module / "data" / name).write_text("<odoo/>", encoding="utf-8")
assert context.is_demo_data(str(module / "data" / "demo.xml"))
assert not context.is_demo_data(str(module / "data" / "params.xml"))
assert not context.is_demo_data(str(tmp_path / "loose.xml"))
# product.template's shape in odoo core: a global company rule in `product`,
# and a visibility rule on website_published that only portal and public users
# get, in `website_sale`.
TWO_RULES = (
"<odoo>"
"<record id='comp' model='ir.rule'>"
"<field name='model_id' ref='model_product_template'/>"
"<field name='domain_force'>['|', ('company_id', 'parent_of', company_ids),"
" ('company_id', '=', False)]</field></record>"
"<record id='public' model='ir.rule'>"
"<field name='model_id' ref='product.model_product_template'/>"
"<field name='domain_force'>[('website_published', '=', True)]</field>"
"<field name='groups' eval=\"[(4, ref('base.group_public'))]\"/></record>"
"</odoo>")
TEMPLATE_DECLARED = ("from odoo import models\n\n\n"
"class Template(models.Model):\n"
" _name = 'product.template'\n")
def test_rules_are_kept_one_by_one_with_their_audience(tmp_path):
"""The merged field set answers 'is this model ruled'. It cannot answer
'did this call re-apply the rules', which needs to know which rule every
user gets and which only some do."""
root = tree(tmp_path, {"models/t.py": TEMPLATE_DECLARED,
"security/rules.xml": TWO_RULES})
facts = context.tree_facts(paths_under(root))
assert sorted(context.model_rule_sets(facts, "product.template")) == [
(False, ("website_published",)), (True, ("company_id",))]
assert context.model_rule_sets(context.no_tree(), "product.template") == ()
def _sudo_search(domain):
return ("from odoo import models\n\n\n"
"class Template(models.Model):\n"
" _inherit = 'product.template'\n\n"
" def swap(self):\n"
" return self.sudo().search(" + domain + ", limit=1)\n")
def test_naming_one_rule_of_two_does_not_re_scope_a_sudo_call(tmp_path):
"""website_sale's set_sequence_up: the call names website_published, the
portal rule's field, and the global company rule is dropped all the same."""
import semantics
root = tree(tmp_path, {"models/t.py": TEMPLATE_DECLARED,
"security/rules.xml": TWO_RULES})
facts = context.tree_facts(paths_under(root))
only_one = _sudo_search("[('website_published', '=', True)]")
assert semantics.run_check("sudo_drops_record_rules", only_one, facts=facts)
both = _sudo_search("[('website_published', '=', True),"
" ('company_id', 'in', self.env.companies.ids)]")
assert semantics.run_check("sudo_drops_record_rules", both, facts=facts) == []
def test_with_no_global_rule_any_rule_field_still_re_scopes(tmp_path):
"""Group rules are ORed per audience, so the old test stands where every
rule the model has belongs to a group."""
import semantics
group_only = TWO_RULES.split("<record id='public'")[0].replace(
"</record>", "<field name='groups' eval=\"[(4, ref('base.group_user'))]\"/>"
"</record>") + "</odoo>"
root = tree(tmp_path, {"models/t.py": TEMPLATE_DECLARED,
"security/rules.xml": group_only})
facts = context.tree_facts(paths_under(root))
assert context.model_rule_sets(facts, "product.template") == (
(False, ("company_id",)),)
body = _sudo_search("[('company_id', 'in', self.env.companies.ids)]")
assert semantics.run_check("sudo_drops_record_rules", body, facts=facts) == []
# ------------------------------------------- what the depends check reads off a tree
def odoo_modules(tmp_path, spec):
"""{module: (its depends, {relative path: source})}, each under its own manifest."""
for module, (depends, files) in spec.items():
root = tmp_path / "addons" / module
root.mkdir(parents=True)
(root / "__manifest__.py").write_text(
"{'name': %r, 'depends': %r}" % (module, list(depends)), encoding="utf-8")
for name, body in files.items():
path = root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body, encoding="utf-8")
return tmp_path / "addons"
SHOP = """from odoo import api, fields, models
class Order(models.Model):
_name = 'shop.order'
line_ids = fields.One2many('shop.line', 'order_id')
discount = fields.Float()
total = fields.Float(compute='_compute_total'{store})
@api.depends('line_ids.price')
def _compute_total(self):
for order in self:
order.total = sum(order.line_ids.mapped('price'))
class Line(models.Model):
_name = 'shop.line'
order_id = fields.Many2one('shop.order')
price = fields.Float()
tax = fields.Float()
"""
DISCOUNT = """from odoo import api, models
class Order(models.Model):
_inherit = 'shop.order'
@api.depends('discount')
def _compute_total(self):
for order in self:
order.total = sum(order.line_ids.mapped('{read}')) - order.discount
"""
TAX = """from odoo import api, models
class Order(models.Model):
_inherit = 'shop.order'
@api.depends('line_ids.tax')
def _compute_total(self):
super()._compute_total()
"""
def _depends_findings(root, module, facts):
import semantics
path = str(root / module / "models.py")
with open(path, encoding="utf-8") as fh:
body = fh.read()
return semantics.run_check("depends_covers_compute_reads", body,
facts=context.for_file(facts, path))
def test_a_dependency_the_parent_definition_declares_is_declared(tmp_path):
"""Odoo merges @api.depends from every definition of the method in the
MRO, so an override reading line_ids.price is covered by the parent's
declaration of it. "Depends merged from sale_project" was one of §3.71's
false findings, and §3.80 counted five more."""
root = odoo_modules(tmp_path, {
"shop": ((), {"models.py": SHOP.replace("{store}", ", store=True")}),
"shop_discount": (("shop",), {"models.py": DISCOUNT.replace("{read}", "price")}),
})
facts = context.tree_facts(paths_under(root))
assert _depends_findings(root, "shop_discount", None), "the file alone cannot tell"
assert _depends_findings(root, "shop_discount", facts) == []
def test_a_sibling_module_declaring_it_does_not_count(tmp_path):
"""shop_tax overrides the same compute and declares line_ids.tax, but
shop_discount does not depend on it: installed without it, nothing
recomputes the total when a line's tax changes."""
root = odoo_modules(tmp_path, {
"shop": ((), {"models.py": SHOP.replace("{store}", ", store=True")}),
"shop_tax": (("shop",), {"models.py": TAX}),
"shop_discount": (("shop",), {"models.py": DISCOUNT.replace("{read}", "tax")}),
})
facts = context.tree_facts(paths_under(root))
found = _depends_findings(root, "shop_discount", facts)
assert any("'line_ids.tax'" in message for _, message, _ in found)
def test_a_compute_every_declaration_leaves_unstored_is_outside_the_rule(tmp_path):
"""The rule is about stored computes. pos_sale's overrides of sale's
amount_to_invoice were two of §3.78's false findings: sale declares the
field without store=True, which the file holding the override cannot see."""
root = odoo_modules(tmp_path, {
"shop": ((), {"models.py": SHOP.replace("{store}", "")}),
"shop_discount": (("shop",), {"models.py": DISCOUNT.replace("{read}", "tax")}),
})
facts = context.tree_facts(paths_under(root))
assert _depends_findings(root, "shop_discount", facts) == []
partial = context.tree_facts(paths_under(root), complete=False)
assert _depends_findings(root, "shop_discount", partial), \
"a walk that is not the whole codebase cannot say nothing stores it"
def test_one_declaration_storing_the_field_keeps_it_stored(tmp_path):
stored = DISCOUNT.replace("{read}", "tax").replace(
" @api.depends", " total = fields.Float(store=True)\n\n @api.depends").replace(
"from odoo import api, models", "from odoo import api, fields, models")
root = odoo_modules(tmp_path, {
"shop": ((), {"models.py": SHOP.replace("{store}", "")}),
"shop_discount": (("shop",), {"models.py": stored}),
})
facts = context.tree_facts(paths_under(root))
found = _depends_findings(root, "shop_discount", facts)
assert any("'line_ids.tax'" in message for _, message, _ in found)
TASKS = """from odoo import api, fields, models
class Task(models.Model):
_name = 'my.task'
parent_id = fields.Many2one('my.task')
partner_id = fields.Many2one('my.partner')
project_id = fields.Many2one('my.project', compute='_compute_project_id', store=True)
has_parent_project = fields.Boolean(compute='_compute_has_parent_project', store=True)
is_top_partner = fields.Boolean(compute='_compute_is_top_partner', store=True)
@api.depends('parent_id.project_id')
def _compute_project_id(self):
for task in self:
task.project_id = task.parent_id.project_id
@api.depends('project_id')
def _compute_has_parent_project(self):
for task in self:
task.has_parent_project = bool(task.parent_id.project_id)
@api.depends('partner_id.commercial_partner_id')
def _compute_is_top_partner(self):
for task in self:
task.is_top_partner = not task.partner_id.parent_id
class Partner(models.Model):
_name = 'my.partner'
parent_id = fields.Many2one('my.partner')
commercial_partner_id = fields.Many2one(
'my.partner', compute='_compute_commercial_partner', store=True)
@api.depends('parent_id.commercial_partner_id')
def _compute_commercial_partner(self):
for partner in self:
partner.commercial_partner_id = partner.parent_id.commercial_partner_id or partner
"""
def test_a_declared_computed_field_covers_what_it_depends_on(tmp_path):
"""Odoo's triggers are transitive. A task's project follows its parent's,
so a compute declaring project_id already re-runs when the parent's project
changes, and its read of parent_id.project_id is covered. So is a read
through a relation to what the declared path's last field depends on.
§3.80 counted 11 of its 76 false findings on core as this."""
root = odoo_modules(tmp_path, {"projects": ((), {"models.py": TASKS})})
facts = context.tree_facts(paths_under(root))
alone = _depends_findings(root, "projects", None)
assert {m.split("'")[1] for _, m, _ in alone} == {"parent_id", "parent_id.project_id",
"partner_id.parent_id"}
assert _depends_findings(root, "projects", facts) == []
def test_a_module_walk_still_merges_and_follows_what_it_holds(tmp_path):
"""`nexa check` walks one module and never suppresses on absence, but a
definition or a dependency it can see is positive evidence."""
root = odoo_modules(tmp_path, {"projects": ((), {"models.py": TASKS})})
path = str(root / "projects" / "models.py")
facts = context.module_facts(path, "odoo")
assert facts.get("module") == "projects" and not facts.get("complete")
assert _depends_findings(root, "projects", facts) == []
def test_the_closure_of_a_module_is_what_it_depends_on(tmp_path):
root = odoo_modules(tmp_path, {
"shop": ((), {"models.py": SHOP.replace("{store}", "")}),
"shop_discount": (("shop",), {"models.py": DISCOUNT.replace("{read}", "tax")}),
"shop_tax": (("shop",), {"models.py": TAX}),
})
facts = context.tree_facts(paths_under(root))
assert context.module_closure(facts, "shop_discount") == {"shop_discount", "shop", "base"}
assert context.module_closure(facts, None) is None
# ----------------------------------- what `nexa check` reads beside its module
def _module_alone(root, module):
"""The facts `check` had before it read the modules beside: the module alone."""
path = str(root / module / "models.py")
return context.for_file(context.tree_facts(paths_under(root / module), complete=False),
path)
def test_check_reads_the_modules_beside_it_that_it_depends_on(tmp_path):
"""spp_cel_event's override of _compute_cel_expression reads two fields
that spp_cel_domain's definition declares, and spp_cel_event depends on
spp_cel_domain. fieldtest, walking the whole tree, merged the two lists;
`check`, walking the one module, reported both reads (ARCHITECTURE 3.84)."""
root = odoo_modules(tmp_path, {
"shop": ((), {"models.py": SHOP.replace("{store}", ", store=True")}),
"shop_discount": (("shop",), {"models.py": DISCOUNT.replace("{read}", "price")}),
})
assert _depends_findings(root, "shop_discount", _module_alone(root, "shop_discount"))
facts = context.module_facts(str(root / "shop_discount" / "models.py"), "odoo")
assert facts.get("module") == "shop_discount" and not facts.get("complete")
assert _depends_findings(root, "shop_discount", facts) == []
def test_check_reads_only_what_the_manifest_depends_on(tmp_path):
"""shop_tax sits beside shop_discount and declares line_ids.tax for the same
compute, but shop_discount does not depend on it, so it is not read."""
root = odoo_modules(tmp_path, {
"shop": ((), {"models.py": SHOP.replace("{store}", ", store=True")}),
"shop_tax": (("shop",), {"models.py": TAX}),
"shop_discount": (("shop",), {"models.py": DISCOUNT.replace("{read}", "tax")}),
})
facts = context.module_facts(str(root / "shop_discount" / "models.py"), "odoo")
assert set(facts["modules"]) == {"shop_discount"}
assert set(context.with_dependencies(facts)["modules"]) == {"shop_discount", "shop"}
found = _depends_findings(root, "shop_discount", facts)
assert any("'line_ids.tax'" in message for _, message, _ in found)
def test_check_follows_the_closure_and_reads_declarations_alone(tmp_path):
"""What a dependency depends on is installed too, and a model a test
declares is not. The modules beside are read for their declarations and
nothing else: the files walked and the models declared stay the module's."""
import os
root = odoo_modules(tmp_path, {
"shop": ((), {"models.py": SHOP.replace("{store}", ", store=True"),
"tests/test_shop.py": TAX}),
"shop_tax": (("shop",), {"models.py": TAX}),
"shop_discount": (("shop_tax",), {"models.py": DISCOUNT.replace("{read}", "tax")}),
})
manifest = str(root / "shop_discount" / "__manifest__.py")
read = [os.path.relpath(p, str(root)).replace(os.sep, "/")
for p in context._dependency_sources(manifest)]
assert read == ["shop_tax/__manifest__.py", "shop_tax/models.py",
"shop/__manifest__.py", "shop/models.py"]
facts = context.module_facts(str(root / "shop_discount" / "models.py"), "odoo")
assert _depends_findings(root, "shop_discount", facts) == []
wider = context.with_dependencies(facts)
assert wider["files"] == 2
assert "shop.line" not in wider["models_declared"]
def test_check_reads_no_dependency_past_the_cap(tmp_path, monkeypatch):
"""Past the cap the read would cost seconds, so `check` keeps the facts of
the module alone, which can leave a finding standing and never makes one."""
root = odoo_modules(tmp_path, {
"shop": ((), {"models.py": SHOP.replace("{store}", ", store=True")}),
"shop_discount": (("shop",), {"models.py": DISCOUNT.replace("{read}", "price")}),
})
monkeypatch.setattr(context, "_CLOSURE_FILE_CAP", 1)
assert context._dependency_sources(str(root / "shop_discount" / "__manifest__.py")) == []
facts = context.module_facts(str(root / "shop_discount" / "models.py"), "odoo")
assert _depends_findings(root, "shop_discount", facts)
def test_check_looks_for_a_dependency_beside_it_and_nowhere_else(tmp_path):
"""A dependency installed in another directory is not looked for, and a
name that is not a module name is not followed out of the directory."""
root = odoo_modules(tmp_path, {
"shop_discount": (("shop", "../elsewhere/shop"),
{"models.py": DISCOUNT.replace("{read}", "price")}),
})
other = tmp_path / "elsewhere" / "shop"
other.mkdir(parents=True)
(other / "__manifest__.py").write_text("{'name': 'shop', 'depends': []}",
encoding="utf-8")
(other / "models.py").write_text(SHOP.replace("{store}", ", store=True"),
encoding="utf-8")
assert context._dependency_sources(str(root / "shop_discount" / "__manifest__.py")) == []
def test_check_finds_a_dependency_in_an_addons_path_it_is_given(tmp_path):
"""OCA's modules depend on core's, which sit in another directory. Named
as an addons path, as Odoo's own --addons-path names them, they are read;
a module beside the checked one comes first, as the nearer copy."""
root = odoo_modules(tmp_path, {
"shop_discount": (("shop",), {"models.py": DISCOUNT.replace("{read}", "price")}),
})
core = tmp_path / "core"
(core / "shop").mkdir(parents=True)
(core / "shop" / "__manifest__.py").write_text("{'name': 'shop', 'depends': []}",
encoding="utf-8")
(core / "shop" / "models.py").write_text(SHOP.replace("{store}", ", store=True"),
encoding="utf-8")
path = str(root / "shop_discount" / "models.py")
assert _depends_findings(root, "shop_discount", context.module_facts(path, "odoo"))
named = context.module_facts(path, "odoo", addons=[str(core)])
assert _depends_findings(root, "shop_discount", named) == []
manifest = str(root / "shop_discount" / "__manifest__.py")
assert context._dependency_sources(manifest, [str(core)])[0].startswith(str(core))
odoo_modules(tmp_path / "beside", {"shop": ((), {"models.py": SHOP})})
beside = tmp_path / "beside" / "addons"
(beside / "shop_discount").mkdir()
(beside / "shop_discount" / "__manifest__.py").write_text(
"{'name': 'shop_discount', 'depends': ['shop']}", encoding="utf-8")
nearer = context._dependency_sources(str(beside / "shop_discount" / "__manifest__.py"),
[str(core)])
assert nearer and all(p.startswith(str(beside)) for p in nearer)
def test_check_reads_the_dependencies_only_when_a_read_is_left(tmp_path, monkeypatch):
"""Most files have no read their module's own declarations leave uncovered,
and reading the modules beside cost seconds on core (ARCHITECTURE 3.86).
They are read once, at the first read left, and never for a file without one."""
import semantics
root = odoo_modules(tmp_path, {
"shop": ((), {"models.py": SHOP.replace("{store}", ", store=True")}),
"shop_discount": (("shop",), {
"models.py": DISCOUNT.replace("{read}", "price"),
"plain.py": "from odoo import models\n\n\nclass Plain(models.Model):\n"
" _inherit = 'shop.order'\n"}),
})
calls = []
real = context._dependency_sources
monkeypatch.setattr(context, "_dependency_sources",
lambda *args: calls.append(args) or real(*args))
facts = context.module_facts(str(root / "shop_discount" / "plain.py"), "odoo")
with open(str(root / "shop_discount" / "plain.py"), encoding="utf-8") as fh:
assert semantics.run_check("depends_covers_compute_reads", fh.read(),
facts=facts) == []
assert calls == []
path = str(root / "shop_discount" / "models.py")
assert _depends_findings(root, "shop_discount", context.for_file(facts, path)) == []
assert _depends_findings(root, "shop_discount", context.for_file(facts, path)) == []
assert len(calls) == 1
|