File: bl_blendfile_liblink.py

package info (click to toggle)
blender 4.3.2%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 309,564 kB
  • sloc: cpp: 2,385,210; python: 330,236; ansic: 280,972; xml: 2,446; sh: 972; javascript: 317; makefile: 170
file content (843 lines) | stat: -rw-r--r-- 35,151 bytes parent folder | download
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
# SPDX-FileCopyrightText: 2020-2023 Blender Authors
#
# SPDX-License-Identifier: Apache-2.0

# ./blender.bin --background --python tests/python/bl_blendfile_liblink.py
import bpy
import os
import sys

sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from bl_blendfile_utils import TestHelper


class TestBlendLibLinkHelper(TestHelper):

    def __init__(self, args):
        self.args = args

    @staticmethod
    def reset_blender():
        bpy.ops.wm.read_homefile(use_empty=True, use_factory_startup=True)
        bpy.data.orphans_purge(do_recursive=True)

    def unique_blendfile_name(self, base_name):
        return base_name + self.__class__.__name__ + ".blend"

    def init_lib_data_basic(self):
        self.reset_blender()

        me = bpy.data.meshes.new("LibMesh")
        ob = bpy.data.objects.new("LibMesh", me)
        coll = bpy.data.collections.new("LibMesh")
        coll.objects.link(ob)
        bpy.context.scene.collection.children.link(coll)

        output_dir = self.args.output_dir
        self.ensure_path(output_dir)
        # Take care to keep the name unique so multiple test jobs can run at once.
        output_lib_path = os.path.join(output_dir, self.unique_blendfile_name("blendlib_basic"))

        bpy.ops.wm.save_as_mainfile(filepath=output_lib_path, check_existing=False, compress=False)

        return output_lib_path

    def init_lib_data_animated(self):
        self.reset_blender()

        me = bpy.data.meshes.new("LibMesh")
        ob = bpy.data.objects.new("LibMesh", me)
        ob_ctrl = bpy.data.objects.new("LibController", None)
        coll = bpy.data.collections.new("LibMesh")
        coll.objects.link(ob)
        coll.objects.link(ob_ctrl)
        bpy.context.scene.collection.children.link(coll)

        # Add some action & driver animation to `LibMesh`.
        # Animate Y location.
        ob.location[1] = 0.0
        ob.keyframe_insert("location", index=1, frame=1)
        ob.location[1] = -5.0
        ob.keyframe_insert("location", index=1, frame=10)

        # Drive X location.
        ob_drv = ob.driver_add("location", 0)
        ob_drv.driver.type = 'AVERAGE'
        ob_drv_var = ob_drv.driver.variables.new()
        ob_drv_var.type = 'TRANSFORMS'
        ob_drv_var.targets[0].id = ob_ctrl
        ob_drv_var.targets[0].transform_type = 'LOC_X'

        # Add some action & driver animation to `LibController`.
        # Animate X location.
        ob_ctrl.location[0] = 0.0
        ob_ctrl.keyframe_insert("location", index=0, frame=1)
        ob_ctrl.location[0] = 5.0
        ob_ctrl.keyframe_insert("location", index=0, frame=10)

        output_dir = self.args.output_dir
        self.ensure_path(output_dir)
        # Take care to keep the name unique so multiple test jobs can run at once.
        output_lib_path = os.path.join(output_dir, self.unique_blendfile_name("blendlib_animated"))

        bpy.ops.wm.save_as_mainfile(filepath=output_lib_path, check_existing=False, compress=False)

        return output_lib_path

    def init_lib_data_indirect_lib(self):
        output_dir = self.args.output_dir
        self.ensure_path(output_dir)

        # Create an indirect library containing a material.
        self.reset_blender()

        ma = bpy.data.materials.new("LibMaterial")
        ma.use_fake_user = True
        # Take care to keep the name unique so multiple test jobs can run at once.
        output_lib_path = os.path.join(output_dir, self.unique_blendfile_name("blendlib_indirect_material"))

        bpy.ops.wm.save_as_mainfile(filepath=output_lib_path, check_existing=False, compress=False)

        # Create a main library containing object etc., and linking material from indirect library.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Material")
        bpy.ops.wm.link(directory=link_dir, filename="LibMaterial")
        ma = bpy.data.materials[0]

        me = bpy.data.meshes.new("LibMesh")
        me.materials.append(ma)
        ob = bpy.data.objects.new("LibMesh", me)
        coll = bpy.data.collections.new("LibMesh")
        coll.objects.link(ob)
        bpy.context.scene.collection.children.link(coll)

        output_dir = self.args.output_dir
        self.ensure_path(output_dir)
        # Take care to keep the name unique so multiple test jobs can run at once.
        output_lib_path = os.path.join(output_dir, self.unique_blendfile_name("blendlib_indirect_main"))

        bpy.ops.wm.save_as_mainfile(filepath=output_lib_path, check_existing=False, compress=False)

        return output_lib_path


