summaryrefslogtreecommitdiff
path: root/addons/product/tests/test_product_attribute_value_config.py
blob: 238f696bce72c42b6b69714229aa70e414eb7197 (plain)
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
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

import time
from psycopg2 import IntegrityError

from odoo.exceptions import UserError, ValidationError
from odoo.tests import tagged
from odoo.tests.common import SavepointCase
from odoo.tools import mute_logger


class TestProductAttributeValueCommon(SavepointCase):
    @classmethod
    def setUpClass(cls):
        super(TestProductAttributeValueCommon, cls).setUpClass()

        cls.computer = cls.env['product.template'].create({
            'name': 'Super Computer',
            'price': 2000,
        })

        cls._add_ssd_attribute()
        cls._add_ram_attribute()
        cls._add_hdd_attribute()

        cls.computer_case = cls.env['product.template'].create({
            'name': 'Super Computer Case'
        })

        cls._add_size_attribute()

    @classmethod
    def _add_ssd_attribute(cls):
        cls.ssd_attribute = cls.env['product.attribute'].create({'name': 'Memory', 'sequence': 1})
        cls.ssd_256 = cls.env['product.attribute.value'].create({
            'name': '256 GB',
            'attribute_id': cls.ssd_attribute.id,
            'sequence': 1,
        })
        cls.ssd_512 = cls.env['product.attribute.value'].create({
            'name': '512 GB',
            'attribute_id': cls.ssd_attribute.id,
            'sequence': 2,
        })

        cls._add_ssd_attribute_line()

    @classmethod
    def _add_ssd_attribute_line(cls):
        cls.computer_ssd_attribute_lines = cls.env['product.template.attribute.line'].create({
            'product_tmpl_id': cls.computer.id,
            'attribute_id': cls.ssd_attribute.id,
            'value_ids': [(6, 0, [cls.ssd_256.id, cls.ssd_512.id])],
        })
        cls.computer_ssd_attribute_lines.product_template_value_ids[0].price_extra = 200
        cls.computer_ssd_attribute_lines.product_template_value_ids[1].price_extra = 400

    @classmethod
    def _add_ram_attribute(cls):
        cls.ram_attribute = cls.env['product.attribute'].create({'name': 'RAM', 'sequence': 2})
        cls.ram_8 = cls.env['product.attribute.value'].create({
            'name': '8 GB',
            'attribute_id': cls.ram_attribute.id,
            'sequence': 1,
        })
        cls.ram_16 = cls.env['product.attribute.value'].create({
            'name': '16 GB',
            'attribute_id': cls.ram_attribute.id,
            'sequence': 2,
        })
        cls.ram_32 = cls.env['product.attribute.value'].create({
            'name': '32 GB',
            'attribute_id': cls.ram_attribute.id,
            'sequence': 3,
        })
        cls.computer_ram_attribute_lines = cls.env['product.template.attribute.line'].create({
            'product_tmpl_id': cls.computer.id,
            'attribute_id': cls.ram_attribute.id,
            'value_ids': [(6, 0, [cls.ram_8.id, cls.ram_16.id, cls.ram_32.id])],
        })
        cls.computer_ram_attribute_lines.product_template_value_ids[0].price_extra = 20
        cls.computer_ram_attribute_lines.product_template_value_ids[1].price_extra = 40
        cls.computer_ram_attribute_lines.product_template_value_ids[2].price_extra = 80

    @classmethod
    def _add_hdd_attribute(cls):
        cls.hdd_attribute = cls.env['product.attribute'].create({'name': 'HDD', 'sequence': 3})
        cls.hdd_1 = cls.env['product.attribute.value'].create({
            'name': '1 To',
            'attribute_id': cls.hdd_attribute.id,
            'sequence': 1,
        })
        cls.hdd_2 = cls.env['product.attribute.value'].create({
            'name': '2 To',
            'attribute_id': cls.hdd_attribute.id,
            'sequence': 2,
        })
        cls.hdd_4 = cls.env['product.attribute.value'].create({
            'name': '4 To',
            'attribute_id': cls.hdd_attribute.id,
            'sequence': 3,
        })

        cls._add_hdd_attribute_line()

    @classmethod
    def _add_hdd_attribute_line(cls):
        cls.computer_hdd_attribute_lines = cls.env['product.template.attribute.line'].create({
            'product_tmpl_id': cls.computer.id,
            'attribute_id': cls.hdd_attribute.id,
            'value_ids': [(6, 0, [cls.hdd_1.id, cls.hdd_2.id, cls.hdd_4.id])],
        })
        cls.computer_hdd_attribute_lines.product_template_value_ids[0].price_extra = 2
        cls.computer_hdd_attribute_lines.product_template_value_ids[1].price_extra = 4
        cls.computer_hdd_attribute_lines.product_template_value_ids[2].price_extra = 8

    def _add_ram_exclude_for(self):
        self._get_product_value_id(self.computer_ram_attribute_lines, self.ram_16).update({
            'exclude_for': [(0, 0, {
                'product_tmpl_id': self.computer.id,
                'value_ids': [(6, 0, [self._get_product_value_id(self.computer_hdd_attribute_lines, self.hdd_1).id])]
            })]
        })

    @classmethod
    def _add_size_attribute(cls):
        cls.size_attribute = cls.env['product.attribute'].create({'name': 'Size', 'sequence': 4})
        cls.size_m = cls.env['product.attribute.value'].create({
            'name': 'M',
            'attribute_id': cls.size_attribute.id,
            'sequence': 1,
        })
        cls.size_l = cls.env['product.attribute.value'].create({
            'name': 'L',
            'attribute_id': cls.size_attribute.id,
            'sequence': 2,
        })
        cls.size_xl = cls.env['product.attribute.value'].create({
            'name': 'XL',
            'attribute_id': cls.size_attribute.id,
            'sequence': 3,
        })
        cls.computer_case_size_attribute_lines = cls.env['product.template.attribute.line'].create({
            'product_tmpl_id': cls.computer_case.id,
            'attribute_id': cls.size_attribute.id,
            'value_ids': [(6, 0, [cls.size_m.id, cls.size_l.id, cls.size_xl.id])],
        })

    def _get_product_value_id(self, product_template_attribute_lines, product_attribute_value):
        return product_template_attribute_lines.product_template_value_ids.filtered(
            lambda product_value_id: product_value_id.product_attribute_value_id == product_attribute_value)[0]

    def _get_product_template_attribute_value(self, product_attribute_value, model=False):
        """
            Return the `product.template.attribute.value` matching
                `product_attribute_value` for self.

            :param: recordset of one product.attribute.value
            :return: recordset of one product.template.attribute.value if found
                else empty
        """
        if not model:
            model = self.computer
        return model.valid_product_template_attribute_line_ids.filtered(
            lambda l: l.attribute_id == product_attribute_value.attribute_id
        ).product_template_value_ids.filtered(
            lambda v: v.product_attribute_value_id == product_attribute_value
        )

    def _add_exclude(self, m1, m2, product_template=False):
        m1.update({
            'exclude_for': [(0, 0, {
                'product_tmpl_id': (product_template or self.computer).id,
                'value_ids': [(6, 0, [m2.id])]
            })]
        })


