test_config.py 25.7 KB
Newer Older
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
1
2
3
4
5
6
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

7
import pickle
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
8
9
10
11
import textwrap
import unittest
from dataclasses import dataclass, field, is_dataclass
from enum import Enum
12
from typing import Any, List, Optional, Set, Tuple
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
13
14
15

from omegaconf import DictConfig, ListConfig, OmegaConf, ValidationError
from pytorch3d.implicitron.tools.config import (
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
16
    _get_type_to_process,
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
17
    _is_actually_dataclass,
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
18
    _ProcessType,
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
19
    _Registry,
20
    Configurable,
21
    enable_get_default_args,
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
22
23
24
25
26
    expand_args_fields,
    get_default_args,
    get_default_args_field,
    registry,
    remove_unused_components,
27
    ReplaceableBase,
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
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
    run_auto_creation,
)


@dataclass
class Animal(ReplaceableBase):
    pass


class Fruit(ReplaceableBase):
    pass


@registry.register
class Banana(Fruit):
    pips: int
    spots: int
    bananame: str


@registry.register
class Pear(Fruit):
    n_pips: int = 13


class Pineapple(Fruit):
    pass


@registry.register
class Orange(Fruit):
    pass


@registry.register
class Kiwi(Fruit):
    pass


@registry.register
class LargePear(Pear):
    pass


Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
72
73
74
75
class BoringConfigurable(Configurable):
    pass


Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
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
class MainTest(Configurable):
    the_fruit: Fruit
    n_ids: int
    n_reps: int = 8
    the_second_fruit: Fruit

    def create_the_second_fruit(self):
        expand_args_fields(Pineapple)
        self.the_second_fruit = Pineapple()

    def __post_init__(self):
        run_auto_creation(self)


class TestConfig(unittest.TestCase):
    def test_is_actually_dataclass(self):
        @dataclass
        class A:
            pass

        self.assertTrue(_is_actually_dataclass(A))
        self.assertTrue(is_dataclass(A))

        class B(A):
            a: int

        self.assertFalse(_is_actually_dataclass(B))
        self.assertTrue(is_dataclass(B))

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
105
106
107
108
109
110
111
112
    def test_get_type_to_process(self):
        gt = _get_type_to_process
        self.assertIsNone(gt(int))
        self.assertEqual(gt(Fruit), (Fruit, _ProcessType.REPLACEABLE))
        self.assertEqual(
            gt(Optional[Fruit]), (Fruit, _ProcessType.OPTIONAL_REPLACEABLE)
        )
        self.assertEqual(gt(MainTest), (MainTest, _ProcessType.CONFIGURABLE))
113
114
115
        self.assertEqual(
            gt(Optional[MainTest]), (MainTest, _ProcessType.OPTIONAL_CONFIGURABLE)
        )
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
116
117
118
        self.assertIsNone(gt(Optional[int]))
        self.assertIsNone(gt(Tuple[Fruit]))
        self.assertIsNone(gt(Tuple[Fruit, Animal]))