class TestBlendLibLinkSaveLoadBasic(TestBlendLibLinkHelper):

    def __init__(self, args):
        self.args = args

    def test_link_save_load(self):
        output_dir = self.args.output_dir
        output_lib_path = self.init_lib_data_basic()

        # Simple link of a single ObData.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Mesh")
        bpy.ops.wm.link(directory=link_dir, filename="LibMesh", instance_object_data=False)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 0
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        orig_data = self.blender_data_to_tuple(bpy.data, "orig_data")

        output_work_path = os.path.join(output_dir, self.unique_blendfile_name("blendfile"))
        bpy.ops.wm.save_as_mainfile(filepath=output_work_path, check_existing=False, compress=False)
        bpy.ops.wm.open_mainfile(filepath=output_work_path, load_ui=False)

        read_data = self.blender_data_to_tuple(bpy.data, "read_data")

        # Since there is no usage of linked mesh, it is lost during save/reload.
        assert len(bpy.data.meshes) == 0
        assert orig_data != read_data

        # Simple link of a single ObData with obdata instantiation.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Mesh")
        bpy.ops.wm.link(directory=link_dir, filename="LibMesh", instance_object_data=True)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1  # Instance created for the mesh ObData.
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        orig_data = self.blender_data_to_tuple(bpy.data, "orig_data")

        bpy.ops.wm.save_as_mainfile(filepath=output_work_path, check_existing=False, compress=False)
        bpy.ops.wm.open_mainfile(filepath=output_work_path, load_ui=False)

        read_data = self.blender_data_to_tuple(bpy.data, "read_data")

        assert orig_data == read_data

        # Simple link of a single Object.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Object")
        bpy.ops.wm.link(directory=link_dir, filename="LibMesh")

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        orig_data = self.blender_data_to_tuple(bpy.data, "orig_data")

        bpy.ops.wm.save_as_mainfile(filepath=output_work_path, check_existing=False, compress=False)
        bpy.ops.wm.open_mainfile(filepath=output_work_path, load_ui=False)

        read_data = self.blender_data_to_tuple(bpy.data, "read_data")

        assert orig_data == read_data

        # Simple link of a single Collection, with Empty-instantiation.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Collection")
        bpy.ops.wm.link(directory=link_dir, filename="LibMesh", instance_collections=True)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 2  # linked object and local empty instancing the collection
        assert len(bpy.data.collections) == 1  # Scene's master collection is not listed here

        orig_data = self.blender_data_to_tuple(bpy.data, "orig_data")

        bpy.ops.wm.save_as_mainfile(filepath=output_work_path, check_existing=False, compress=False)
        bpy.ops.wm.open_mainfile(filepath=output_work_path, load_ui=False)

        read_data = self.blender_data_to_tuple(bpy.data, "read_data")

        assert orig_data == read_data

        # Simple link of a single Collection, with ViewLayer-instantiation.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Collection")
        bpy.ops.wm.link(directory=link_dir, filename="LibMesh", instance_collections=False)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1
        assert len(bpy.data.collections) == 1  # Scene's master collection is not listed here
        # Linked collection should have been added to the scene's master collection children.
        assert bpy.data.collections[0] in set(bpy.data.scenes[0].collection.children)

        orig_data = self.blender_data_to_tuple(bpy.data, "orig_data")

        bpy.ops.wm.save_as_mainfile(filepath=output_work_path, check_existing=False, compress=False)
        bpy.ops.wm.open_mainfile(filepath=output_work_path, load_ui=False)

        read_data = self.blender_data_to_tuple(bpy.data, "read_data")

        assert orig_data == read_data