@tagged('post_install', '-at_install')
class TestProductAttributeValueConfig(TestProductAttributeValueCommon):

    def test_product_template_attribute_values_creation(self):
        self.assertEqual(len(self.computer_ssd_attribute_lines.product_template_value_ids), 2,
            'Product attribute values (ssd) were not automatically created')
        self.assertEqual(len(self.computer_ram_attribute_lines.product_template_value_ids), 3,
            'Product attribute values (ram) were not automatically created')
        self.assertEqual(len(self.computer_hdd_attribute_lines.product_template_value_ids), 3,
            'Product attribute values (hdd) were not automatically created')
        self.assertEqual(len(self.computer_case_size_attribute_lines.product_template_value_ids), 3,
            'Product attribute values (size) were not automatically created')

    def test_get_variant_for_combination(self):
        computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
        computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
        computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
        computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)

        # completely defined variant
        combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
        ok_variant = self.computer._get_variant_for_combination(combination)
        self.assertEqual(ok_variant.product_template_attribute_value_ids, combination)

        # over defined variant
        combination = computer_ssd_256 + computer_ram_8 + computer_ram_16 + computer_hdd_1
        variant = self.computer._get_variant_for_combination(combination)
        self.assertEqual(len(variant), 0)

        # under defined variant
        combination = computer_ssd_256 + computer_ram_8
        variant = self.computer._get_variant_for_combination(combination)
        self.assertFalse(variant)

    def test_product_filtered_exclude_for(self):
        """
            Super Computer has 18 variants total (2 ssd * 3 ram * 3 hdd)
            RAM 16 excudes HDD 1, that matches 2 variants:
            - SSD 256 RAM 16 HDD 1
            - SSD 512 RAM 16 HDD 1

            => There has to be 16 variants left when filtered
        """
        computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
        computer_ssd_512 = self._get_product_template_attribute_value(self.ssd_512)
        computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
        computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
        computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)

        self.assertEqual(len(self.computer._get_possible_variants()), 18)
        self._add_ram_exclude_for()
        self.assertEqual(len(self.computer._get_possible_variants()), 16)
        self.assertTrue(self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)._is_variant_possible())
        self.assertFalse(self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_16 + computer_hdd_1)._is_variant_possible())
        self.assertFalse(self.computer._get_variant_for_combination(computer_ssd_512 + computer_ram_16 + computer_hdd_1)._is_variant_possible())

    def test_children_product_filtered_exclude_for(self):
        """
            Super Computer Case has 3 variants total (3 size)
            Reference product Computer with HDD 4 excludes Size M
            The following variant will be excluded:
            - Size M

            => There has to be 2 variants left when filtered
        """
        computer_hdd_4 = self._get_product_template_attribute_value(self.hdd_4)
        computer_size_m = self._get_product_template_attribute_value(self.size_m, self.computer_case)
        self._add_exclude(computer_hdd_4, computer_size_m, self.computer_case)
        self.assertEqual(len(self.computer_case._get_possible_variants(computer_hdd_4)), 2)
        self.assertFalse(self.computer_case._get_variant_for_combination(computer_size_m)._is_variant_possible(computer_hdd_4))

    def test_is_combination_possible(self):
        computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
        computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
        computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
        computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
        self._add_exclude(computer_ram_16, computer_hdd_1)

        # CASE: basic
        self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))

        # CASE: ram 16 excluding hdd1
        self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_16 + computer_hdd_1))

        # CASE: under defined combination
        self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_16))

        # CASE: no combination, no variant, just return the only variant
        mouse = self.env['product.template'].create({'name': 'Mouse'})
        self.assertTrue(mouse._is_combination_possible(self.env['product.template.attribute.value']))

        # prep work for the last part of the test
        color_attribute = self.env['product.attribute'].create({'name': 'Color'})
        color_red = self.env['product.attribute.value'].create({
            'name': 'Red',
            'attribute_id': color_attribute.id,
        })
        color_green = self.env['product.attribute.value'].create({
            'name': 'Green',
            'attribute_id': color_attribute.id,
        })
        self.env['product.template.attribute.line'].create({
            'product_tmpl_id': mouse.id,
            'attribute_id': color_attribute.id,
            'value_ids': [(6, 0, [color_red.id, color_green.id])],
        })

        mouse_color_red = self._get_product_template_attribute_value(color_red, mouse)
        mouse_color_green = self._get_product_template_attribute_value(color_green, mouse)

        self._add_exclude(computer_ssd_256, mouse_color_green, mouse)

        variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)

        # CASE: wrong attributes (mouse_color_red not on computer)
        self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_16 + mouse_color_red))

        # CASE: parent ok
        self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1, mouse_color_red))
        self.assertTrue(mouse._is_combination_possible(mouse_color_red, computer_ssd_256 + computer_ram_8 + computer_hdd_1))

        # CASE: parent exclusion but good direction (parent is directional)
        self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1, mouse_color_green))

        # CASE: parent exclusion and wrong direction (parent is directional)
        self.assertFalse(mouse._is_combination_possible(mouse_color_green, computer_ssd_256 + computer_ram_8 + computer_hdd_1))

        # CASE: deleted combination
        variant.unlink()
        self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))

        # CASE: if multiple variants exist for the same combination and at least
        # one of them is not archived, the combination is possible
        combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
        self.env['product.product'].create({
            'product_tmpl_id': self.computer.id,
            'product_template_attribute_value_ids': [(6, 0, combination.ids)],
            'active': False,
        })
        self.env['product.product'].create({
            'product_tmpl_id': self.computer.id,
            'product_template_attribute_value_ids': [(6, 0, combination.ids)],
            'active': True,
        })
        self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))

    def test_get_first_possible_combination(self):
        computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
        computer_ssd_512 = self._get_product_template_attribute_value(self.ssd_512)
        computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
        computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
        computer_ram_32 = self._get_product_template_attribute_value(self.ram_32)
        computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
        computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
        computer_hdd_4 = self._get_product_template_attribute_value(self.hdd_4)
        self._add_exclude(computer_ram_16, computer_hdd_1)

        # Basic case: test all iterations of generator
        gen = self.computer._get_possible_combinations()
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_1)
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_2)
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_4)
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_16 + computer_hdd_2)
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_16 + computer_hdd_4)
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_32 + computer_hdd_1)
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_32 + computer_hdd_2)
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_32 + computer_hdd_4)
        self.assertEqual(next(gen), computer_ssd_512 + computer_ram_8 + computer_hdd_1)
        self.assertEqual(next(gen), computer_ssd_512 + computer_ram_8 + computer_hdd_2)
        self.assertEqual(next(gen), computer_ssd_512 + computer_ram_8 + computer_hdd_4)
        self.assertEqual(next(gen), computer_ssd_512 + computer_ram_16 + computer_hdd_2)
        self.assertEqual(next(gen), computer_ssd_512 + computer_ram_16 + computer_hdd_4)
        self.assertEqual(next(gen), computer_ssd_512 + computer_ram_32 + computer_hdd_1)
        self.assertEqual(next(gen), computer_ssd_512 + computer_ram_32 + computer_hdd_2)
        self.assertEqual(next(gen), computer_ssd_512 + computer_ram_32 + computer_hdd_4)
        self.assertIsNone(next(gen, None))

        # Give priority to ram_16 but it is not allowed by hdd_1 so it should return hhd_2 instead
        # Test invalidate_cache on product.attribute.value write
        computer_ram_16.product_attribute_value_id.sequence = -1
        self.assertEqual(self.computer._get_first_possible_combination(), computer_ssd_256 + computer_ram_16 + computer_hdd_2)

        # Move down the ram, so it will try to change the ram instead of the hdd
        # Test invalidate_cache on product.attribute write
        self.ram_attribute.sequence = 10
        self.assertEqual(self.computer._get_first_possible_combination(), computer_ssd_256 + computer_ram_8 + computer_hdd_1)

        # Give priority to ram_32 and is allowed with the rest so it should return it
        self.ram_attribute.sequence = 2
        computer_ram_16.product_attribute_value_id.sequence = 2
        computer_ram_32.product_attribute_value_id.sequence = -1
        self.assertEqual(self.computer._get_first_possible_combination(), computer_ssd_256 + computer_ram_32 + computer_hdd_1)

        # Give priority to ram_16 but now it is not allowing any hdd so it should return ram_8 instead
        computer_ram_32.product_attribute_value_id.sequence = 3
        computer_ram_16.product_attribute_value_id.sequence = -1
        self._add_exclude(computer_ram_16, computer_hdd_2)
        self._add_exclude(computer_ram_16, computer_hdd_4)
        self.assertEqual(self.computer._get_first_possible_combination(), computer_ssd_256 + computer_ram_8 + computer_hdd_1)

        # Only the last combination is possible
        computer_ram_16.product_attribute_value_id.sequence = 2
        self._add_exclude(computer_ram_8, computer_hdd_1)
        self._add_exclude(computer_ram_8, computer_hdd_2)
        self._add_exclude(computer_ram_8, computer_hdd_4)
        self._add_exclude(computer_ram_32, computer_hdd_1)
        self._add_exclude(computer_ram_32, computer_hdd_2)
        self._add_exclude(computer_ram_32, computer_ssd_256)
        self.assertEqual(self.computer._get_first_possible_combination(), computer_ssd_512 + computer_ram_32 + computer_hdd_4)

        # No possible combination (test helper and iterator)
        self._add_exclude(computer_ram_32, computer_hdd_4)
        self.assertEqual(self.computer._get_first_possible_combination(), self.env['product.template.attribute.value'])
        gen = self.computer._get_possible_combinations()
        self.assertIsNone(next(gen, None))

        # Testing parent case
        mouse = self.env['product.template'].create({'name': 'Mouse'})
        self.assertTrue(mouse._is_combination_possible(self.env['product.template.attribute.value']))

        # prep work for the last part of the test
        color_attribute = self.env['product.attribute'].create({'name': 'Color'})
        color_red = self.env['product.attribute.value'].create({
            'name': 'Red',
            'attribute_id': color_attribute.id,
        })
        color_green = self.env['product.attribute.value'].create({
            'name': 'Green',
            'attribute_id': color_attribute.id,
        })
        self.env['product.template.attribute.line'].create({
            'product_tmpl_id': mouse.id,
            'attribute_id': color_attribute.id,
            'value_ids': [(6, 0, [color_red.id, color_green.id])],
        })

        mouse_color_red = self._get_product_template_attribute_value(color_red, mouse)
        mouse_color_green = self._get_product_template_attribute_value(color_green, mouse)

        self._add_exclude(computer_ssd_256, mouse_color_red, mouse)
        self.assertEqual(mouse._get_first_possible_combination(parent_combination=computer_ssd_256 + computer_ram_8 + computer_hdd_1), mouse_color_green)

        # Test to see if several attribute_line for same attribute is well handled
        color_blue = self.env['product.attribute.value'].create({
            'name': 'Blue',
            'attribute_id': color_attribute.id,
        })
        color_yellow = self.env['product.attribute.value'].create({
            'name': 'Yellow',
            'attribute_id': color_attribute.id,
        })
        self.env['product.template.attribute.line'].create({
            'product_tmpl_id': mouse.id,
            'attribute_id': color_attribute.id,
            'value_ids': [(6, 0, [color_blue.id, color_yellow.id])],
        })
        mouse_color_yellow = self._get_product_template_attribute_value(color_yellow, mouse)
        self.assertEqual(mouse._get_first_possible_combination(necessary_values=mouse_color_yellow), mouse_color_red + mouse_color_yellow)

        # Making sure it's not extremely slow (has to discard invalid combinations early !)
        product_template = self.env['product.template'].create({
            'name': 'many combinations',
        })

        for i in range(10):
            # create the attributes
            product_attribute = self.env['product.attribute'].create({
                'name': "att %s" % i,
                'create_variant': 'dynamic',
                'sequence': i,
            })

            for j in range(50):
                # create the attribute values
                value = self.env['product.attribute.value'].create([{
                    'name': "val %s" % j,
                    'attribute_id': product_attribute.id,
                    'sequence': j,
                }])

            # set attribute and attribute values on the template
            self.env['product.template.attribute.line'].create([{
                'attribute_id': product_attribute.id,
                'product_tmpl_id': product_template.id,
                'value_ids': [(6, 0, product_attribute.value_ids.ids)]
            }])

        self._add_exclude(
            self._get_product_template_attribute_value(product_template.attribute_line_ids[1].value_ids[0],
                                                       model=product_template),
            self._get_product_template_attribute_value(product_template.attribute_line_ids[0].value_ids[0],
                                                       model=product_template),
            product_template)
        self._add_exclude(
            self._get_product_template_attribute_value(product_template.attribute_line_ids[0].value_ids[0],
                                                       model=product_template),
            self._get_product_template_attribute_value(product_template.attribute_line_ids[1].value_ids[1],
                                                       model=product_template),
            product_template)

        combination = self.env['product.template.attribute.value']
        for idx, ptal in enumerate(product_template.attribute_line_ids):
            if idx != 1:
                value = ptal.product_template_value_ids[0]
            else:
                value = ptal.product_template_value_ids[2]
            combination += value

        started_at = time.time()
        self.assertEqual(product_template._get_first_possible_combination(), combination)
        elapsed = time.time() - started_at
        # It should be about instantaneous, 0.5 to avoid false positives
        self.assertLess(elapsed, 0.5)




    def test_get_closest_possible_combinations(self):
        computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
        computer_ssd_512 = self._get_product_template_attribute_value(self.ssd_512)
        computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
        computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
        computer_ram_32 = self._get_product_template_attribute_value(self.ram_32)
        computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
        computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
        computer_hdd_4 = self._get_product_template_attribute_value(self.hdd_4)
        self._add_exclude(computer_ram_16, computer_hdd_1)

        # CASE nothing special (test 2 iterations)
        gen = self.computer._get_closest_possible_combinations(None)
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_1)
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_2)

        # CASE contains computer_hdd_1 (test all iterations)
        gen = self.computer._get_closest_possible_combinations(computer_hdd_1)
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_1)
        self.assertEqual(next(gen), computer_ssd_256 + computer_ram_32 + computer_hdd_1)
        self.assertEqual(next(gen), computer_ssd_512 + computer_ram_8 + computer_hdd_1)
        self.assertEqual(next(gen), computer_ssd_512 + computer_ram_32 + computer_hdd_1)
        self.assertIsNone(next(gen, None))

        # CASE contains computer_hdd_2
        self.assertEqual(self.computer._get_closest_possible_combination(computer_hdd_2),
            computer_ssd_256 + computer_ram_8 + computer_hdd_2)

        # CASE contains computer_hdd_2, computer_ram_16
        self.assertEqual(self.computer._get_closest_possible_combination(computer_hdd_2 + computer_ram_16),
            computer_ssd_256 + computer_ram_16 + computer_hdd_2)

        # CASE invalid combination (excluded):
        self.assertEqual(self.computer._get_closest_possible_combination(computer_hdd_1 + computer_ram_16),
            computer_ssd_256 + computer_ram_8 + computer_hdd_1)

        # CASE invalid combination (too much):
        self.assertEqual(self.computer._get_closest_possible_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_4 + computer_hdd_2),
            computer_ssd_256 + computer_ram_8 + computer_hdd_4)

        # Make sure this is not extremely slow:
        product_template = self.env['product.template'].create({
            'name': 'many combinations',
        })

        for i in range(10):
            # create the attributes
            product_attribute = self.env['product.attribute'].create({
                'name': "att %s" % i,
                'create_variant': 'dynamic',
                'sequence': i,
            })

            for j in range(10):
                # create the attribute values
                self.env['product.attribute.value'].create([{
                    'name': "val %s/%s" % (i, j),
                    'attribute_id': product_attribute.id,
                    'sequence': j,
                }])

            # set attribute and attribute values on the template
            self.env['product.template.attribute.line'].create([{
                'attribute_id': product_attribute.id,
                'product_tmpl_id': product_template.id,
                'value_ids': [(6, 0, product_attribute.value_ids.ids)]
            }])

        # Get a value in the middle for each attribute to make sure it would
        # take time to reach it (if looping one by one like before the fix).
        combination = self.env['product.template.attribute.value']
        for ptal in product_template.attribute_line_ids:
            combination += ptal.product_template_value_ids[5]

        started_at = time.time()
        self.assertEqual(product_template._get_closest_possible_combination(combination), combination)
        elapsed = time.time() - started_at
        # It should take around 10ms, but to avoid false positives we check an
        # higher value. Before the fix it would take hours.
        self.assertLess(elapsed, 0.5)

    def test_clear_caches(self):
        """The goal of this test is to make sure the cache is invalidated when
        it should be."""
        computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
        computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
        computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
        combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1

        # CASE: initial result of _get_variant_for_combination
        variant = self.computer._get_variant_for_combination(combination)
        self.assertTrue(variant)

        # CASE: clear_caches in product.product unlink
        variant.unlink()
        self.assertFalse(self.computer._get_variant_for_combination(combination))

        # CASE: clear_caches in product.product create
        variant = self.env['product.product'].create({
            'product_tmpl_id': self.computer.id,
            'product_template_attribute_value_ids': [(6, 0, combination.ids)],
        })
        self.assertEqual(variant, self.computer._get_variant_for_combination(combination))

        # CASE: clear_caches in product.product write
        variant.product_template_attribute_value_ids = False
        self.assertFalse(self.computer._get_variant_id_for_combination(combination))

    def test_constraints(self):
        """The goal of this test is to make sure constraints are correct."""
        with self.assertRaises(UserError, msg="can't change variants creation mode of attribute used on product"):
            self.ram_attribute.create_variant = 'no_variant'

        with self.assertRaises(UserError, msg="can't delete attribute used on product"):
            self.ram_attribute.unlink()

        with self.assertRaises(UserError, msg="can't change the attribute of an value used on product"):
            self.ram_32.attribute_id = self.hdd_attribute.id

        with self.assertRaises(UserError, msg="can't delete value used on product"):
            self.ram_32.unlink()

        with self.assertRaises(ValidationError, msg="can't have attribute without value on product"):
            self.env['product.template.attribute.line'].create({
                'product_tmpl_id': self.computer_case.id,
                'attribute_id': self.hdd_attribute.id,
                'value_ids': [(6, 0, [])],
            })

        with self.assertRaises(ValidationError, msg="value attribute must match line attribute"):
            self.env['product.template.attribute.line'].create({
                'product_tmpl_id': self.computer_case.id,
                'attribute_id': self.ram_attribute.id,
                'value_ids': [(6, 0, [self.ssd_256.id])],
            })

        with self.assertRaises(UserError, msg="can't change the attribute of an attribute line"):
            self.computer_ssd_attribute_lines.attribute_id = self.hdd_attribute.id

        with self.assertRaises(UserError, msg="can't change the product of an attribute line"):
            self.computer_ssd_attribute_lines.product_tmpl_id = self.computer_case.id

        with self.assertRaises(UserError, msg="can't change the value of a product template attribute value"):
            self.computer_ram_attribute_lines.product_template_value_ids[0].product_attribute_value_id = self.hdd_1

        with self.assertRaises(UserError, msg="can't change the product of a product template attribute value"):
            self.computer_ram_attribute_lines.product_template_value_ids[0].product_tmpl_id = self.computer_case.id

        with mute_logger('odoo.sql_db'), self.assertRaises(IntegrityError, msg="can't have two values with the same name for the same attribute"):
            self.env['product.attribute.value'].create({
                'name': '32 GB',
                'attribute_id': self.ram_attribute.id,
            })