-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathtest_util.py
1479 lines (1251 loc) · 60.8 KB
/
test_util.py
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ast
import operator
import re
import threading
import unittest
import uuid
from ast import literal_eval
from lxml import etree
try:
from unittest import mock
except ImportError:
import mock
from odoo.osv.expression import FALSE_LEAF, TRUE_LEAF
from odoo.tools import mute_logger
from odoo.tools.safe_eval import safe_eval
from odoo.addons.base.maintenance.migrations import util
from odoo.addons.base.maintenance.migrations.testing import UnitTestCase, parametrize
from odoo.addons.base.maintenance.migrations.util.domains import _adapt_one_domain, _model_of_path
from odoo.addons.base.maintenance.migrations.util.exceptions import MigrationError
class TestAdaptOneDomain(UnitTestCase):
def setUp(self):
super(TestAdaptOneDomain, self).setUp()
self.mock_adapter = mock.Mock()
def test_adapt_renamed_field(self):
domain = [("user_ids.partner_id.user_ids.partner_id", "=", False)]
Filter = self.env["ir.filters"]
filter1 = Filter.create(
{"name": "Test filter for adapt domain", "model_id": "res.partner", "domain": str(domain)}
)
assert domain == ast.literal_eval(filter1.domain)
util.invalidate(Filter)
util.rename_field(self.cr, "res.partner", "user_ids", "renamed_user_ids")
match_domain = [("renamed_user_ids.partner_id.renamed_user_ids.partner_id", "=", False)]
new_domain = ast.literal_eval(filter1.domain)
self.assertEqual(match_domain, new_domain)
@parametrize(
[
("res.currency", [], "res.currency"),
("res.currency", ["rate_ids"], "res.currency.rate"),
("res.currency", ("rate_ids", "company_id"), "res.company"),
("res.currency", ["rate_ids", "company_id", "user_ids"], "res.users"),
("res.currency", ("rate_ids", "company_id", "user_ids", "partner_id"), "res.partner"),
("res.users", ["partner_id"], "res.partner"),
("res.users", ["nonexistent_field"], None),
("res.users", ("partner_id", "active"), None),
("res.users", ("partner_id", "active", "name"), None),
("res.users", ("partner_id", "removed_field"), None),
]
)
def test_model_of_path(self, model, path, expected):
cr = self.env.cr
self.assertEqual(_model_of_path(cr, model, path), expected)
def test_change_no_leaf(self):
# testing plan: updata path of a domain where the last element is not changed
# no adapter
domain = [("partner_id.user_id.partner_id.user_id.partner_id", "=", False)]
match_domain = [("partner_id.friend_id.partner_id.friend_id.partner_id", "=", False)]
new_domain = _adapt_one_domain(self.cr, "res.partner", "user_id", "friend_id", "res.users", domain)
self.assertEqual(match_domain, new_domain)
# with adapter, verify it's not called
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.assertEqual(match_domain, new_domain)
self.mock_adapter.assert_not_called()
def test_change_leaf(self):
# testing plan: update path of a domain where the last element is changed
# no adapter
domain = [("partner_id.user_id.partner_id.user_id", "=", False)]
match_domain = [("partner_id.friend_id.partner_id.friend_id", "=", False)]
new_domain = _adapt_one_domain(self.cr, "res.partner", "user_id", "friend_id", "res.users", domain)
self.assertEqual(match_domain, new_domain)
# with adapter, verify it's called even if nothing was changed on the path
self.mock_adapter.return_value = domain # adapter won't update anything
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "user_id", "res.users", domain, adapter=self.mock_adapter
) # even if new==old the adapter must be called
self.mock_adapter.assert_called_once()
# Ignore `boolean-positional-value-in-call` lint violations in the whole file
# ruff: noqa: FBT003
self.mock_adapter.assert_called_with(domain[0], False, False)
self.assertEqual(None, new_domain)
# path is changed even if adapter doesn't touch it
self.mock_adapter.reset_mock()
match_domain = [("partner_id.friend_id.partner_id.friend_id", "=", False)]
self.mock_adapter.return_value = domain # adapter won't update anything
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_once()
self.mock_adapter.assert_called_with(domain[0], False, False)
self.assertEqual(match_domain, new_domain) # updated path even if adapter didn't
def test_adapter_calls(self):
# testing plan: ensure the adapter is called with the right parameters
self.mock_adapter.return_value = [("partner_id.friend_id", "=", 2)]
# '&' domain
domain = ["&", ("partner_id.user_id", "=", 1), ("name", "=", False)]
match_domain = ["&", ("partner_id.friend_id", "=", 2), ("name", "=", False)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(domain[1], False, False)
self.assertEqual(match_domain, new_domain)
# '|' domain
self.mock_adapter.reset_mock()
domain = ["|", ("partner_id.user_id", "=", 1), ("name", "=", False)]
match_domain = ["|", ("partner_id.friend_id", "=", 2), ("name", "=", False)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(domain[1], True, False)
self.assertEqual(match_domain, new_domain)
# '!' domain
self.mock_adapter.reset_mock()
domain = ["!", ("partner_id.user_id", "=", 1)]
match_domain = ["!", ("partner_id.friend_id", "=", 2)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(domain[1], False, True)
self.assertEqual(match_domain, new_domain)
# '&' '!' domain
self.mock_adapter.reset_mock()
domain = ["|", "!", ("partner_id.user_id", "=", 1), ("name", "=", False)]
match_domain = ["|", "!", ("partner_id.friend_id", "=", 2), ("name", "=", False)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(domain[2], True, True)
self.assertEqual(match_domain, new_domain)
# '|' '!' domain
self.mock_adapter.reset_mock()
domain = ["|", "!", ("partner_id.user_id", "=", 1), ("name", "=", False)]
match_domain = ["|", "!", ("partner_id.friend_id", "=", 2), ("name", "=", False)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(domain[2], True, True)
self.assertEqual(match_domain, new_domain)
def test_adapter_more_domains(self):
# testing plan: check more complex domains
self.mock_adapter.return_value = [("partner_id.friend_id", "=", 2)]
term = ("partner_id.user_id", "=", 1)
# double '!'
self.mock_adapter.reset_mock()
domain = ["!", "!", ("partner_id.user_id", "=", 1)]
match_domain = ["!", "!", ("partner_id.friend_id", "=", 2)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(term, False, False)
self.assertEqual(match_domain, new_domain)
# triple '!'
self.mock_adapter.reset_mock()
domain = ["!", "!", "!", ("partner_id.user_id", "=", 1)]
match_domain = ["!", "!", "!", ("partner_id.friend_id", "=", 2)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(term, False, True)
self.assertEqual(match_domain, new_domain)
# '|' double '!'
self.mock_adapter.reset_mock()
domain = ["|", "!", "!", ("partner_id.user_id", "=", 1), ("name", "=", False)]
match_domain = ["|", "!", "!", ("partner_id.friend_id", "=", 2), ("name", "=", False)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(term, True, False)
self.assertEqual(match_domain, new_domain)
# '&' double '!'
self.mock_adapter.reset_mock()
domain = ["&", "!", "!", ("partner_id.user_id", "=", 1), ("name", "=", False)]
match_domain = ["&", "!", "!", ("partner_id.friend_id", "=", 2), ("name", "=", False)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(term, False, False)
self.assertEqual(match_domain, new_domain)
# mixed domains
self.mock_adapter.reset_mock()
domain = ["|", "&", ("partner_id.user_id", "=", 1), ("name", "=", False), ("name", "=", False)]
match_domain = ["|", "&", ("partner_id.friend_id", "=", 2), ("name", "=", False), ("name", "=", False)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(term, False, False)
self.assertEqual(match_domain, new_domain)
self.mock_adapter.reset_mock()
domain = ["&", "|", ("partner_id.user_id", "=", 1), ("name", "=", False), ("name", "=", False)]
match_domain = ["&", "|", ("partner_id.friend_id", "=", 2), ("name", "=", False), ("name", "=", False)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(term, True, False)
self.assertEqual(match_domain, new_domain)
self.mock_adapter.reset_mock()
domain = ["|", "&", "!", ("partner_id.user_id", "=", 1), ("name", "=", False), ("name", "=", False)]
match_domain = ["|", "&", "!", ("partner_id.friend_id", "=", 2), ("name", "=", False), ("name", "=", False)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(term, False, True)
self.assertEqual(match_domain, new_domain)
self.mock_adapter.reset_mock()
domain = ["&", "|", "!", ("partner_id.user_id", "=", 1), ("name", "=", False), ("name", "=", False)]
match_domain = ["&", "|", "!", ("partner_id.friend_id", "=", 2), ("name", "=", False), ("name", "=", False)]
new_domain = _adapt_one_domain(
self.cr, "res.partner", "user_id", "friend_id", "res.users", domain, adapter=self.mock_adapter
)
self.mock_adapter.assert_called_with(term, True, True)
self.assertEqual(match_domain, new_domain)
@parametrize(
[
# first and last position in path at the same time
("partner_id", "res.users"),
# first and last position in path
("partner_id.user_id.partner_id", "res.users"),
# last position
("user_id.partner_id", "res.partner"),
# middle
("user_id.partner_id.user.id", "res.partner"),
# last position, longer domain
("company_id.partner_id.user_id.partner_id", "res.partner"),
]
)
def test_force_adapt(self, left, model, target_model="res.users", old="partner_id"):
# simulate the adapter used for removal of a field
# this is the main use case for force_adapt=True
self.mock_adapter.return_value = [TRUE_LEAF]
domain = [(left, "=", False)]
res = _adapt_one_domain(
self.cr, target_model, old, "ignored", model, domain, adapter=self.mock_adapter, force_adapt=True
)
self.mock_adapter.assert_called_once()
self.assertEqual(res, self.mock_adapter.return_value)
@parametrize(
[
("partner_id.old", "new"),
("partner_id.user_id.partner_id.old", "partner_id.user_id.new"),
("partner_id.old.foo", "new.foo"),
# from another model
("user_id.partner_id.old", "user_id.new", "res.partner"),
# no change expected
("old", None),
("partner_id", None),
("partner_id.name", None),
]
)
def test_dotted_old(self, left, expected, model="res.users"):
domain = [(left, "=", "test")]
new_domain = _adapt_one_domain(self.cr, "res.users", "partner_id.old", "new", model, domain)
if expected is not None:
self.assertEqual(new_domain, [(expected, "=", "test")])
else:
self.assertIsNone(new_domain)
@unittest.skipUnless(util.version_gte("17.0"), "`any` operator only supported from Odoo 17")
def test_any_operator(self):
domain = [("partner_id", "any", [("complete_name", "=", "Odoo")])]
expected = [("partner_id", "any", [("full_name", "=", "Odoo")])]
new_domain = _adapt_one_domain(self.cr, "res.partner", "complete_name", "full_name", "res.company", domain)
self.assertEqual(new_domain, expected)
# test it also works recursively
domain = [("partner_id", "any", [("title", "not any", [("shortcut", "like", "S.A.")])])]
expected = [("partner_id", "any", [("title", "not any", [("abbr", "like", "S.A.")])])]
new_domain = _adapt_one_domain(self.cr, "res.partner.title", "shortcut", "abbr", "res.company", domain)
self.assertEqual(new_domain, expected)
class TestAdaptDomainView(UnitTestCase):
def test_adapt_domain_view(self):
view_form = self.env["ir.ui.view"].create(
{
"name": "test_adapt_domain_view_form",
"model": "res.currency",
"arch": """\
<form>
<field name="rate_ids">
<tree>
<field name="company_id" domain="[('email', '!=', False)]"/>
<field name="company_id" domain="[('email', 'not like', 'odoo.com')]"/>
</tree>
</field>
</form>
""",
}
)
view_search_1 = self.env["ir.ui.view"].create(
{
"name": "test_adapt_domain_view_search",
"model": "res.company",
"arch": """\
<search>
<field name="email" string="Mail" filter_domain="[('email', '=', self)]"/>
</search>
""",
}
)
view_search_2 = self.env["ir.ui.view"].create(
{
"name": "test_adapt_domain_view_search",
"model": "res.company",
"arch": """\
<search>
<filter name="mail" string="Mail" domain="[('email', '=', self)]"/>
</search>
""",
}
)
util.adapt_domains(self.env.cr, "res.partner", "email", "courriel")
util.invalidate(view_form | view_search_1 | view_search_2)
self.assertIn("email", view_form.arch)
self.assertIn("email", view_search_1.arch)
self.assertIn("email", view_search_2.arch)
util.adapt_domains(self.env.cr, "res.company", "email", "courriel")
util.invalidate(view_form | view_search_1 | view_search_2)
self.assertIn("courriel", view_form.arch)
self.assertIn("courriel", view_search_1.arch)
self.assertIn("courriel", view_search_2.arch)
class TestRemoveFieldDomains(UnitTestCase):
@parametrize(
[
([("updated", "=", 0)], [TRUE_LEAF]),
# operator is not relevant
([("updated", "!=", 0)], [TRUE_LEAF]),
# if negate we should end with "not false"
(["!", ("updated", "!=", 0)], ["!", FALSE_LEAF]),
# multiple !, we should still end with a true leaf
(["!", "!", ("updated", ">", 0)], ["!", "!", TRUE_LEAF]),
# with operator
([("updated", "=", 0), ("state", "=", "done")], ["&", TRUE_LEAF, ("state", "=", "done")]),
(["&", ("updated", "=", 0), ("state", "=", "done")], ["&", TRUE_LEAF, ("state", "=", "done")]),
(["|", ("updated", "=", 0), ("state", "=", "done")], ["|", FALSE_LEAF, ("state", "=", "done")]),
# in second operand
(["&", ("state", "=", "done"), ("updated", "=", 0)], ["&", ("state", "=", "done"), TRUE_LEAF]),
(["|", ("state", "=", "done"), ("updated", "=", 0)], ["|", ("state", "=", "done"), FALSE_LEAF]),
# combination with !
(["&", "!", ("updated", "=", 0), ("state", "=", "done")], ["&", "!", FALSE_LEAF, ("state", "=", "done")]),
(["|", "!", ("updated", "=", 0), ("state", "=", "done")], ["|", "!", TRUE_LEAF, ("state", "=", "done")]),
# here, the ! apply on the whole &/| and should not invert the replaced leaf
(["!", "&", ("updated", "=", 0), ("state", "=", "done")], ["!", "&", TRUE_LEAF, ("state", "=", "done")]),
(["!", "|", ("updated", "=", 0), ("state", "=", "done")], ["!", "|", FALSE_LEAF, ("state", "=", "done")]),
]
)
def test_remove_field(self, domain, expected):
cr = self.env.cr
cr.execute(
"INSERT INTO ir_filters(name, model_id, domain, context, sort)"
" VALUES ('test', 'base.module.update', %s, '{}', 'id') RETURNING id",
[str(domain)],
)
(filter_id,) = cr.fetchone()
util.remove_field(cr, "base.module.update", "updated")
cr.execute("SELECT domain FROM ir_filters WHERE id = %s", [filter_id])
altered_domain = literal_eval(cr.fetchone()[0])
self.assertEqual(altered_domain, expected)
class TestIrExports(UnitTestCase):
def setUp(self):
super().setUp()
self.export = self.env["ir.exports"].create(
[
{
"name": "Test currency export",
"resource": "res.currency",
"export_fields": [
(0, 0, {"name": "full_name"}),
(0, 0, {"name": "rate_ids/company_id/user_ids/name"}),
(0, 0, {"name": "rate_ids/company_id/user_ids/partner_id/user_ids/name"}),
(0, 0, {"name": "rate_ids/name"}),
(0, 0, {}),
],
}
]
)
util.flush(self.export)
def _invalidate(self):
util.invalidate(self.export.export_fields)
util.invalidate(self.export)
def test_rename_field(self):
util.rename_field(self.cr, "res.partner", "user_ids", "renamed_user_ids")
self._invalidate()
self.assertEqual(
self.export.export_fields[2].name, "rate_ids/company_id/user_ids/partner_id/renamed_user_ids/name"
)
util.rename_field(self.cr, "res.users", "name", "new_name")
self._invalidate()
self.assertEqual(self.export.export_fields[1].name, "rate_ids/company_id/user_ids/new_name")
def test_remove_field(self):
util.remove_field(self.cr, "res.currency.rate", "company_id")
self._invalidate()
self.assertEqual(len(self.export.export_fields), 3)
self.assertEqual(self.export.export_fields[0].name, "full_name")
self.assertEqual(self.export.export_fields[1].name, "rate_ids/name")
def test_rename_model(self):
util.rename_model(self.cr, "res.currency", "res.currency2")
self._invalidate()
self.assertEqual(self.export.resource, "res.currency2")
def test_remove_model(self):
util.remove_model(self.cr, "res.currency.rate")
self._invalidate()
self.assertEqual(len(self.export.export_fields), 2)
self.assertEqual(self.export.export_fields.mapped("name"), ["full_name", False])
util.remove_model(self.cr, "res.currency")
self.cr.execute("SELECT * FROM ir_exports WHERE id IN %s", [tuple(self.export.ids)])
self.assertFalse(self.cr.fetchall())
class TestBaseImportMappings(UnitTestCase):
def setUp(self):
super().setUp()
self.import_mapping = self.env["base_import.mapping"].create(
[
{"res_model": "res.currency", "column_name": "Column name", "field_name": path}
for path in [
"full_name",
"rate_ids/company_id/user_ids/name",
"rate_ids/company_id/user_ids/partner_id/user_ids/name",
"rate_ids/name",
False,
]
]
)
util.flush(self.import_mapping)
def test_rename_field(self):
util.rename_field(self.cr, "res.partner", "user_ids", "renamed_user_ids")
util.invalidate(self.import_mapping)
self.assertEqual(
self.import_mapping[2].field_name, "rate_ids/company_id/user_ids/partner_id/renamed_user_ids/name"
)
util.rename_field(self.cr, "res.users", "name", "new_name")
util.invalidate(self.import_mapping)
self.assertEqual(self.import_mapping[1].field_name, "rate_ids/company_id/user_ids/new_name")
def test_remove_field(self):
prev_mappings = self.env["base_import.mapping"].search([])
util.remove_field(self.cr, "res.currency.rate", "company_id")
util.invalidate(self.import_mapping)
removed_mappings = prev_mappings - self.env["base_import.mapping"].search([])
remaining_mappings = self.import_mapping - removed_mappings
self.assertEqual(len(removed_mappings), 2)
self.assertEqual(remaining_mappings[0].field_name, "full_name")
self.assertEqual(remaining_mappings[1].field_name, "rate_ids/name")
def test_rename_model(self):
util.rename_model(self.cr, "res.currency", "res.currency2")
util.invalidate(self.import_mapping)
self.assertEqual(self.import_mapping[0].res_model, "res.currency2")
def test_remove_model(self):
prev_mappings = self.env["base_import.mapping"].search([])
util.remove_model(self.cr, "res.currency.rate")
util.invalidate(self.import_mapping)
removed_mappings = prev_mappings - self.env["base_import.mapping"].search([])
remaining_mappings = self.import_mapping - removed_mappings
self.assertEqual(len(removed_mappings), 3)
self.assertEqual(remaining_mappings.mapped("field_name"), ["full_name", False])
util.remove_model(self.cr, "res.currency")
self.cr.execute("SELECT * FROM base_import_mapping WHERE id IN %s", [tuple(remaining_mappings.ids)])
self.assertFalse(self.cr.fetchall())
class TestIterBrowse(UnitTestCase):
def test_iter_browse_iter(self):
cr = self.env.cr
cr.execute("SELECT id FROM res_country")
ids = [c for (c,) in cr.fetchall()]
chunk_size = 10
Country = type(self.env["res.country"])
func = "fetch" if util.version_gte("saas~16.2") else "_read" if util.version_gte("saas~12.5") else "read"
with mock.patch.object(Country, func, autospec=True, side_effect=getattr(Country, func)) as read:
for c in util.iter_browse(self.env["res.country"], ids, logger=None, chunk_size=chunk_size):
c.name # noqa: B018
expected = (len(ids) + chunk_size - 1) // chunk_size
self.assertEqual(read.call_count, expected)
def test_iter_browse_call(self):
cr = self.env.cr
cr.execute("SELECT id FROM res_country")
ids = [c for (c,) in cr.fetchall()]
chunk_size = 10
Country = type(self.env["res.country"])
with mock.patch.object(Country, "write", autospec=True, side_effect=Country.write) as write:
ib = util.iter_browse(self.env["res.country"], ids, logger=None, chunk_size=chunk_size)
ib.write({"vat_label": "VAT"})
expected = (len(ids) + chunk_size - 1) // chunk_size
self.assertEqual(write.call_count, expected)
def test_iter_browse_create_non_empty(self):
RPT = self.env["res.partner.title"]
with self.assertRaises(ValueError):
util.iter_browse(RPT, [42]).create([{}])
@parametrize([(True,), (False,)])
def test_iter_browse_create(self, multi):
chunk_size = 2
RPT = self.env["res.partner.title"]
names = [f"Title {i}" for i in range(7)]
ib = util.iter_browse(RPT, [], chunk_size=chunk_size)
records = ib.create([{"name": name} for name in names], multi=multi)
self.assertEqual([t.name for t in records], names)
def test_iter_browse_iter_twice(self):
cr = self.env.cr
cr.execute("SELECT id FROM res_country")
ids = [c for (c,) in cr.fetchall()]
chunk_size = 10
ib = util.iter_browse(self.env["res.country"], ids, logger=None, chunk_size=chunk_size)
for c in ib:
c.name # noqa: B018
with self.assertRaises(RuntimeError):
for c in ib:
c.name # noqa: B018
def test_iter_browse_call_twice(self):
cr = self.env.cr
cr.execute("SELECT id FROM res_country")
ids = [c for (c,) in cr.fetchall()]
chunk_size = 10
ib = util.iter_browse(self.env["res.country"], ids, logger=None, chunk_size=chunk_size)
ib.write({"vat_label": "VAT"})
with self.assertRaises(RuntimeError):
ib.write({"name": "FAIL"})
class TestPG(UnitTestCase):
def test_alter_column_type(self):
cr = self.env.cr
cr.execute(
"""
ALTER TABLE res_partner_title ADD COLUMN x bool;
UPDATE res_partner_title
SET x = CASE id % 3
WHEN 1 THEN NULL
WHEN 2 THEN True
ELSE False
END
"""
)
self.assertEqual(util.column_type(cr, "res_partner_title", "x"), "bool")
util.alter_column_type(cr, "res_partner_title", "x", "int", using="CASE {0} WHEN True THEN 2 ELSE 1 END")
self.assertEqual(util.column_type(cr, "res_partner_title", "x"), "int4")
cr.execute("SELECT id, x FROM res_partner_title")
data = cr.fetchall()
self.assertTrue(
all(x == 1 or (x == 2 and id_ % 3 == 2) for id_, x in data),
"Some values where not casted correctly via USING",
)
@parametrize(
[
("test", "<p>test</p>"),
("<p>test</p>", "<p>test</p>"),
("<div>test</div>", "<div>test</div>"),
# escapings
("r&d", "<p>r&d</p>"),
("!<(^_^)>!", "<p>!<(^_^)>!</p>"),
("'quoted'", "<p>'quoted'</p>"),
# and with links
(
"Go to https://upgrade.odoo.com/?debug=1&version=14.0 and follow the instructions.",
'<p>Go to <a href="https://upgrade.odoo.com/?debug=1&version=14.0"'
' target="_blank" rel="noreferrer noopener">https://upgrade.odoo.com/?debug=1&version=14.0</a> and'
" follow the instructions.</p>",
),
]
)
def test_pg_text2html(self, value, expected):
cr = self.env.cr
uid = self.env.user.id
cr.execute("UPDATE res_users SET signature=%s WHERE id=%s", [value, uid])
cr.execute("SELECT {} FROM res_users WHERE id=%s".format(util.pg_text2html("signature")), [uid])
result = cr.fetchone()[0]
self.assertEqual(result, expected)
def test_explode_mult_filters(self):
cr = self.env.cr
queries = util.explode_query_range(
cr,
"""
WITH cte1 AS (
SELECT id,
login
FROM res_users
WHERE {parallel_filter}
), cte2 AS (
SELECT id,
login
FROM res_users
WHERE {parallel_filter}
) SELECT u.login = cte1.login AND u.login = cte2.login
FROM cte1
LEFT JOIN cte2
ON cte2.id = cte1.id
JOIN res_users u
ON u.id = cte1.id
""",
table="res_users",
bucket_size=4,
)
for q in queries:
cr.execute(q)
self.assertTrue(all(x for (x,) in cr.fetchall()))
@mute_logger("odoo.upgrade.util.pg.explode_query_range")
def test_explode_query_range(self):
cr = self.env.cr
cr.execute("SELECT count(id) FROM res_partner_title")
count = cr.fetchone()[0]
# ensure there start with at least 10 records
for _ in range(10 - count):
count += 1
self.env["res.partner.title"].create({"name": "x"})
# set one record with very high id
tid = self.env["res.partner.title"].create({"name": "x"}).id
count += 1
cr.execute("UPDATE res_partner_title SET id = 10000000 WHERE id = %s", [tid])
qs = util.explode_query_range(cr, "SELECT 1", table="res_partner_title", bucket_size=count)
self.assertEqual(len(qs), 1) # one bucket should be enough for all records
qs = util.explode_query_range(cr, "SELECT 1", table="res_partner_title", bucket_size=count - 1)
self.assertEqual(len(qs), 1) # 10% rule for second bucket, 1 <= 0.1(count - 1) since count >= 11
def test_parallel_rowcount(self):
cr = self.env.cr
cr.execute("SELECT count(*) FROM res_lang")
[expected] = cr.fetchone()
# util.parallel_execute will `commit` the cursor and create new ones
# as we are in a test, we should not commit as we are in a subtransaction
with mock.patch.object(cr, "commit", lambda: ...):
query = "UPDATE res_lang SET name = name"
rowcount = util.explode_execute(cr, query, table="res_lang", bucket_size=10)
self.assertEqual(rowcount, expected)
def test_parallel_rowcount_threaded(self):
threading.current_thread().testing = False
self.test_parallel_rowcount()
threading.current_thread().testing = True
def test_parallel_execute_retry_on_serialization_failure(self):
TEST_TABLE_NAME = "_upgrade_serialization_failure_test_table"
N_ROWS = 10
cr = self.env.cr
cr.execute(
util.format_query(
cr,
"""
DROP TABLE IF EXISTS {table};
CREATE TABLE {table} (
id SERIAL PRIMARY KEY,
other_id INTEGER,
FOREIGN KEY (other_id) REFERENCES {table} ON DELETE CASCADE
);
INSERT INTO {table} SELECT GENERATE_SERIES(1, %s);
-- map odd numbers `n` to `n + 1` and viceversa (`n + 1` to `n`)
UPDATE {table} SET other_id = id + (MOD(id, 2) - 0.5)*2;
"""
% N_ROWS,
table=TEST_TABLE_NAME,
)
)
threading.current_thread().testing = False
# exploded queries will generate a SerializationFailed error, causing some of the queries to be retried
with mute_logger(util.pg._logger.name, "odoo.sql_db"):
util.explode_execute(
cr, util.format_query(cr, "DELETE FROM {}", TEST_TABLE_NAME), TEST_TABLE_NAME, bucket_size=1
)
threading.current_thread().testing = True
if hasattr(self, "_savepoint_id"):
# `explode_execute` causes the cursor to be committed, losing the automatic checkpoint
# Force a new one to avoid issues when cleaning up
self.addCleanup(cr.execute, f"SAVEPOINT test_{self._savepoint_id}")
self.addCleanup(cr.execute, util.format_query(cr, "DROP TABLE IF EXISTS {}", TEST_TABLE_NAME))
cr.execute(util.format_query(cr, "SELECT 1 FROM {}", TEST_TABLE_NAME))
self.assertFalse(cr.rowcount)
def test_create_column_with_fk(self):
cr = self.env.cr
self.assertFalse(util.column_exists(cr, "res_partner", "_test_lang_id"))
with self.assertRaises(ValueError):
util.create_column(cr, "res_partner", "_test_lang_id", "int4", on_delete_action="SET NULL")
with self.assertRaises(ValueError):
util.create_column(
cr, "res_partner", "_test_lang_id", "int4", fk_table="res_lang", on_delete_action="INVALID"
)
# this one should works
util.create_column(cr, "res_partner", "_test_lang_id", "int4", fk_table="res_lang", on_delete_action="SET NULL")
target = util.target_of(cr, "res_partner", "_test_lang_id")
self.assertEqual(target, ("res_lang", "id", "res_partner__test_lang_id_fkey"))
# code should be reentrant
util.create_column(cr, "res_partner", "_test_lang_id", "int4", fk_table="res_lang", on_delete_action="SET NULL")
target = util.target_of(cr, "res_partner", "_test_lang_id")
self.assertEqual(target, ("res_lang", "id", "res_partner__test_lang_id_fkey"))
class TestORM(UnitTestCase):
def test_create_cron(self):
cr = self.env.cr
util.create_cron(cr, "Test cron creation don't fail", "res.partner", "answer = 42")
cron_id = util.ref(cr, "__upgrade__.cron_post_upgrade_test_cron_creation_don_t_fail")
self.assertIsNotNone(cron_id)
cron = self.env["ir.cron"].browse(cron_id)
self.assertEqual(cron.code, "answer = 42")
class TestHelpers(UnitTestCase):
def test_model_table_convertion(self):
cr = self.env.cr
for model in self.env.registry:
if model in ("ir.actions.act_window_close",):
continue
table = util.table_of_model(cr, model)
self.assertEqual(table, self.env[model]._table)
self.assertEqual(util.model_of_table(cr, table), model)
def test_resolve_model_fields_path(self):
cr = self.env.cr
# test with provided paths
model, path = "res.currency", ["rate_ids", "company_id", "user_ids", "partner_id"]
expected_result = [
util.FieldsPathPart("res.currency", "rate_ids", "res.currency.rate"),
util.FieldsPathPart("res.currency.rate", "company_id", "res.company"),
util.FieldsPathPart("res.company", "user_ids", "res.users"),
util.FieldsPathPart("res.users", "partner_id", "res.partner"),
]
result = util.resolve_model_fields_path(cr, model, path)
self.assertEqual(result, expected_result)
model, path = "res.users", ("partner_id", "removed_field", "user_id")
expected_result = [util.FieldsPathPart("res.users", "partner_id", "res.partner")]
result = util.resolve_model_fields_path(cr, model, path)
self.assertEqual(result, expected_result)
@unittest.skipIf(
util.version_gte("saas~17.1"),
"Starting Odoo 17, the info being stored in the database, the test can't lie about its base version",
)
class TestInherit(UnitTestCase):
@classmethod
def setUpClass(cls):
bv = util.ENVIRON.get("__base_version")
util.ENVIRON["__base_version"] = util.parse_version("12.0.1.3")
if bv:
cls.addClassCleanup(operator.setitem, util.ENVIRON, "__base_version", bv)
return super().setUpClass()
@parametrize(
[
# simple tests
("do.not.exits", []),
("account.common.journal.report", ["account.common.report"]),
# avoid duplicates
(
"product.product",
[
"mail.activity.mixin",
"mail.thread",
"product.template",
"rating.mixin",
"website.published.multi.mixin",
"website.seo.metadata",
],
),
# version boundaries
# ... born after 12.0, should not include it.
("report.paperformat", []),
# ... dead before 12.0. should not be included
("delivery.carrier", ["website.published.multi.mixin"]),
# ... dead between 12.0 and CURRENT_VERSION
("crm.lead.convert2task", ["crm.partner.binding"]),
]
)
def test_inherit_parents(self, model, expected):
cr = self.env.cr
result = sorted(util.inherit_parents(cr, model))
self.assertEqual(result, sorted(expected))
def test_direct_inherit_parents(self):
cr = self.env.cr
result = sorted(util.direct_inherit_parents(cr, "product.product"))
self.assertEqual(len(result), 3)
parents, inhs = zip(*result)
self.assertEqual(parents, ("mail.activity.mixin", "mail.thread", "product.template"))
self.assertTrue(all(inh.model == "product.product" for inh in inhs))
self.assertEqual([inh.via for inh in inhs], [None, None, "product_tmpl_id"])
class TestNamedCursors(UnitTestCase):
@staticmethod
def exec(cr, which="", args=()):
cr.execute("SELECT * FROM ir_ui_view")
if which:
return getattr(cr, which)(*args)
return None
@parametrize(
[
(None, "dictfetchone"),
(None, "dictfetchmany", [10]),
(None, "dictfetchall"),
(1, "dictfetchone"),
(1, "dictfetchmany", [10]),
(1, "dictfetchall"),
(None, "fetchone"),
(None, "fetchmany", [10]),
(None, "fetchall"),
(1, "fetchone"),
(1, "fetchmany", [10]),
(1, "fetchall"),
]
)
def test_dictfetch(self, itersize, which, args=()):
expected = self.exec(self.env.cr, which, args)
with util.named_cursor(self.env.cr, itersize=itersize) as ncr:
result = self.exec(ncr, which, args)
self.assertEqual(result, expected)
def test_iterdict(self):
expected = self.exec(self.env.cr, "dictfetchall")
with util.named_cursor(self.env.cr) as ncr:
result = list(self.exec(ncr, "iterdict"))
self.assertEqual(result, expected)
def test_iter(self):
expected = self.exec(self.env.cr, "fetchall")
with util.named_cursor(self.env.cr) as ncr:
result = list(self.exec(ncr, "__iter__"))
self.assertEqual(result, expected)
class TestRecords(UnitTestCase):
def test_rename_xmlid(self):
cr = self.env.cr
old = self.env["res.currency"].create({"name": "TX1", "symbol": "TX1"})
new = self.env["res.currency"].create({"name": "TX2", "symbol": "TX2"})
self.env["ir.model.data"].create({"name": "TX1", "module": "base", "model": "res.currency", "res_id": old.id})
self.env["ir.model.data"].create({"name": "TX2", "module": "base", "model": "res.currency", "res_id": new.id})
rate = self.env["res.currency.rate"].create({"currency_id": old.id})
self.env["ir.model.data"].create(
{"name": "test_rate_tx1", "module": "base", "model": "res.currency.rate", "res_id": rate.id}
)
if hasattr(self, "_savepoint_id"):
# As the `rename_xmlid` method uses `parallel_execute`, the cursor is commited; which kill
# the savepoint created by the test setup (since saas~14.1 with the merge of SavepointCase
# into TransactionCase in odoo/odoo@7f2e168c02a7aea666d34510ed2ed8efacd5654b).
# Force a new one to avoid this issue.
# Incidentally, we should also explicitly remove the created records.
self.addCleanup(cr.execute, f"SAVEPOINT test_{self._savepoint_id}")
self.addCleanup(old.unlink)
self.addCleanup(new.unlink)
self.addCleanup(rate.unlink)
# Wrong model
with self.assertRaises(MigrationError):
util.rename_xmlid(cr, "base.TX1", "base.test_rate_tx1", on_collision="merge")
# Collision
with self.assertRaises(MigrationError):
util.rename_xmlid(cr, "base.TX1", "base.TX2", on_collision="fail")
# As TX2 is not free, TX1 is merged with TX2
with mute_logger(util.helpers._logger.name):
res = util.rename_xmlid(cr, "base.TX1", "base.TX2", on_collision="merge")
self.assertEqual(res, new.id)
self.assertEqual(util.ref(cr, "base.TX1"), None)
# TX1 references moved to TX2
cr.execute("SELECT currency_id FROM res_currency_rate WHERE id = %s", [rate.id])
self.assertEqual(cr.fetchall(), [(new.id,)])
# Nothing left to rename in TX1
res = util.rename_xmlid(cr, "base.TX1", "base.TX3", on_collision="merge")
self.assertEqual(res, None)
# Can rename to empty TX3 without need for merge
res = util.rename_xmlid(cr, "base.TX2", "base.TX3", on_collision="merge")
self.assertEqual(res, new.id)
# Normal rename
res = util.rename_xmlid(cr, "base.TX3", "base.TX4")
self.assertEqual(res, new.id)
def test_update_record_from_xml(self):
# reset all fields on a <record>
xmlid = "base.res_partner_title_mister"
data_after = {"name": "Fortytwo", "shortcut": "42"}
record = self.env.ref(xmlid)
data_before = {key: record[key] for key in data_after}
for key, value in data_after.items():
record.write({key: value})
self.assertEqual(record[key], value)
util.update_record_from_xml(self.env.cr, xmlid, reset_translations=True)
if util.version_gte("16.0"):
record.invalidate_recordset(["name"])