class TestBlendLibLinkIndirect(TestBlendLibLinkHelper):

    def __init__(self, args):
        self.args = args

    def test_append(self):
        output_dir = self.args.output_dir
        output_lib_path = self.init_lib_data_indirect_lib()

        # Simple link of a single ObData.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Mesh")
        bpy.ops.wm.link(directory=link_dir, filename="LibMesh", instance_object_data=False)

        assert len(bpy.data.materials) == 1
        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 0
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        mesh = bpy.data.meshes[0]
        material = bpy.data.materials[0]

        assert material.library is not None
        assert material.use_fake_user is False  # Fake user is cleared when linking.
        assert material.users == 1
        assert material.is_library_indirect is True

        assert mesh.library is not None
        assert mesh.use_fake_user is False
        assert mesh.users == 0
        # IDs explicitely linked by the user are forcefully considered directly linked.
        assert mesh.is_library_indirect is False

        ob = bpy.data.objects.new("LocalMesh", mesh)
        coll = bpy.data.collections.new("LocalMesh")
        coll.objects.link(ob)
        bpy.context.scene.collection.children.link(coll)

        assert material.users == 1
        assert material.is_library_indirect is True
        assert mesh.users == 1
        assert mesh.is_library_indirect is False

        ob.material_slots[0].link = 'OBJECT'
        ob.material_slots[0].material = material

        assert material.users == 2
        assert material.is_library_indirect is False

        ob.material_slots[0].material = None

        assert material.users == 1
        # This is not properly updated whene removing a local user of linked data.
        assert material.is_library_indirect is False

        output_work_path = os.path.join(output_dir, self.unique_blendfile_name("blendfile"))
        bpy.ops.wm.save_as_mainfile(filepath=output_work_path, check_existing=False, compress=False)

        assert material.users == 1
        assert material.is_library_indirect is True

        bpy.ops.wm.open_mainfile(filepath=output_work_path, load_ui=False)

        assert len(bpy.data.materials) == 1
        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1
        assert len(bpy.data.collections) == 1  # Scene's master collection is not listed here

        mesh = bpy.data.meshes[0]
        material = bpy.data.materials[0]

        assert material.library is not None
        assert material.use_fake_user is False  # Fake user is cleared when linking.
        assert material.users == 1
        assert material.is_library_indirect is True

        assert mesh.library is not None
        assert mesh.use_fake_user is False
        assert mesh.users == 1
        assert mesh.is_library_indirect is False


class TestBlendLibLinkAnimation(TestBlendLibLinkHelper):

    def __init__(self, args):
        self.args = args

    def test_link(self):
        output_dir = self.args.output_dir
        output_lib_path = self.init_lib_data_animated()

        # Simple link of a the collection, and check animation values.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Collection")
        bpy.ops.wm.link(directory=link_dir, filename="LibMesh", instance_collections=False, instance_object_data=False)

        assert bpy.data.meshes[0].library
        assert bpy.data.meshes[0].users == 1
        assert len(bpy.data.objects) == 2
        assert bpy.data.objects[0].library
        assert bpy.data.objects[0].users == 1
        assert bpy.data.objects[1].library
        assert bpy.data.objects[1].users == 1
        assert len(bpy.data.collections) == 1  # Scene's master collection is not listed here
        assert bpy.data.collections[0].library
        assert bpy.data.collections[0].users == 1
        assert len(bpy.data.actions) == 2
        assert bpy.data.actions[0].library
        assert bpy.data.actions[0].users == 1
        assert bpy.data.actions[1].library
        assert bpy.data.actions[1].users == 1

        # Validate animation evaluation.
        bpy.context.scene.frame_set(10)
        print(bpy.data.objects["LibController"].location)
        print(bpy.data.objects["LibMesh"].location)
        bpy.context.scene.frame_set(1)
        print(bpy.data.objects["LibController"].location)
        print(bpy.data.objects["LibMesh"].location)
        assert bpy.data.objects["LibController"].location[0] == 0.0
        assert bpy.data.objects["LibMesh"].location[0] == bpy.data.objects["LibController"].location[0]
        assert bpy.data.objects["LibMesh"].location[1] == 0.0
        bpy.context.scene.frame_set(10)
        assert bpy.data.objects["LibController"].location[0] == 5.0
        assert bpy.data.objects["LibMesh"].location[0] == bpy.data.objects["LibController"].location[0]
        assert bpy.data.objects["LibMesh"].location[1] == -5.0