119
        self.assertIsNone(gt(Optional[List[int]]))
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
120

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
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
    def test_simple_replacement(self):
        struct = get_default_args(MainTest)
        struct.n_ids = 9780
        struct.the_fruit_Pear_args.n_pips = 3
        struct.the_fruit_class_type = "Pear"
        struct.the_second_fruit_class_type = "Pear"

        main = MainTest(**struct)
        self.assertIsInstance(main.the_fruit, Pear)
        self.assertEqual(main.n_reps, 8)
        self.assertEqual(main.n_ids, 9780)
        self.assertEqual(main.the_fruit.n_pips, 3)
        self.assertIsInstance(main.the_second_fruit, Pineapple)

        struct2 = get_default_args(MainTest)
        self.assertEqual(struct2.the_fruit_Pear_args.n_pips, 13)

        self.assertEqual(
            MainTest._creation_functions,
            ("create_the_fruit", "create_the_second_fruit"),
        )

    def test_detect_bases(self):
        # testing the _base_class_from_class function
        self.assertIsNone(_Registry._base_class_from_class(ReplaceableBase))
        self.assertIsNone(_Registry._base_class_from_class(MainTest))
        self.assertIs(_Registry._base_class_from_class(Fruit), Fruit)
        self.assertIs(_Registry._base_class_from_class(Pear), Fruit)

        class PricklyPear(Pear):
            pass

        self.assertIs(_Registry._base_class_from_class(PricklyPear), Fruit)

    def test_registry_entries(self):
        self.assertIs(registry.get(Fruit, "Banana"), Banana)
        with self.assertRaisesRegex(ValueError, "Banana has not been registered."):
            registry.get(Animal, "Banana")
        with self.assertRaisesRegex(ValueError, "PricklyPear has not been registered."):
            registry.get(Fruit, "PricklyPear")

        self.assertIs(registry.get(Pear, "Pear"), Pear)
        self.assertIs(registry.get(Pear, "LargePear"), LargePear)
        with self.assertRaisesRegex(ValueError, "Banana resolves to"):
            registry.get(Pear, "Banana")

        all_fruit = set(registry.get_all(Fruit))
        self.assertIn(Banana, all_fruit)
        self.assertIn(Pear, all_fruit)
        self.assertIn(LargePear, all_fruit)
        self.assertEqual(set(registry.get_all(Pear)), {LargePear})

        @registry.register
        class Apple(Fruit):
            pass

        @registry.register
        class CrabApple(Apple):
            pass

        self.assertEqual(set(registry.get_all(Apple)), {CrabApple})

        self.assertIs(registry.get(Fruit, "CrabApple"), CrabApple)

        with self.assertRaisesRegex(ValueError, "Cannot tell what it is."):

            @registry.register
            class NotAFruit:
                pass

    def test_recursion(self):
        class Shape(ReplaceableBase):
            pass

        @registry.register
        class Triangle(Shape):
            a: float = 5.0

        @registry.register
        class Square(Shape):
            a: float = 3.0

        @registry.register
        class LargeShape(Shape):
            inner: Shape

            def __post_init__(self):
                run_auto_creation(self)

        class ShapeContainer(Configurable):
            shape: Shape

        container = ShapeContainer(**get_default_args(ShapeContainer))
        # This is because ShapeContainer is missing __post_init__
        with self.assertRaises(AttributeError):
            container.shape

        class ShapeContainer2(Configurable):
            x: Shape
            x_class_type: str = "LargeShape"

            def __post_init__(self):
                self.x_LargeShape_args.inner_class_type = "Triangle"
                run_auto_creation(self)

        container2_args = get_default_args(ShapeContainer2)
        container2_args.x_LargeShape_args.inner_Triangle_args.a += 10
        self.assertIn("inner_Square_args", container2_args.x_LargeShape_args)
        # We do not perform expansion that would result in an infinite recursion,
        # so this member is not present.
        self.assertNotIn("inner_LargeShape_args", container2_args.x_LargeShape_args)
        container2_args.x_LargeShape_args.inner_Square_args.a += 100
        container2 = ShapeContainer2(**container2_args)
        self.assertIsInstance(container2.x, LargeShape)
        self.assertIsInstance(container2.x.inner, Triangle)
        self.assertEqual(container2.x.inner.a, 15.0)

    def test_simpleclass_member(self):
        # Members which are not dataclasses are
        # tolerated. But it would be nice to be able to
        # configure them.
        class Foo:
243
            def __init__(self, a: Any = 1, b: Any = 2):
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
244
245
                self.a, self.b = a, b

246
247
        enable_get_default_args(Foo)

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
        @dataclass()
        class Bar:
            aa: int = 9
            bb: int = 9

        class Container(Configurable):
            bar: Bar = Bar()
            # TODO make this work?
            # foo: Foo = Foo()
            fruit: Fruit
            fruit_class_type: str = "Orange"

            def __post_init__(self):
                run_auto_creation(self)

        self.assertEqual(get_default_args(Foo), {"a": 1, "b": 2})
        container_args = get_default_args(Container)
        container = Container(**container_args)
        self.assertIsInstance(container.fruit, Orange)
