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
|
# SPDX-FileCopyrightText: 2017-2022 Blender Authors
#
# SPDX-License-Identifier: GPL-2.0-or-later
# ./blender.bin --background --python tests/python/bl_pyapi_idprop_datablock.py -- --verbose
import contextlib
import inspect
import io
import os
import re
import sys
import tempfile
import bpy
from bpy.types import UIList
arr_len = 100
ob_cp_count = 100
# Set before execution.
lib_path = None
test_path = None
def print_fail_msg_and_exit(msg):
def __LINE__():
try:
raise Exception
except:
return sys.exc_info()[2].tb_frame.f_back.f_back.f_back.f_lineno
def __FILE__():
return inspect.currentframe().f_code.co_filename
print("'%s': %d >> %s" % (__FILE__(), __LINE__(), msg), file=sys.stderr)
sys.stderr.flush()
sys.stdout.flush()
os._exit(1)
def expect_false_or_abort(expr, msg=None):
if not expr:
if not msg:
msg = "test failed"
print_fail_msg_and_exit(msg)
def expect_exception_or_abort(*, fn, ex):
try:
fn()
exception = False
except ex:
exception = True
if exception:
return # OK
print_fail_msg_and_exit("test failed")
def expect_output_or_abort(*, fn, match_stderr=None, match_stdout=None):
stdout, stderr = io.StringIO(), io.StringIO()
with (contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(stdout)):
fn()
for (handle, match) in ((stdout, match_stdout), (stderr, match_stderr)):
if not match:
continue
output = handle.getvalue()
if not re.match(match, output):
print_fail_msg_and_exit("%r not found in %r" % (match, output))
class TestClass(bpy.types.PropertyGroup):
test_prop: bpy.props.PointerProperty(type=bpy.types.Object)
name: bpy.props.StringProperty()
def get_scene(lib_name, sce_name):
for s in bpy.data.scenes:
if s.name == sce_name:
if (
(s.library and s.library.name == lib_name) or
(lib_name is None and s.library is None)
):
return s
def init():
bpy.utils.register_class(TestClass)
bpy.types.Object.prop_array = bpy.props.CollectionProperty(
name="prop_array",
type=TestClass)
bpy.types.Object.prop = bpy.props.PointerProperty(type=bpy.types.Object)
def make_lib():
bpy.ops.wm.read_factory_settings()
# datablock pointer to the Camera object
bpy.data.objects["Cube"].prop = bpy.data.objects['Camera']
# array of datablock pointers to the Light object
for i in range(0, arr_len):
a = bpy.data.objects["Cube"].prop_array.add()
a.test_prop = bpy.data.objects['Light']
a.name = a.test_prop.name
# make unique named copy of the cube
ob = bpy.data.objects["Cube"].copy()
bpy.context.collection.objects.link(ob)
bpy.data.objects["Cube.001"].name = "Unique_Cube"
# duplicating of Cube
for i in range(0, ob_cp_count):
ob = bpy.data.objects["Cube"].copy()
bpy.context.collection.objects.link(ob)
# nodes
bpy.data.scenes["Scene"].use_nodes = True
bpy.data.scenes["Scene"].node_tree.nodes['Render Layers']["prop"] =\
bpy.data.objects['Camera']
# rename scene and save
bpy.data.scenes["Scene"].name = "Scene_lib"
bpy.ops.wm.save_as_mainfile(filepath=lib_path)
def check_lib():
# check pointer
expect_false_or_abort(bpy.data.objects["Cube"].prop == bpy.data.objects['Camera'])
# check array of pointers in duplicated object
for i in range(0, arr_len):
expect_false_or_abort(
bpy.data.objects["Cube.001"].prop_array[i].test_prop ==
bpy.data.objects['Light'])
def check_lib_linking():
# open startup file
bpy.ops.wm.read_factory_settings()
# link scene to the startup file
with bpy.data.libraries.load(lib_path, link=True) as (data_from, data_to):
data_to.scenes = ["Scene_lib"]
bpy.context.window.scene = bpy.data.scenes["Scene_lib"]
o = bpy.data.scenes["Scene_lib"].objects['Unique_Cube']
expect_false_or_abort(o.prop_array[0].test_prop == bpy.data.scenes["Scene_lib"].objects['Light'])
expect_false_or_abort(o.prop == bpy.data.scenes["Scene_lib"].objects['Camera'])
expect_false_or_abort(o.prop.library == o.library)
bpy.ops.wm.save_as_mainfile(filepath=test_path)
def check_linked_scene_copying():
# full copy of the scene with datablock props
bpy.ops.wm.open_mainfile(filepath=test_path)
bpy.ops.scene.new(type='FULL_COPY')
bpy.context.window.scene = get_scene("lib.blend", "Scene_lib")
# check save/open
bpy.ops.wm.save_as_mainfile(filepath=test_path)
bpy.ops.wm.open_mainfile(filepath=test_path)
intern_sce = get_scene(None, "Scene_lib")
extern_sce = get_scene("lib.blend", "Scene_lib")
# check node's props
# must point to own scene camera
expect_false_or_abort(
intern_sce.node_tree.nodes['Render Layers']["prop"] and
not (intern_sce.node_tree.nodes['Render Layers']["prop"] ==
extern_sce.node_tree.nodes['Render Layers']["prop"]))
def check_scene_copying():
# full copy of the scene with datablock props
bpy.ops.wm.open_mainfile(filepath=lib_path)
bpy.context.window.scene = bpy.data.scenes["Scene_lib"]
bpy.ops.scene.new(type='FULL_COPY')
path = test_path + "_"
# check save/open
bpy.ops.wm.save_as_mainfile(filepath=path)
bpy.ops.wm.open_mainfile(filepath=path)
first_sce = get_scene(None, "Scene_lib")
second_sce = get_scene(None, "Scene_lib.001")
# check node's props
# must point to own scene camera
expect_false_or_abort(
not (first_sce.node_tree.nodes['Render Layers']["prop"] ==
second_sce.node_tree.nodes['Render Layers']["prop"]))
# count users
def test_users_counting():
bpy.ops.wm.read_factory_settings()
Light_us = bpy.data.objects["Light"].data.users
n = 1000
for i in range(0, n):
bpy.data.objects["Cube"]["a%s" % i] = bpy.data.objects["Light"].data
expect_false_or_abort(bpy.data.objects["Light"].data.users == Light_us + n)
for i in range(0, int(n / 2)):
bpy.data.objects["Cube"]["a%s" % i] = 1
expect_false_or_abort(bpy.data.objects["Light"].data.users == Light_us + int(n / 2))
# linking
def test_linking():
make_lib()
check_lib()
check_lib_linking()
check_linked_scene_copying()
check_scene_copying()
# check restrictions for datablock pointers for some classes; GUI for manual testing
def test_restrictions1():
class TEST_Op(bpy.types.Operator):
bl_idname = 'scene.test_op'
bl_label = 'Test'
bl_options = {"INTERNAL"}
str_prop: bpy.props.StringProperty(name="str_prop")
# disallow registration of datablock properties in operators
# will be checked in the draw method (test manually)
# also, see console:
# ValueError: bpy_struct "SCENE_OT_test_op" doesn't support datablock properties
id_prop: bpy.props.PointerProperty(type=bpy.types.Object)
def execute(self, context):
return {'FINISHED'}
# just panel for testing the poll callback with lots of objects
class TEST_PT_DatablockProp(bpy.types.Panel):
bl_label = "Datablock IDProp"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "render"
def draw(self, context):
self.layout.prop_search(context.scene, "prop", bpy.data, "objects")
self.layout.template_ID(context.scene, "prop1")
self.layout.prop_search(context.scene, "prop2", bpy.data, "node_groups")
op = self.layout.operator(TEST_Op.bl_idname)
op.str_prop = "test string"
def test_fn(op):
op["ob"] = bpy.data.objects['Unique_Cube']
expect_exception_or_abort(
fn=lambda: test_fn(op),
ex=ImportError,
)
expect_false_or_abort(not hasattr(op, "id_prop"))
bpy.utils.register_class(TEST_PT_DatablockProp)
expect_output_or_abort(
fn=lambda: bpy.utils.register_class(TEST_Op),
match_stderr="^ValueError: bpy_struct \"SCENE_OT_test_op\" registration error:",
)
def poll(self, value):
return value.name in bpy.data.scenes["Scene_lib"].objects
def poll1(self, value):
return True
bpy.types.Scene.prop = bpy.props.PointerProperty(type=bpy.types.Object)
bpy.types.Scene.prop1 = bpy.props.PointerProperty(type=bpy.types.Object, poll=poll)
bpy.types.Scene.prop2 = bpy.props.PointerProperty(type=bpy.types.NodeTree, poll=poll1)
# check poll effect on UI (poll returns false => red alert)
bpy.context.scene.prop = bpy.data.objects["Light.001"]
bpy.context.scene.prop1 = bpy.data.objects["Light.001"]
# check incorrect type assignment
def sub_test():
# NodeTree id_prop
bpy.context.scene.prop2 = bpy.data.objects["Light.001"]
expect_exception_or_abort(
fn=sub_test,
ex=TypeError,
)
bpy.context.scene.prop2 = bpy.data.node_groups.new("Shader", "ShaderNodeTree")
# NOTE: keep since the author thought this useful information.
# print(
# "Please, test GUI performance manually on the Render tab, '%s' panel" %
# TEST_PT_DatablockProp.bl_label, file=sys.stderr,
# )
sys.stderr.flush()
# check some possible regressions
def test_regressions():
bpy.types.Object.prop_str = bpy.props.StringProperty(name="str")
bpy.data.objects["Unique_Cube"].prop_str = "test"
bpy.types.Object.prop_gr = bpy.props.PointerProperty(
name="prop_gr",
type=TestClass,
description="test")
bpy.data.objects["Unique_Cube"].prop_gr = None
# test restrictions for datablock pointers
def test_restrictions2():
class TestClassCollection(bpy.types.PropertyGroup):
prop: bpy.props.CollectionProperty(
name="prop_array",
type=TestClass)
bpy.utils.register_class(TestClassCollection)
class TestPrefs(bpy.types.AddonPreferences):
bl_idname = "testprefs"
# expecting crash during registering
my_prop2: bpy.props.PointerProperty(type=TestClass)
prop: bpy.props.PointerProperty(
name="prop",
type=TestClassCollection,
description="test")
bpy.types.Addon.a = bpy.props.PointerProperty(type=bpy.types.Object)
class TEST_UL_list(UIList):
test: bpy.props.PointerProperty(type=bpy.types.Object)
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
layout.prop(item, "name", text="", emboss=False, icon_value=icon)
expect_exception_or_abort(
fn=lambda: bpy.utils.register_class(TestPrefs),
ex=ValueError,
)
expect_exception_or_abort(
fn=lambda: bpy.utils.register_class(TEST_UL_list),
ex=ValueError,
)
bpy.utils.unregister_class(TestClassCollection)
def main():
global lib_path
global test_path
with tempfile.TemporaryDirectory() as temp_dir:
lib_path = os.path.join(temp_dir, "lib.blend")
test_path = os.path.join(temp_dir, "test.blend")
init()
test_users_counting()
test_linking()
test_restrictions1()
expect_exception_or_abort(
fn=test_regressions,
ex=AttributeError,
)
test_restrictions2()
if __name__ == "__main__":
main()
|