class TestBlendLibAppendBasic(TestBlendLibLinkHelper):

    def __init__(self, args):
        self.args = args

    def test_append(self):
        output_dir = self.args.output_dir
        output_lib_path = self.init_lib_data_indirect_lib()

        # Simple append of a single ObData.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Mesh")
        bpy.ops.wm.append(directory=link_dir, filename="LibMesh",
                          instance_object_data=False, set_fake=False, use_recursive=False, do_reuse_local_id=False)

        assert len(bpy.data.materials) == 1
        assert bpy.data.materials[0].library is not None
        assert bpy.data.materials[0].users == 1  # Fake user is cleared when linking.
        assert len(bpy.data.meshes) == 1
        assert bpy.data.meshes[0].library is None
        assert bpy.data.meshes[0].use_fake_user is False
        assert bpy.data.meshes[0].users == 0
        assert len(bpy.data.objects) == 0
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        # Simple append of a single ObData with obdata instantiation.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Mesh")
        bpy.ops.wm.append(directory=link_dir, filename="LibMesh",
                          instance_object_data=True, set_fake=False, use_recursive=False, do_reuse_local_id=False)

        assert len(bpy.data.materials) == 1
        assert bpy.data.materials[0].library is not None
        assert bpy.data.materials[0].users == 1  # Fake user is cleared when linking.
        assert len(bpy.data.meshes) == 1
        assert bpy.data.meshes[0].library is None
        assert bpy.data.meshes[0].use_fake_user is False
        assert bpy.data.meshes[0].users == 1
        assert len(bpy.data.objects) == 1  # Instance created for the mesh ObData.
        assert bpy.data.objects[0].library is None
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        # Simple append of a single ObData with fake user.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Mesh")
        bpy.ops.wm.append(directory=link_dir, filename="LibMesh",
                          instance_object_data=False, set_fake=True, use_recursive=False, do_reuse_local_id=False)

        assert len(bpy.data.materials) == 1
        assert bpy.data.materials[0].library is not None
        assert bpy.data.materials[0].users == 1  # Fake user is cleared when linking.
        assert len(bpy.data.meshes) == 1
        assert bpy.data.meshes[0].library is None
        assert bpy.data.meshes[0].use_fake_user is True
        assert bpy.data.meshes[0].users == 1
        assert len(bpy.data.objects) == 0
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        # Simple append of a single Object.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Object")
        bpy.ops.wm.append(directory=link_dir, filename="LibMesh",
                          instance_object_data=False, set_fake=False, use_recursive=False, do_reuse_local_id=False)

        assert len(bpy.data.materials) == 1
        assert bpy.data.materials[0].library is not None
        assert bpy.data.materials[0].users == 1  # Fake user is cleared when linking.
        assert len(bpy.data.meshes) == 1
        assert bpy.data.meshes[0].library is None
        assert bpy.data.meshes[0].users == 1
        assert len(bpy.data.objects) == 1
        assert bpy.data.objects[0].library is None
        assert bpy.data.objects[0].users == 1
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        # Simple recursive append of a single Object.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Object")
        bpy.ops.wm.append(directory=link_dir, filename="LibMesh",
                          instance_object_data=False, set_fake=False, use_recursive=True, do_reuse_local_id=False)

        assert len(bpy.data.materials) == 1
        assert bpy.data.materials[0].library is None
        assert bpy.data.materials[0].users == 1  # Fake user is cleared when appending.
        assert len(bpy.data.meshes) == 1
        assert bpy.data.meshes[0].library is None
        assert bpy.data.meshes[0].users == 1
        assert len(bpy.data.objects) == 1
        assert bpy.data.objects[0].library is None
        assert bpy.data.objects[0].users == 1
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        # Simple recursive append of a single Collection.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Collection")
        bpy.ops.wm.append(directory=link_dir, filename="LibMesh",
                          instance_object_data=False, set_fake=False, use_recursive=True, do_reuse_local_id=False)

        assert len(bpy.data.materials) == 1
        assert bpy.data.materials[0].library is None
        assert bpy.data.materials[0].users == 1  # Fake user is cleared when appending.
        assert bpy.data.meshes[0].library is None
        assert bpy.data.meshes[0].users == 1
        assert len(bpy.data.objects) == 1
        assert bpy.data.objects[0].library is None
        assert bpy.data.objects[0].users == 1
        assert len(bpy.data.collections) == 1  # Scene's master collection is not listed here
        assert bpy.data.collections[0].library is None
        assert bpy.data.collections[0].users == 1