267
268
        self.assertEqual(Container._processed_members, {"fruit": Fruit})
        self.assertEqual(container._processed_members, {"fruit": Fruit})
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
269
270
271
272
273
274
275
276
277

        container_defaulted = Container()
        container_defaulted.fruit_Pear_args.n_pips += 4

        container_args2 = get_default_args(Container)
        container = Container(**container_args2)
        self.assertEqual(container.fruit_Pear_args.n_pips, 13)

    def test_inheritance(self):
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
278
        # Also exercises optional replaceables
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
279
280
281
282
283
284
285
286
        class FruitBowl(ReplaceableBase):
            main_fruit: Fruit
            main_fruit_class_type: str = "Orange"

            def __post_init__(self):
                raise ValueError("This doesn't get called")

        class LargeFruitBowl(FruitBowl):
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
287
            extra_fruit: Optional[Fruit]
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
288
            extra_fruit_class_type: str = "Kiwi"
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
289
290
            no_fruit: Optional[Fruit]
            no_fruit_class_type: Optional[str] = None
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
291
292
293
294
295
296
297
298
299
300

            def __post_init__(self):
                run_auto_creation(self)

        large_args = get_default_args(LargeFruitBowl)
        self.assertNotIn("extra_fruit", large_args)
        self.assertNotIn("main_fruit", large_args)
        large = LargeFruitBowl(**large_args)
        self.assertIsInstance(large.main_fruit, Orange)
        self.assertIsInstance(large.extra_fruit, Kiwi)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
        self.assertIsNone(large.no_fruit)
        self.assertIn("no_fruit_Kiwi_args", large_args)

        remove_unused_components(large_args)
        large2 = LargeFruitBowl(**large_args)
        self.assertIsInstance(large2.main_fruit, Orange)
        self.assertIsInstance(large2.extra_fruit, Kiwi)
        self.assertIsNone(large2.no_fruit)
        needed_args = [
            "extra_fruit_Kiwi_args",
            "extra_fruit_class_type",
            "main_fruit_Orange_args",
            "main_fruit_class_type",
            "no_fruit_class_type",
        ]
        self.assertEqual(sorted(large_args.keys()), needed_args)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
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

    def test_inheritance2(self):
        # This is a case where a class could contain an instance
        # of a subclass, which is ignored.
        class Parent(ReplaceableBase):
            pass

        class Main(Configurable):
            parent: Parent
            # Note - no __post__init__

        @registry.register
        class Derived(Parent, Main):
            pass

        args = get_default_args(Main)
        # Derived has been ignored in processing Main.
        self.assertCountEqual(args.keys(), ["parent_class_type"])

        main = Main(**args)

        with self.assertRaisesRegex(ValueError, "UNDEFAULTED has not been registered."):
            run_auto_creation(main)

        main.parent_class_type = "Derived"
        # Illustrates that a dict works fine instead of a DictConfig.
        main.parent_Derived_args = {}
        with self.assertRaises(AttributeError):
            main.parent
        run_auto_creation(main)
        self.assertIsInstance(main.parent, Derived)

    def test_redefine(self):
        class FruitBowl(ReplaceableBase):
            main_fruit: Fruit
            main_fruit_class_type: str = "Grape"

            def __post_init__(self):
                run_auto_creation(self)

        @registry.register
        @dataclass
        class Grape(Fruit):
            large: bool = False

            def get_color(self):
                return "red"

            def __post_init__(self):
                raise ValueError("This doesn't get called")

        bowl_args = get_default_args(FruitBowl)

        @registry.register
        @dataclass
        class Grape(Fruit):  # noqa: F811
            large: bool = True

            def get_color(self):
                return "green"

        with self.assertWarnsRegex(
            UserWarning, "New implementation of Grape is being chosen."
        ):
            bowl = FruitBowl(**bowl_args)
        self.assertIsInstance(bowl.main_fruit, Grape)

        # Redefining the same class won't help with defaults because encoded in args
        self.assertEqual(bowl.main_fruit.large, False)

        # But the override worked.
        self.assertEqual(bowl.main_fruit.get_color(), "green")

        # 2. Try redefining without the dataclass modifier
        # This relies on the fact that default creation processes the class.
        # (otherwise incomprehensible messages)
        @registry.register
        class Grape(Fruit):  # noqa: F811
            large: bool = True

        with self.assertWarnsRegex(
            UserWarning, "New implementation of Grape is being chosen."
        ):
            bowl = FruitBowl(**bowl_args)

        # 3. Adding a new class doesn't get picked up, because the first
        # get_default_args call has frozen FruitBowl. This is intrinsic to
        # the way dataclass and expand_args_fields work in-place but
        # expand_args_fields is not pure - it depends on the registry.
        @registry.register
        class Fig(Fruit):
            pass

        bowl_args2 = get_default_args(FruitBowl)
        self.assertIn("main_fruit_Grape_args", bowl_args2)
        self.assertNotIn("main_fruit_Fig_args", bowl_args2)

        # TODO Is it possible to make this work?
        # bowl_args2["main_fruit_Fig_args"] = get_default_args(Fig)
        # bowl_args2.main_fruit_class_type = "Fig"
        # bowl2 = FruitBowl(**bowl_args2)  <= unexpected argument

        # Note that it is possible to use Fig if you can set
        # bowl2.main_fruit_Fig_args explicitly (not in bowl_args2)
        # before run_auto_creation happens. See test_inheritance2
        # for an example.

    def test_no_replacement(self):
        # Test of Configurables without ReplaceableBase
        class A(Configurable):
            n: int = 9

        class B(Configurable):
            a: A

            def __post_init__(self):
                run_auto_creation(self)

        class C(Configurable):