class TestBlendLibAppendReuseID(TestBlendLibLinkHelper):

    def __init__(self, args):
        self.args = args

    def test_append(self):
        output_dir = self.args.output_dir
        output_lib_path = self.init_lib_data_basic()

        # Append of a single Object, and then append it again.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Object")
        bpy.ops.wm.append(directory=link_dir, filename="LibMesh",
                          instance_object_data=False, set_fake=False, use_recursive=True, do_reuse_local_id=False)

        assert len(bpy.data.meshes) == 1
        assert bpy.data.meshes[0].library is None
        assert bpy.data.meshes[0].use_fake_user is False
        assert bpy.data.meshes[0].users == 1
        assert bpy.data.meshes[0].library_weak_reference is not None
        assert bpy.data.meshes[0].library_weak_reference.filepath == output_lib_path
        assert bpy.data.meshes[0].library_weak_reference.id_name == "MELibMesh"
        assert len(bpy.data.objects) == 1
        for ob in bpy.data.objects:
            assert ob.library is None
            assert ob.library_weak_reference is None
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        bpy.ops.wm.append(directory=link_dir, filename="LibMesh",
                          instance_object_data=False, set_fake=False, use_recursive=True, do_reuse_local_id=True)

        assert len(bpy.data.meshes) == 1
        assert bpy.data.meshes[0].library is None
        assert bpy.data.meshes[0].use_fake_user is False
        assert bpy.data.meshes[0].users == 2
        assert bpy.data.meshes[0].library_weak_reference is not None
        assert bpy.data.meshes[0].library_weak_reference.filepath == output_lib_path
        assert bpy.data.meshes[0].library_weak_reference.id_name == "MELibMesh"
        assert len(bpy.data.objects) == 2
        for ob in bpy.data.objects:
            assert ob.library is None
            assert ob.library_weak_reference is None
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        bpy.ops.wm.append(directory=link_dir, filename="LibMesh",
                          instance_object_data=False, set_fake=False, use_recursive=True, do_reuse_local_id=False)

        assert len(bpy.data.meshes) == 2
        assert bpy.data.meshes[0].library_weak_reference is None
        assert bpy.data.meshes[1].library is None
        assert bpy.data.meshes[1].use_fake_user is False
        assert bpy.data.meshes[1].users == 1
        assert bpy.data.meshes[1].library_weak_reference is not None
        assert bpy.data.meshes[1].library_weak_reference.filepath == output_lib_path
        assert bpy.data.meshes[1].library_weak_reference.id_name == "MELibMesh"
        assert len(bpy.data.objects) == 3
        for ob in bpy.data.objects:
            assert ob.library is None
            assert ob.library_weak_reference is None
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here


class TestBlendLibLibraryReload(TestBlendLibLinkHelper):

    def __init__(self, args):
        self.args = args

    def test_link_reload(self):
        output_dir = self.args.output_dir
        output_lib_path = self.init_lib_data_basic()

        # Simple link of a single Object, and reload.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Object")
        bpy.ops.wm.link(directory=link_dir, filename="LibMesh")

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        orig_data = self.blender_data_to_tuple(bpy.data, "orig_data")

        bpy.ops.wm.lib_reload(library=bpy.data.objects[0].name)

        reload_data = self.blender_data_to_tuple(bpy.data, "reload_data")

        print(orig_data)
        print(reload_data)
        assert orig_data == reload_data


class TestBlendLibLibraryRelocate(TestBlendLibLinkHelper):

    def __init__(self, args):
        self.args = args

    def test_link_relocate(self):
        output_dir = self.args.output_dir
        output_lib_path = self.init_lib_data_basic()

        # Simple link of a single Object, and reload.
        self.reset_blender()

        link_dir = os.path.join(output_lib_path, "Object")
        bpy.ops.wm.link(directory=link_dir, filename="LibMesh")

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1
        assert len(bpy.data.collections) == 0  # Scene's master collection is not listed here

        orig_data = self.blender_data_to_tuple(bpy.data, "orig_data")

        lib_path, lib_ext = os.path.splitext(output_lib_path)
        new_lib_path = lib_path + "_relocate" + lib_ext
        os.replace(output_lib_path, new_lib_path)

        bpy.ops.wm.lib_relocate(library=bpy.data.objects[0].name, directory="", filename=new_lib_path)

        relocate_data = self.blender_data_to_tuple(bpy.data, "relocate_data")

        print(orig_data)
        print(relocate_data)
        assert orig_data == relocate_data