436
437
438
439
            b1: B
            b2: Optional[B]
            b3: Optional[B]
            b2_enabled: bool = True
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
440
441
442
443
444
445

            def __post_init__(self):
                run_auto_creation(self)

        c_args = get_default_args(C)
        c = C(**c_args)
446
447
448
449
450
451
452
453
        self.assertIsInstance(c.b1.a, A)
        self.assertEqual(c.b1.a.n, 9)
        self.assertFalse(hasattr(c, "b1_enabled"))
        self.assertIsInstance(c.b2.a, A)
        self.assertEqual(c.b2.a.n, 9)
        self.assertTrue(c.b2_enabled)
        self.assertIsNone(c.b3)
        self.assertFalse(c.b3_enabled)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
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

    def test_doc(self):
        # The case in the docstring.
        class A(ReplaceableBase):
            k: int = 1

        @registry.register
        class A1(A):
            m: int = 3

        @registry.register
        class A2(A):
            n: str = "2"

        class B(Configurable):
            a: A
            a_class_type: str = "A2"

            def __post_init__(self):
                run_auto_creation(self)

        b_args = get_default_args(B)
        self.assertNotIn("a", b_args)
        b = B(**b_args)
        self.assertEqual(b.a.n, "2")

    def test_raw_types(self):
        @dataclass
        class MyDataclass:
            int_field: int = 0
            none_field: Optional[int] = None
            float_field: float = 9.3
            bool_field: bool = True
            tuple_field: tuple = (3, True, "j")

        class SimpleClass:
490
491
492
493
494
            def __init__(
                self,
                tuple_member_: Tuple[int, int] = (3, 4),
                set_member_: Set[int] = {2},  # noqa
            ):
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
495
                self.tuple_member = tuple_member_
496
                self.set_member = set_member_
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
497
498
499
500

            def get_tuple(self):
                return self.tuple_member

501
502
        enable_get_default_args(SimpleClass)

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
503
504
505
506
        def f(*, a: int = 3, b: str = "kj"):
            self.assertEqual(a, 3)
            self.assertEqual(b, "kj")

507
508
        enable_get_default_args(f)

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
        class C(Configurable):
            simple: DictConfig = get_default_args_field(SimpleClass)
            # simple2: SimpleClass2 = SimpleClass2()
            mydata: DictConfig = get_default_args_field(MyDataclass)
            a_tuple: Tuple[float] = (4.0, 3.0)
            f_args: DictConfig = get_default_args_field(f)

        args = get_default_args(C)
        c = C(**args)
        self.assertCountEqual(args.keys(), ["simple", "mydata", "a_tuple", "f_args"])

        mydata = MyDataclass(**c.mydata)
        simple = SimpleClass(**c.simple)

        # OmegaConf converts tuples to ListConfigs (which act like lists).
        self.assertEqual(simple.get_tuple(), [3, 4])
        self.assertTrue(isinstance(simple.get_tuple(), ListConfig))
526
527
528
        # get_default_args converts sets to ListConfigs (which act like lists).
        self.assertEqual(simple.set_member, [2])
        self.assertTrue(isinstance(simple.set_member, ListConfig))
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
529
530
531
532
533
534
535
536
537
538
539
        self.assertEqual(c.a_tuple, [4.0, 3.0])
        self.assertTrue(isinstance(c.a_tuple, ListConfig))
        self.assertEqual(mydata.tuple_field, (3, True, "j"))
        self.assertTrue(isinstance(mydata.tuple_field, ListConfig))
        f(**c.f_args)

    def test_irrelevant_bases(self):
        class NotADataclass:
            # Like torch.nn.Module, this class contains annotations
            # but is not designed to be dataclass'd.
            # This test ensures that such classes, when inherited fron,
540
            # are not accidentally affected by expand_args_fields.
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
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
            a: int = 9
            b: int

        class LeftConfigured(Configurable, NotADataclass):
            left: int = 1

        class RightConfigured(NotADataclass, Configurable):
            right: int = 2

        class Outer(Configurable):
            left: LeftConfigured
            right: RightConfigured

            def __post_init__(self):
                run_auto_creation(self)

        outer = Outer(**get_default_args(Outer))
        self.assertEqual(outer.left.left, 1)
        self.assertEqual(outer.right.right, 2)
        with self.assertRaisesRegex(TypeError, "non-default argument"):
            dataclass(NotADataclass)

    def test_unprocessed(self):
        # behavior of Configurable classes which need processing in __new__,
        class Unprocessed(Configurable):
            a: int = 9

        class UnprocessedReplaceable(ReplaceableBase):
            a: int = 1

        with self.assertWarnsRegex(UserWarning, "must be processed"):
            Unprocessed()
        with self.assertWarnsRegex(UserWarning, "must be processed"):
            UnprocessedReplaceable()

    def test_enum(self):
        # Test that enum values are kept, i.e. that OmegaConf's runtime checks
        # are in use.

        class A(Enum):
            B1 = "b1"
            B2 = "b2"

584
        # Test for a Configurable class, a function, and a regular class.
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
585
586
587
        class C(Configurable):
            a: A = A.B1

588
589
590
591
        # Also test for a calllable with enum arguments.
        def C_fn(a: A = A.B1):
            pass

592
593
        enable_get_default_args(C_fn)

594
595
596
        class C_cl:
            def __init__(self, a: A = A.B1) -> None:
                pass
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
597

598
599
        enable_get_default_args(C_cl)

600
601
602
603
604
605
606
607
608
609
610
611
612
        for C_ in [C, C_fn, C_cl]:
            base = get_default_args(C_)
            self.assertEqual(base.a, A.B1)
            replaced = OmegaConf.merge(base, {"a": "B2"})
            self.assertEqual(replaced.a, A.B2)
            with self.assertRaises(ValidationError):
                # You can't use a value which is not one of the
                # choices, even if it is the str representation
                # of one of the choices.
                OmegaConf.merge(base, {"a": "b2"})

            remerged = OmegaConf.merge(base, OmegaConf.create(OmegaConf.to_yaml(base)))
            self.assertEqual(remerged.a, A.B1)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
613

614
    def test_pickle(self):
615
        def func(a: int = 1, b: str = "3"):
616
617
            pass

618
619
620
        enable_get_default_args(func)

        args = get_default_args(func)
621
622
623
624
        args2 = pickle.loads(pickle.dumps(args))
        self.assertEqual(args2.a, 1)
        self.assertEqual(args2.b, "3")

625
626
627
628
        args_regenerated = get_default_args(func)
        pickle.dumps(args_regenerated)
        pickle.dumps(args)

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
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
    def test_remove_unused_components(self):
        struct = get_default_args(MainTest)
        struct.n_ids = 32
        struct.the_fruit_class_type = "Pear"
        struct.the_second_fruit_class_type = "Banana"
        remove_unused_components(struct)
        expected_keys = [
            "n_ids",
            "n_reps",
            "the_fruit_Pear_args",
            "the_fruit_class_type",
            "the_second_fruit_Banana_args",
            "the_second_fruit_class_type",
        ]
        expected_yaml = textwrap.dedent(
            """\
            n_ids: 32
            n_reps: 8
            the_fruit_class_type: Pear
            the_fruit_Pear_args:
              n_pips: 13
            the_second_fruit_class_type: Banana
            the_second_fruit_Banana_args:
              pips: ???
              spots: ???
              bananame: ???
            """
        )
        self.assertEqual(sorted(struct.keys()), expected_keys)

        # Check that struct is what we expect
        expected = OmegaConf.create(expected_yaml)
        self.assertEqual(struct, expected)

        # Check that we get what we expect when writing to yaml.
        self.assertEqual(OmegaConf.to_yaml(struct, sort_keys=False), expected_yaml)

        main = MainTest(**struct)
        instance_data = OmegaConf.structured(main)
        remove_unused_components(instance_data)
        self.assertEqual(sorted(instance_data.keys()), expected_keys)
        self.assertEqual(instance_data, expected)