# Python library loader context manager.
class TestBlendLibDataLibrariesLoad(TestBlendLibLinkHelper):

    def __init__(self, args):
        self.args = args

    def do_libload_init(self):
        output_dir = self.args.output_dir
        output_lib_path = self.init_lib_data_basic()

        # Simple link of a single Object, and reload.
        self.reset_blender()

        return output_lib_path

    def do_libload(self, **load_kwargs):
        with bpy.data.libraries.load(**load_kwargs) as lib_ctx:
            lib_src, lib_link = lib_ctx

            assert len(lib_src.meshes) == 1
            assert len(lib_src.objects) == 1
            assert len(lib_src.collections) == 1

            assert len(lib_link.meshes) == 0
            assert len(lib_link.objects) == 0
            assert len(lib_link.collections) == 0

            lib_link.collections.append(lib_src.collections[0])

        # Linking/append/liboverride happens when living the context manager.


class TestBlendLibDataLibrariesLoadAppend(TestBlendLibDataLibrariesLoad):

    def test_libload_append(self):
        output_lib_path = self.do_libload_init()
        self.do_libload(filepath=output_lib_path, link=False, create_liboverrides=False)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1  # This code does no instantiation.
        assert len(bpy.data.collections) == 1

        # Append, so all data should have been made local.
        assert bpy.data.meshes[0].library is None
        assert bpy.data.objects[0].library is None
        assert bpy.data.collections[0].library is None


class TestBlendLibDataLibrariesLoadLink(TestBlendLibDataLibrariesLoad):

    def test_libload_link(self):
        output_lib_path = self.do_libload_init()
        self.do_libload(filepath=output_lib_path, link=True, create_liboverrides=False)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1  # This code does no instantiation.
        assert len(bpy.data.collections) == 1

        # Link, so all data should have remained linked.
        assert bpy.data.meshes[0].library is not None
        assert bpy.data.objects[0].library is not None
        assert bpy.data.collections[0].library is not None


class TestBlendLibDataLibrariesLoadLibOverride(TestBlendLibDataLibrariesLoad):

    def test_libload_liboverride(self):
        output_lib_path = self.do_libload_init()
        self.do_libload(filepath=output_lib_path, link=True, create_liboverrides=True)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1  # This code does no instantiation.
        assert len(bpy.data.collections) == 2  # The linked one and its local liboverride.

        # Link + LibOverride, so linked data should have remained linked.
        assert bpy.data.meshes[-1].library is not None
        assert bpy.data.objects[-1].library is not None
        assert bpy.data.collections[-1].library is not None

        # Only explicitely linked data gets a liboverride, without any handling of hierarchy/dependencies.
        assert bpy.data.collections[0].library is None
        assert bpy.data.collections[0].is_runtime_data is False
        assert bpy.data.collections[0].override_library is not None
        assert bpy.data.collections[0].override_library.reference == bpy.data.collections[-1]

        # Should create another liboverride for the linked collection.
        self.do_libload(filepath=output_lib_path, link=True, create_liboverrides=True, reuse_liboverrides=False)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1  # This code does no instantiation.
        assert len(bpy.data.collections) == 3  # The linked one and its two local liboverrides.

        # Link + LibOverride, so linked data should have remained linked.
        assert bpy.data.meshes[-1].library is not None
        assert bpy.data.objects[-1].library is not None
        assert bpy.data.collections[-1].library is not None

        # Only explicitely linked data gets a liboverride, without any handling of hierarchy/dependencies.
        assert bpy.data.collections[1].library is None
        assert bpy.data.collections[1].is_runtime_data is False
        assert bpy.data.collections[1].override_library is not None
        assert bpy.data.collections[1].override_library.reference == bpy.data.collections[-1]

        # This call should not change anything, first liboverrides should be found and 'reused'.
        self.do_libload(filepath=output_lib_path, link=True, create_liboverrides=True, reuse_liboverrides=True)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1  # This code does no instantiation.
        assert len(bpy.data.collections) == 3  # The linked one and its two local liboverrides.

        # Link + LibOverride, so linked data should have remained linked.
        assert bpy.data.meshes[-1].library is not None
        assert bpy.data.objects[-1].library is not None
        assert bpy.data.collections[-1].library is not None

        # Only explicitely linked data gets a liboverride, without any handling of hierarchy/dependencies.
        assert bpy.data.collections[1].library is None
        assert bpy.data.collections[1].is_runtime_data is False
        assert bpy.data.collections[1].override_library is not None
        assert bpy.data.collections[1].override_library.reference == bpy.data.collections[-1]

    def test_libload_liboverride_runtime(self):
        output_lib_path = self.do_libload_init()
        self.do_libload(filepath=output_lib_path, link=True,
                        create_liboverrides=True,
                        create_liboverrides_runtime=True)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1  # This code does no instantiation.
        assert len(bpy.data.collections) == 2  # The linked one and its local liboverride.

        # Link + LibOverride, so linked data should have remained linked.
        assert bpy.data.meshes[-1].library is not None
        assert bpy.data.objects[-1].library is not None
        assert bpy.data.collections[-1].library is not None

        # Only explicitely linked data gets a liboverride, without any handling of hierarchy/dependencies.
        assert bpy.data.collections[0].library is None
        assert bpy.data.collections[0].is_runtime_data is True
        assert bpy.data.collections[0].override_library is not None
        assert bpy.data.collections[0].override_library.reference == bpy.data.collections[-1]

        # This call should not change anything, first liboverrides should be found and 'reused'.
        self.do_libload(filepath=output_lib_path,
                        link=True,
                        create_liboverrides=True,
                        create_liboverrides_runtime=True,
                        reuse_liboverrides=True)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1  # This code does no instantiation.
        assert len(bpy.data.collections) == 2  # The linked one and its local liboverride.

        # Link + LibOverride, so linked data should have remained linked.
        assert bpy.data.meshes[-1].library is not None
        assert bpy.data.objects[-1].library is not None
        assert bpy.data.collections[-1].library is not None

        # Only explicitely linked data gets a liboverride, without any handling of hierarchy/dependencies.
        assert bpy.data.collections[0].library is None
        assert bpy.data.collections[0].is_runtime_data is True
        assert bpy.data.collections[0].override_library is not None
        assert bpy.data.collections[0].override_library.reference == bpy.data.collections[-1]

        # Should create another liboverride for the linked collection, since this time we request a non-runtime one.
        self.do_libload(filepath=output_lib_path,
                        link=True,
                        create_liboverrides=True,
                        create_liboverrides_runtime=False,
                        reuse_liboverrides=True)

        assert len(bpy.data.meshes) == 1
        assert len(bpy.data.objects) == 1  # This code does no instantiation.
        assert len(bpy.data.collections) == 3  # The linked one and its two local liboverrides.

        # Link + LibOverride, so linked data should have remained linked.
        assert bpy.data.meshes[-1].library is not None
        assert bpy.data.objects[-1].library is not None
        assert bpy.data.collections[-1].library is not None

        # Only explicitely linked data gets a liboverride, without any handling of hierarchy/dependencies.
        assert bpy.data.collections[1].library is None
        assert bpy.data.collections[1].is_runtime_data is False
        assert bpy.data.collections[1].override_library is not None
        assert bpy.data.collections[1].override_library.reference == bpy.data.collections[-1]


TESTS = (
    TestBlendLibLinkSaveLoadBasic,
    TestBlendLibLinkAnimation,
    TestBlendLibLinkIndirect,

    TestBlendLibAppendBasic,
    TestBlendLibAppendReuseID,

    TestBlendLibLibraryReload,
    TestBlendLibLibraryRelocate,

    TestBlendLibDataLibrariesLoadAppend,
    TestBlendLibDataLibrariesLoadLink,
    TestBlendLibDataLibrariesLoadLibOverride,
)


def argparse_create():
    import argparse

    # When --help or no args are given, print this help
    description = "Test basic IO of blend file."
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument(
        "--output-dir",
        dest="output_dir",
        default=".",
        help="Where to output temp saved blendfiles",
        required=False,
    )

    return parser


def main():
    args = argparse_create().parse_args()

    # Don't write thumbnails into the home directory.
    bpy.context.preferences.filepaths.file_preview_type = 'NONE'

    for Test in TESTS:
        Test(args).run_all_tests()


if __name__ == '__main__':
    import sys
    sys.argv = [__file__] + (sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])
    main()