672
673
674
675
676
677
678
679
680
    def test_remove_unused_components_optional(self):
        class MainTestWrapper(Configurable):
            mt: Optional[MainTest]

        args = get_default_args(MainTestWrapper)
        self.assertEqual(list(args.keys()), ["mt_args", "mt_enabled"])
        remove_unused_components(args)
        self.assertEqual(OmegaConf.to_yaml(args), "mt_enabled: false\n")

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
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
    def test_impls(self):
        # Check that create_x actually uses create_x_impl to do its work
        # by using all the member types, both with a faked impl function
        # and without.
        # members with _0 are optional and absent, those with _o are
        # optional and present.
        control_args = []

        def fake_impl(self, control, args):
            control_args.append(control)

        for fake in [False, True]:

            class MyClass(Configurable):
                fruit: Fruit
                fruit_class_type: str = "Orange"
                fruit_o: Optional[Fruit]
                fruit_o_class_type: str = "Orange"
                fruit_0: Optional[Fruit]
                fruit_0_class_type: Optional[str] = None
                boring: BoringConfigurable
                boring_o: Optional[BoringConfigurable]
                boring_o_enabled: bool = True
                boring_0: Optional[BoringConfigurable]

                def __post_init__(self):
                    run_auto_creation(self)

            if fake:
                MyClass.create_fruit_impl = fake_impl
                MyClass.create_fruit_o_impl = fake_impl
                MyClass.create_boring_impl = fake_impl
                MyClass.create_boring_o_impl = fake_impl

            expand_args_fields(MyClass)
            instance = MyClass()
            for name in ["fruit", "fruit_o", "boring", "boring_o"]:
                self.assertEqual(
                    hasattr(instance, name), not fake, msg=f"{name} {fake}"
                )

            self.assertIsNone(instance.fruit_0)
            self.assertIsNone(instance.boring_0)
            if not fake:
                self.assertIsInstance(instance.fruit, Orange)
                self.assertIsInstance(instance.fruit_o, Orange)
                self.assertIsInstance(instance.boring, BoringConfigurable)
                self.assertIsInstance(instance.boring_o, BoringConfigurable)

        self.assertEqual(control_args, ["Orange", "Orange", True, True])

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
732
733
734
735
736

@dataclass(eq=False)
class MockDataclass:
    field_no_default: int
    field_primitive_type: int = 42
737
738
    field_optional_none: Optional[int] = None
    field_optional_with_value: Optional[int] = 42
739
740
741
742
743
744
745
746
    field_list_type: List[int] = field(default_factory=lambda: [])


class RefObject:
    pass


REF_OBJECT = RefObject()
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
747
748
749
750
751


class MockClassWithInit:  # noqa: B903
    def __init__(
        self,
752
        field_no_nothing,
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
753
754
        field_no_default: int,
        field_primitive_type: int = 42,
755
756
        field_optional_none: Optional[int] = None,
        field_optional_with_value: Optional[int] = 42,
757
758
        field_list_type: List[int] = [],  # noqa: B006
        field_reference_type: RefObject = REF_OBJECT,
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
759
    ):
760
        self.field_no_nothing = field_no_nothing
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
761
762
        self.field_no_default = field_no_default
        self.field_primitive_type = field_primitive_type
763
764
        self.field_optional_none = field_optional_none
        self.field_optional_with_value = field_optional_with_value
765
        self.field_list_type = field_list_type
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
766
767
768
        self.field_reference_type = field_reference_type


769
770
771
enable_get_default_args(MockClassWithInit)


Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
772
class TestRawClasses(unittest.TestCase):
773
774
775
776
777
778
779
780
    def setUp(self) -> None:
        self._instances = {
            MockDataclass: MockDataclass(field_no_default=0),
            MockClassWithInit: MockClassWithInit(
                field_no_nothing="tratata", field_no_default=0
            ),
        }

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
781
782
783
    def test_get_default_args(self):
        for cls in [MockDataclass, MockClassWithInit]:
            dataclass_defaults = get_default_args(cls)
784
785
786
787
788
789
            # DictConfig fields with missing values are `not in`
            self.assertNotIn("field_no_default", dataclass_defaults)
            self.assertNotIn("field_no_nothing", dataclass_defaults)
            self.assertNotIn("field_reference_type", dataclass_defaults)
            if cls == MockDataclass:  # we don't remove undefaulted from dataclasses
                dataclass_defaults.field_no_default = 0
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
790
            for name, val in dataclass_defaults.items():
791
792
                self.assertTrue(hasattr(self._instances[cls], name))
                self.assertEqual(val, getattr(self._instances[cls], name))
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
793
794
795
796

    def test_get_default_args_readonly(self):
        for cls in [MockDataclass, MockClassWithInit]:
            dataclass_defaults = get_default_args(cls)
797
798
            dataclass_defaults["field_list_type"].append(13)
            self.assertEqual(self._instances[cls].field_list_type, [])