def testVersionCheck(self): # Useful for debugging accessor Tf.Debug.SetDebugSymbolsByName("USDMAYA_PLUG_INFO_VERSION", 1) # Loading the plugin will trigger registration of plugins from MAYA_PXR_PLUGINPATH_NAME # path try: if not cmds.pluginInfo("mayaUsdPlugin", loaded=True, query=True): cmds.loadPlugin("mayaUsdPlugin", quiet=True) except: print(sys.exc_info()[1]) print("Unable to load mayaUsdPlugin") # All test plugins derive from _TestPlugBase<1> base1Subclasses = Tf.Type.FindByName( '_TestPlugBase<1>').GetAllDerivedTypes() # All checkes should pass for testPlugModule1,2,3 plugin paths based on # mayaUsdPluginInfo.json self.assertIn('TestPlugModule1.TestPlugPythonDerived1', base1Subclasses) self.assertIn('TestPlugModule2.TestPlugPythonDerived2', base1Subclasses) self.assertIn('TestPlugModule3.TestPlugPythonDerived3', base1Subclasses) # Following plugins should never get register since they shouldn't pass version check with self.assertRaises(TypeError): ppd4 = Plug.Registry().GetPluginForType( 'TestPlugModule4.TestPlugPythonDerived4') with self.assertRaises(TypeError): ppd5 = Plug.Registry().GetPluginForType( 'TestPlugModule5.TestPlugPythonDerived5') with self.assertRaises(TypeError): ppd6 = Plug.Registry().GetPluginForType( 'TestPlugModule6.TestPlugPythonDerived6')
def test_Registration(self): # pre-load some plugins import TestPlugModuleLoaded import TestPlugModuleLoadedBadBase listener = NoticeListener() # Register dso plugins. Discard possible exception due to TestPlugDsoEmpty. # The exception only shows up here if it happens in the main thread so we # can't rely on it. try: Plug.Registry().RegisterPlugins(testPluginsDsoSearch) except RuntimeError: pass # Verify we received the appropriate notification self.assertEqual(listener.numReceived, 1) self.assertEqual(set([p.name for p in listener.newPlugins]), set(['TestPlugDso1', 'TestPlugDso2', 'TestPlugDso3', 'TestPlugDsoUnloadable'])) # Register python module plugins with nested(ExpectedErrors(2), RequiredException(RuntimeError)): Plug.Registry().RegisterPlugins(testPluginsPythonSearch) # Verify we received the appropriate notification self.assertEqual(listener.numReceived, 2) self.assertEqual(set([p.name for p in listener.newPlugins]), set(['TestPlugDso1', 'TestPlugDso2', 'TestPlugDso3', 'TestPlugDsoUnloadable', 'TestPlugModule1', 'TestPlugModule2', 'TestPlugModule3', 'TestPlugModuleDepBadBase', 'TestPlugModuleDepBadDep', 'TestPlugModuleDepBadDep2', 'TestPlugModuleDepBadLoad', 'TestPlugModuleDepCycle', 'TestPlugModuleLoaded', 'TestPlugModuleLoadedBadBase', 'TestPlugModuleUnloadable'])) # Check available subclasses of TestPlugBase<1> base1Subclasses = Tf.Type.FindByName('_TestPlugBase<1>').GetAllDerivedTypes() base1SubclassesExpected = \ ('_TestPlugDerived0', 'TestPlugDerived1', 'TestPlugPythonDerived1', 'TestPlugModuleLoaded.TestPlugPythonLoaded', 'TestPlugModuleLoadedBadBase.TestPlugPythonLoadedBadBase', 'TestPlugUnloadable', 'TestPlugPythonUnloadable') for sc in base1SubclassesExpected: self.assertIn(sc, base1Subclasses) self.assertEqual(len(base1Subclasses), len(base1SubclassesExpected)) # Check available subclasses of _TestPlugBase<2> base2Subclasses = Tf.Type.FindByName('_TestPlugBase<2>').GetAllDerivedTypes() base2SubclassesExpected = ('TestPlugDerived2', 'TestPlugPythonDerived2') for sc in base2SubclassesExpected: self.assertIn(sc, base2Subclasses) self.assertEqual(len(base2Subclasses), len(base2SubclassesExpected)) allPlugins = Plug.Registry().GetAllPlugins() self.assertTrue(len(allPlugins) >= 8)
def loadPlugins(): containerTypes = Plug.Registry.GetAllDerivedTypes(PluginContainerTfType) # Find all plugins and plugin container types through libplug. plugins = dict() for containerType in containerTypes: plugin = Plug.Registry().GetPluginForType(containerType) pluginContainerTypes = plugins.setdefault(plugin, []) pluginContainerTypes.append(containerType) # Load each plugin in alphabetical order by name. For each plugin, load all # of its containers in alphabetical order by type name. allContainers = [] for plugin in sorted(plugins.keys(), key=lambda plugin: plugin.name): plugin.Load() pluginContainerTypes = sorted( plugins[plugin], key=lambda containerType: containerType.typeName) for containerType in pluginContainerTypes: if containerType.pythonClass is None: print( ("WARNING: Missing plugin container '{}' from plugin " "'{}'. Make sure the container is a defined Tf.Type and " "the container's import path matches the path in " "plugInfo.json.").format(containerType.typeName, plugin.name)) continue container = containerType.pythonClass() allContainers.append(container) # No plugins to load, so don't create a registry. if len(allContainers) == 0: return None for container in allContainers: container.registerPlugins()
def test_GetAvailableResolvers(self): """Tests ArGetAvailableResolvers and ArCreateResolver APIs via _TestResolver1 and _TestResolver2 subclasses.""" # Register test resolver plugin and verify we have the # expected ArResolver subclasses. pr = Plug.Registry() plugins = pr.RegisterPlugins(testPluginsDsoSearch) self.assertEqual(len(plugins), 1) self.assertEqual( set(pr.GetAllDerivedTypes('ArResolver')), set([ Tf.Type.FindByName('ArDefaultResolver'), Tf.Type.FindByName('_TestResolver1'), Tf.Type.FindByName('_TestResolver2') ])) # Set _TestResolver2 to be the preferred resolver; # otherwise, _TestResolver1 would be initially constructed # by the call to Ar.GetResolver() below since its typename # comes before _TestResolver2. Ar.SetPreferredResolver('_TestResolver2') # Invoke Ar.GetResolver(). This will cause _TestResolver1 # and _TestResolver2 to be created. These classes test # ArGetAvailableResolvers and ArCreateResolver internally. resolver = Ar.GetResolver()
def test_NewPluginRegistrationNotice(self): # Add some behavior entries self.assertTrue( UsdShade.ConnectableAPI.HasConnectableAPI( Tf.Type.FindByName('UsdShadeMaterial'))) self.assertFalse( UsdShade.ConnectableAPI.HasConnectableAPI( _SchemaTypeFindByName("UsdShadeTestTyped"))) # check a material's behavior before registering new plugins stage = Usd.Stage.CreateInMemory() material = UsdShade.Material.Define(stage, "/Mat") matConnectable = UsdShade.ConnectableAPI(material) self.assertTrue(matConnectable) self.assertTrue(matConnectable.IsContainer()) # register new plugins, to trigger a call to _DidRegisterPlugins, which # should prune the behavior cache off any entry which has a null # behavior defined pr = Plug.Registry() testPlugins = pr.RegisterPlugins(os.path.abspath("resources/plugins2")) self.assertTrue(len(testPlugins) == 1) # check material connectableAPI again if it has the correct behavior # still self.assertTrue(matConnectable) self.assertTrue(matConnectable.IsContainer())
def test_MetadataAccess(self): base1Subclasses = Tf.Type.FindByName('_TestPlugBase<1>').derivedTypes self.assertIn('TestPlugUnloadable', base1Subclasses) plugin = Plug.Registry().GetPluginForType('TestPlugUnloadable') self.assertIsNotNone(plugin) metadata = plugin.metadata self.assertIsNotNone(metadata) self.assertTrue(metadata.has_key('Types')) self.assertTrue(metadata['Types'].has_key('TestPlugUnloadable')) md = metadata['Types']['TestPlugUnloadable'] self.assertTrue(md == plugin.GetMetadataForType( Tf.Type.FindByName('TestPlugUnloadable'))) self.assertTrue(md.has_key('bases')) self.assertTrue(md['bases'] == ['_TestPlugBase<1>']) self.assertTrue(md.has_key('description')) self.assertTrue(md['description'] == 'unloadable plugin') self.assertTrue(md.has_key('notLoadable')) self.assertTrue(md['notLoadable'] == True) self.assertTrue(md.has_key('vectorInt')) self.assertTrue(md['vectorInt'] == [1, 2, 3]) self.assertTrue(md.has_key('vectorString')) self.assertTrue(md['vectorString'] == ["f", "l", "o"]) self.assertTrue(md.has_key('vectorDouble')) self.assertTrue(md['vectorDouble'] == [1.1, 2.2, 3.3]) self.assertTrue(md.has_key('Int')) self.assertTrue(md['Int'] == 4711) self.assertTrue(md.has_key('Double')) self.assertTrue(Gf.IsClose(md['Double'], 0.815, 1e-6))
def test_Basic(self): # Register python module plugins Plug.Registry().RegisterPlugins(os.getcwd() + "/**/") reg = Kind.Registry() self.assertTrue(reg) # Test factory default kinds + config file contributions expectedDefaultKinds = [ 'group', 'model', 'test_model_kind', 'test_root_kind', ] actualDefaultKinds = Kind.Registry.GetAllKinds() # We cannot expect actual to be equal to expected, because there is no # way to prune the site's extension plugins from actual. # assertEqual(sorted(expectedDefaultKinds), sorted(actualDefaultKinds)) for expected in expectedDefaultKinds: self.assertTrue(Kind.Registry.HasKind(expected)) self.assertTrue(expected in actualDefaultKinds) # Check the 'test_model_kind' kind from the TestKindModule_plugInfo.json self.assertTrue(Kind.Registry.HasKind('test_root_kind')) self.assertEqual(Kind.Registry.GetBaseKind('test_root_kind'), '') # Check the 'test_model_kind' kind from the TestKindModule_plugInfo.json self.assertTrue(Kind.Registry.HasKind('test_model_kind')) self.assertEqual(Kind.Registry.GetBaseKind('test_model_kind'), 'model')
def setUpClass(cls): pr = Plug.Registry() testPlugins = pr.RegisterPlugins(os.path.abspath("resources")) assert len(testPlugins) == 1, \ "Failed to load expected test plugin" assert testPlugins[0].name == "testUsdAppliedAPISchemas", \ "Failed to load expected test plugin"
def test_ManufacturingPythonDerivedClasses(self): ppd1 = Plug.Registry().GetPluginForType( 'TestPlugModule1.TestPlugPythonDerived1') self.assertIsNotNone(ppd1) self.assertFalse(ppd1.isLoaded) self.assertTrue(ppd1.isPythonModule) ppd2 = Plug.Registry().GetPluginForType( 'TestPlugModule2.TestPlugPythonDerived2') self.assertIsNotNone(ppd2) self.assertFalse(ppd2.isLoaded) self.assertTrue(ppd2.isPythonModule) # Load and construct an instance of TestPlugPythonDerived1 # (Loading should add TestPlugModule1 to the namespace) ppd1.Load() tpd1 = TestPlugModule1.TestPlugPythonDerived1() self.assertEqual(tpd1.GetTypeName(), 'TestPlugModule1.TestPlugPythonDerived1') self.assertTrue(ppd1.isLoaded) # Load and construct an instance of TestPlugPythonDerived2 # (Loading should add TestPlugModule2 to the namespace) ppd2.Load() tpd2 = TestPlugModule2.TestPlugPythonDerived2() self.assertEqual(tpd2.GetTypeName(), 'TestPlugModule2.TestPlugPythonDerived2') self.assertTrue(ppd2.isLoaded) # Check that loading an already loaded plugin is a noop. ppd2.Load() # Check that plugin correctly reports its declared types. self.assertFalse( ppd1.DeclaresType(Tf.Type('_TestPlugBase<1>'), includeSubclasses=False)) self.assertTrue( ppd1.DeclaresType(Tf.Type('_TestPlugBase<1>'), includeSubclasses=True)) self.assertTrue( ppd1.DeclaresType( Tf.Type('TestPlugModule1.TestPlugPythonDerived1'), includeSubclasses=False)) self.assertTrue( ppd1.DeclaresType( Tf.Type('TestPlugModule1.TestPlugPythonDerived1'), includeSubclasses=True))
def test_Registry(self): """ Test basic registry operations. Also ensures that the discovery process works correctly. """ # Register test plugins and verify they have been found pr = Plug.Registry() plugins = pr.RegisterPlugins(testPluginsDsoSearch) # Verify the test plugins have been found. When building monolithic # we should find at least these derived types. self.assertEqual(len(plugins), 1) fsdpType = Tf.Type.FindByName('_NdrFilesystemDiscoveryPlugin') tdpType = Tf.Type.FindByName('_NdrTestDiscoveryPlugin') self.assertEqual( set([fsdpType, tdpType]) - set(pr.GetAllDerivedTypes('NdrDiscoveryPlugin')), set()) self.assertEqual( set([ Tf.Type.FindByName('_NdrArgsTestParserPlugin'), Tf.Type.FindByName('_NdrOslTestParserPlugin') ]) - set(pr.GetAllDerivedTypes('NdrParserPlugin')), set()) # Instantiating the registry will kick off the discovery process. # This test assumes the PXR_NDR_SKIP_DISCOVERY_PLUGIN_DISCOVERY has # been set prior to being run to ensure built-in plugins are not # found. Instead we'll list the plugins we want explicitly. # Setting this from within the script does not work on Windows. # os.environ["PXR_NDR_SKIP_DISCOVERY_PLUGIN_DISCOVERY"] = "" reg = Sdr.Registry() reg.SetExtraDiscoveryPlugins([fsdpType, tdpType]) nodes = reg.GetShaderNodesByFamily() assert len(nodes) == 4 assert reg.GetSearchURIs() == ["/TestSearchPath"] assert set(reg.GetNodeNames()) == { "TestNodeARGS", "TestNodeOSL", "TestNodeSameName" } assert id(reg.GetShaderNodeByURI(nodes[0].GetSourceURI())) == id( nodes[0]) assert id(reg.GetShaderNodeByName(nodes[0].GetName())) == id(nodes[0]) argsType = "RmanCpp" oslType = "OSL" # Ensure that the registry can retrieve two nodes of the same name but # different source types assert {argsType, oslType}.issubset(set(reg.GetAllNodeSourceTypes())) assert len(reg.GetShaderNodesByName("TestNodeSameName")) == 2 assert reg.GetShaderNodeByNameAndType("TestNodeSameName", oslType) is not None assert reg.GetShaderNodeByNameAndType("TestNodeSameName", argsType) is not None assert reg.GetShaderNodeByName("TestNodeSameName", [oslType, argsType])\ .GetSourceType() == oslType assert reg.GetShaderNodeByName("TestNodeSameName", [argsType, oslType])\ .GetSourceType() == argsType
def test_Setup(self): # Verify that our test plugin was registered properly. pr = Plug.Registry() self.assertTrue(pr.GetPluginWithName('TestArURIResolver')) self.assertTrue(Tf.Type.FindByName('_TestURIResolver')) self.assertTrue(pr.GetPluginWithName('TestArPackageResolver')) self.assertTrue(Tf.Type.FindByName('_TestPackageResolver'))
def test_LoadingPluginDependencies(self): # Get the plugin for a subclass pd3 = Plug.Registry().GetPluginForType('TestPlugDerived3_3') self.assertIsNotNone(pd3) self.assertFalse(pd3.sLoaded) # Get the plugin for one of its subclass dependencies ppd3 = Plug.Registry().GetPluginForType('TestPlugPythonDerived3_3') self.assertIsNotNone(ppd3) self.assertFalse(ppd3.isLoaded) # Load the plugin using the PlugRegistry Plug.Registry().GetPluginForType('TestPlugDerived3_3').Load() # Check that both the plugin and its dependency were loaded self.assertTrue(pd3.isLoaded) self.assertTrue(ppd3.isLoaded)
def setUpClass(cls): # Register applied schemas pr = Plug.Registry() testPlugins = pr.RegisterPlugins(os.path.abspath("resources")) assert len(testPlugins) == 1, \ "Failed to load expected test plugin" assert testPlugins[0].name == \ "TestUsdUtilsUpdateSchemaWithSdrAttrPruning", \ "Failed to load expected test plugin" return True
def setUpClass(cls): pr = Plug.Registry() testPlugins = pr.RegisterPlugins(os.path.abspath("resources")) assert len(testPlugins) == 1, \ "Failed to load expected test plugin" assert testPlugins[0].name == "testUsdAppliedAPISchemas", \ "Failed to load expected test plugin" cls.SingleApplyAPIType = \ Tf.Type(Usd.SchemaBase).FindDerivedByName("TestSingleApplyAPI") cls.MultiApplyAPIType = \ Tf.Type(Usd.SchemaBase).FindDerivedByName("TestMultiApplyAPI")
def SetupPlugins(): # Register test resolver plugins # Test plugins are installed relative to this script testRoot = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'ArPlugins') pr = Plug.Registry() testResolverPath = os.path.join( testRoot, 'lib/TestArOptionalImplementation*/Resources/') assert pr.RegisterPlugins(testResolverPath)
def setUpClass(cls): """ Load the test modules for discovery and parsing and check basic type registration """ # Register test plugins and verify they have been found cls.pr = Plug.Registry() plugins = cls.pr.RegisterPlugins(testPluginsDsoSearch) # Verify the test plugins have been found. When building monolithic # we should find at least these derived types. assert len(plugins) == 1 cls.tdpType = Tf.Type.FindByName('_NdrTestDiscoveryPlugin') cls.tdp2Type = Tf.Type.FindByName('_NdrTestDiscoveryPlugin2') cls.tppType = Tf.Type.FindByName('_NdrArgsTestParserPlugin') cls.tpp2Type = Tf.Type.FindByName('_NdrOslTestParserPlugin') # We don't check for all the derived types of NdrDiscoveryPlugin # because this test only uses the discovery and parser plugins # that are defined in this testenv assert {cls.tdpType, cls.tdp2Type}.issubset( set(cls.pr.GetAllDerivedTypes('NdrDiscoveryPlugin'))) assert {cls.tppType, cls.tpp2Type }.issubset(set(cls.pr.GetAllDerivedTypes('NdrParserPlugin'))) # Instantiating the registry will kick off the discovery process. # This test assumes the PXR_NDR_SKIP_DISCOVERY_PLUGIN_DISCOVERY # and PXR_NDR_SKIP_PARSER_PLUGIN_DISCOVERY has been set prior to # being run to ensure built-in plugins are not found. Instead # we'll list the plugins we want explicitly. # Setting this from within the script does not work on Windows. # os.environ["PXR_NDR_SKIP_DISCOVERY_PLUGIN_DISCOVERY"] = "" # os.environ["PXR_NDR_SKIP_PARSER_PLUGIN_DISCOVERY"] = "" cls.reg = Sdr.Registry() # Set up the test parser plugins. cls.reg.SetExtraParserPlugins([cls.tppType, cls.tpp2Type]) # We will register the discovery plugins one by one so that we can check # source types are not duplicated in the registry if we have plugins # that discover nodes of the same source type # The _NdrTestDiscoveryPlugin should find discovery results that have # source types of RmanCpp and OSL cls.reg.SetExtraDiscoveryPlugins([cls.tdpType]) assert sorted(cls.reg.GetAllNodeSourceTypes()) == \ [cls.oslType, cls.argsType] # The _NdrTestDiscoveryPlugin2 should find discovery results that have # source types of RmanCpp and glslfx cls.reg.SetExtraDiscoveryPlugins([cls.tdp2Type])
def loadPlugins(usdviewApi, mainWindow): """Find and load all Usdview plugins.""" # Find all the defined container types using libplug. containerTypes = Plug.Registry.GetAllDerivedTypes(PluginContainerTfType) # Find all plugins and plugin container types through libplug. plugins = dict() for containerType in containerTypes: plugin = Plug.Registry().GetPluginForType(containerType) pluginContainerTypes = plugins.setdefault(plugin, []) pluginContainerTypes.append(containerType) # Load each plugin in alphabetical order by name. For each plugin, load all # of its containers in alphabetical order by type name. allContainers = [] for plugin in sorted(plugins.keys(), key=lambda plugin: plugin.name): plugin.Load() pluginContainerTypes = sorted( plugins[plugin], key=lambda containerType: containerType.typeName) for containerType in pluginContainerTypes: if containerType.pythonClass is None: print( ("WARNING: Missing plugin container '{}' from plugin " "'{}'. Make sure the container is a defined Tf.Type and " "the container's import path matches the path in " "plugInfo.json.").format(containerType.typeName, plugin.name), file=sys.stderr) continue container = containerType.pythonClass() allContainers.append(container) # No plugins to load, so don't create a registry. if len(allContainers) == 0: return None # Register all plugins from each container. If there is a naming conflict, # abort plugin initialization. registry = PluginRegistry(usdviewApi) for container in allContainers: try: container.registerPlugins(registry, usdviewApi) except DuplicateCommandPlugin as e: print("WARNING: {}".format(e), file=sys.stderr) print("Plugins will not be loaded.", file=sys.stderr) return None # Allow each plugin to construct UI elements. uiBuilder = PluginUIBuilder(mainWindow) for container in allContainers: container.configureView(registry, uiBuilder) return registry
def setUpClass(cls): testRoot = os.path.join(os.path.dirname(__file__), 'UsdPlugins') testPluginsDso = testRoot + '/lib' testPluginsDsoSearch = testPluginsDso + '/*/Resources/' # Register dso plugins. Discard possible exception due to TestPlugDsoEmpty. # The exception only shows up here if it happens in the main thread so we # can't rely on it. try: Plug.Registry().RegisterPlugins(testPluginsDsoSearch) except RuntimeError: pass
def test_Registry(self): """ Test basic registry operations. Also ensures that the discovery process works correctly. """ # Register test plugins and verify they have been found pr = Plug.Registry() plugins = pr.RegisterPlugins(testPluginsDsoSearch) self.assertEqual(len(plugins), 1) self.assertEqual( set(pr.GetAllDerivedTypes('NdrDiscoveryPlugin')), set([ Tf.Type.FindByName('_NdrFilesystemDiscoveryPlugin'), Tf.Type.FindByName('_NdrTestDiscoveryPlugin') ])) self.assertEqual( set(pr.GetAllDerivedTypes('NdrParserPlugin')), set([ Tf.Type.FindByName('_NdrArgsTestParserPlugin'), Tf.Type.FindByName('_NdrOslTestParserPlugin') ])) # Instantiating the registry will kick off the discovery process reg = Sdr.Registry() nodes = reg.GetShaderNodesByFamily() assert len(nodes) == 4 assert reg.GetSearchURIs() == ["/TestSearchPath"] assert set(reg.GetNodeNames()) == { "TestNodeARGS", "TestNodeOSL", "TestNodeSameName" } assert id(reg.GetShaderNodeByURI(nodes[0].GetSourceURI())) == id( nodes[0]) assert id(reg.GetShaderNodeByName(nodes[0].GetName())) == id(nodes[0]) argsType = "RmanCpp" oslType = "OSL" # Ensure that the registry can retrieve two nodes of the same name but # different source types assert {argsType, oslType}.issubset(set(reg.GetAllNodeSourceTypes())) assert len(reg.GetShaderNodesByName("TestNodeSameName")) == 2 assert reg.GetShaderNodeByNameAndType("TestNodeSameName", oslType) is not None assert reg.GetShaderNodeByNameAndType("TestNodeSameName", argsType) is not None assert reg.GetShaderNodeByName("TestNodeSameName", [oslType, argsType])\ .GetSourceType() == oslType assert reg.GetShaderNodeByName("TestNodeSameName", [argsType, oslType])\ .GetSourceType() == argsType
def setUpClass(cls): # Register applied schemas and auto applied schemas pr = Plug.Registry() testPlugins = pr.RegisterPlugins(os.path.abspath("resources/plugins1")) assert len(testPlugins) == 1, \ "Failed to load expected test plugin" assert testPlugins[0].name == "testUsdShadeConnectableAPIBehavior", \ "Failed to load expected test plugin" cls.AutoApplyDefaultConnectableBehaviorAPI = \ _SchemaTypeFindByName("AutoApplyDefaultConnectableBehaviorAPI") cls.DefaultConnectableBehaviorAPI = \ _SchemaTypeFindByName("DefaultConnectableBehaviorAPI") return True
def setUpClass(cls): testRoot = os.path.join(os.path.dirname(__file__), 'UsdPlugins') testPluginsDso = testRoot + '/lib' testPluginsDsoSearch = testPluginsDso + \ '/TestUsdProceduralExternalAssetsFileFormatPlugin*/Resources/' try: plugins = Plug.Registry().RegisterPlugins(testPluginsDsoSearch) assert len(plugins) == 1 assert plugins[0].name == \ "Test_UsdProceduralExternalAssetsFileFormatPlugin" except RuntimeError: pass
def setUpClass(cls): pr = Plug.Registry() testPlugins = pr.RegisterPlugins(os.path.abspath("resources")) assert len(testPlugins) == 1, \ "Failed to load expected test plugin" assert testPlugins[0].name == "testUsdFallbackPrimTypes", \ "Failed to load expected test plugin" cls.validType1 = Usd.SchemaRegistry.GetConcreteTypeFromSchemaTypeName( "ValidType_1") assert cls.validType1 cls.validType2 = Usd.SchemaRegistry.GetConcreteTypeFromSchemaTypeName( "ValidType_2") assert cls.validType2
def setUpClass(cls): # pre-load some plugins import TestPlugModuleLoaded import TestPlugModuleLoadedBadBase cls.listener1 = NoticeListener() cls.listener2 = NoticeListener() # Register dso plugins. Discard possible exception due to TestPlugDsoEmpty. # The exception only shows up here if it happens in the main thread so we # can't rely on it. try: Plug.Registry().RegisterPlugins(testPluginsDsoSearch) except RuntimeError: pass cls.listener1.Block() # Register python module plugins try: Plug.Registry().RegisterPlugins(testPluginsPythonSearch) except RuntimeError: pass cls.listener2.Block()
def test_ManufacturingCppDerivedClasses(self): # Construct and verify an instance of _TestPlugBase<1> tb1 = Plug._TestPlugBase1() self.assertEqual(tb1.GetTypeName(), '_TestPlugBase<1>') # Get the plugin for TestPlugDerived1 pd1 = Plug.Registry().GetPluginForType('TestPlugDerived1') self.assertIsNotNone(pd1) self.assertFalse(pd1.isLoaded) # Manufacture and verify an instance of TestPlugDerived1 td1 = Plug._TestPlugBase1('TestPlugDerived1') self.assertTrue(td1 and not td1.expired) self.assertEqual(td1.GetTypeName(), 'TestPlugDerived1') self.assertTrue(pd1.isLoaded) # Construct and verify an instance of _TestPlugBase<2> tb2 = Plug._TestPlugBase2() self.assertEqual(tb2.GetTypeName(), '_TestPlugBase<2>') # Get the plugin for TestPlugDerived2 pd2 = Plug.Registry().GetPluginForType('TestPlugDerived2') self.assertIsNotNone(pd2) self.assertFalse(pd2.isLoaded) # Manufacture and verify an instance of TestPlugDerived2 td2 = Plug._TestPlugBase2('TestPlugDerived2') self.assertTrue(td2 and not td2.expired) self.assertEqual(td2.GetTypeName(), 'TestPlugDerived2') self.assertTrue(pd2.isLoaded) # Check that plugin correctly reports its declared types. self.assertFalse(pd1.DeclaresType(Tf.Type('_TestPlugBase<1>'), includeSubclasses=False)) self.assertTrue(pd1.DeclaresType(Tf.Type('_TestPlugBase<1>'), includeSubclasses=True)) self.assertTrue(pd1.DeclaresType(Tf.Type('TestPlugDerived1'), includeSubclasses=False)) self.assertTrue(pd1.DeclaresType(Tf.Type('TestPlugDerived1'), includeSubclasses=True))
def setUpClass(cls): # Register test resolver plugins # Test plugins are installed relative to this script testRoot = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ArPlugins') pr = Plug.Registry() testURIResolverPath = os.path.join( testRoot, 'lib/TestArURIResolver*/Resources/') pr.RegisterPlugins(testURIResolverPath) testPackageResolverPath = os.path.join( testRoot, 'lib/TestArPackageResolver*/Resources/') pr.RegisterPlugins(testPackageResolverPath)
def test_Registration(self): # Verify we received the appropriate notification self.assertEqual(self.listener1.numReceived, 1) self.assertEqual( set([p.name for p in self.listener1.newPlugins]), set([ 'TestPlugDso1', 'TestPlugDso2', 'TestPlugDso3', 'TestPlugDsoUnloadable' ])) # Verify we received the appropriate notification self.assertEqual(self.listener2.numReceived, 2) self.assertEqual( set([p.name for p in self.listener2.newPlugins]), set([ 'TestPlugDso1', 'TestPlugDso2', 'TestPlugDso3', 'TestPlugDsoUnloadable', 'TestPlugModule1', 'TestPlugModule2', 'TestPlugModule3', 'TestPlugModuleDepBadBase', 'TestPlugModuleDepBadDep', 'TestPlugModuleDepBadDep2', 'TestPlugModuleDepBadLoad', 'TestPlugModuleDepCycle', 'TestPlugModuleLoaded', 'TestPlugModuleLoadedBadBase', 'TestPlugModuleUnloadable' ])) # Check available subclasses of TestPlugBase<1> base1Subclasses = Tf.Type.FindByName( '_TestPlugBase<1>').GetAllDerivedTypes() base1SubclassesExpected = \ ('_TestPlugDerived0', 'TestPlugDerived1', 'TestPlugModule1.TestPlugPythonDerived1', 'TestPlugModuleLoaded.TestPlugPythonLoaded', 'TestPlugModuleLoadedBadBase.TestPlugPythonLoadedBadBase', 'TestPlugUnloadable', 'TestPlugPythonUnloadable') for sc in base1SubclassesExpected: self.assertIn(sc, base1Subclasses) self.assertEqual(len(base1Subclasses), len(base1SubclassesExpected)) # Check available subclasses of _TestPlugBase<2> base2Subclasses = Tf.Type.FindByName( '_TestPlugBase<2>').GetAllDerivedTypes() base2SubclassesExpected = ('TestPlugDerived2', 'TestPlugModule2.TestPlugPythonDerived2') for sc in base2SubclassesExpected: self.assertIn(sc, base2Subclasses) self.assertEqual(len(base2Subclasses), len(base2SubclassesExpected)) allPlugins = Plug.Registry().GetAllPlugins() self.assertTrue(len(allPlugins) >= 8)
def test_Basic(self): # Register test plugin testenvDir = os.getcwd() Plug.Registry().RegisterPlugins(testenvDir) # We should pick up the plugInfo.json fallbacks now. self.assertEqual(Usd.Stage.GetGlobalVariantFallbacks()['displayColor'], ['green']) def OpenLayer(name): fullName = '%s.usda' % name layerFile = os.path.abspath(fullName) self.assertTrue(layerFile, 'failed to find @%s@' % fullName) layer = Sdf.Layer.FindOrOpen(layerFile) self.assertTrue(layer, 'failed to open layer @%s@' % fullName) return layer # Open stage. layer = OpenLayer('testAPI_var') stage = Usd.Stage.Open(layer.identifier) self.assertTrue(stage, 'failed to create stage for @%s@' % layer.identifier) sarah = stage.GetPrimAtPath('/Sarah') displayColor = sarah.GetVariantSet('displayColor') self.assertTrue(sarah, 'failed to find prim /Sarah') # Because our test has plugInfo.json that specifies a fallback of green, # we should see green. self.assertEqual(sarah.GetAttribute('color').Get(), Gf.Vec3d(0, 1, 0)) self.assertEqual(displayColor.GetVariantSelection(), 'green') # Now override our process global variant policy and open a new stage. Usd.Stage.SetGlobalVariantFallbacks({'displayColor': ['red']}) self.assertEqual(Usd.Stage.GetGlobalVariantFallbacks(), {'displayColor': ['red']}) stage = Usd.Stage.Open(layer.identifier) sarah = stage.GetPrimAtPath('/Sarah') displayColor = sarah.GetVariantSet('displayColor') # We should now get an attribute that resolves to red self.assertEqual(sarah.GetAttribute('color').Get(), Gf.Vec3d(1, 0, 0)) self.assertEqual(displayColor.GetVariantSelection(), 'red') # Author a variant selection. displayColor.SetVariantSelection('blue') self.assertEqual(sarah.GetAttribute('color').Get(), Gf.Vec3d(0, 0, 1)) self.assertEqual(displayColor.GetVariantSelection(), 'blue')
def test_Basic(self): # Find 'UsdGeomScope' by name, assert its size is unknown to TfType (this is # true since the library is not loaded and the type is only Declare()'d not # Define()'d. plugReg = Plug.Registry() scopeType = plugReg.FindDerivedTypeByName(Usd.Typed, 'UsdGeomScope') self.assertTrue(scopeType) self.assertEqual(scopeType.sizeof, 0, 'Expected Declared() but not Defined() type') # Make a stage with a Scope, ensure we can type-check it. stage = Usd.Stage.CreateInMemory() scope = stage.DefinePrim('/scope', 'Scope') self.assertTrue(scope) self.assertTrue(scope.IsA(Usd.Typed)) # Now ensure that fallbacks from generated schema apply without loading plugins. # Create a Cube prim and assert that size appears as an attribute with a # fallback value, even though there is no scene description for it. cube = stage.DefinePrim('/cube', 'Cube') self.assertTrue(cube) # Unauthored builtins should be reported by GetAttributes and GetProperties. self.assertTrue( 'size' in [attr.GetName() for attr in cube.GetAttributes()]) self.assertTrue( 'size' in [prop.GetName() for prop in cube.GetProperties()]) self.assertTrue('size' in cube.GetPropertyNames()) # ... but should not appear for authored-only queries. self.assertTrue( 'size' not in [attr.GetName() for attr in cube.GetAuthoredAttributes()]) self.assertTrue( 'size' not in [prop.GetName() for prop in cube.GetAuthoredProperties()]) self.assertTrue('size' not in cube.GetAuthoredPropertyNames()) # Fallback values should come from definition. sizeAttr = cube.GetAttribute('size') self.assertTrue(sizeAttr) self.assertEqual(sizeAttr.Get(), 2.0) self.assertFalse(sizeAttr.IsAuthored())
def InitializeResolver(): """Initialize the resolver so that search paths pointing to schema.usda files are resolved to the directories where those files are installed""" from pxr import Ar, Plug # Force the use of the ArDefaultResolver so we can take advantage # of its search path functionality. Ar.SetPreferredResolver('ArDefaultResolver') # Figure out where all the plugins that provide schemas are located # and add their resource directories to the search path prefix list. resourcePaths = set() pr = Plug.Registry() for t in pr.GetAllDerivedTypes('UsdSchemaBase'): plugin = pr.GetPluginForType(t) if plugin: resourcePaths.add(plugin.resourcePath) # The sorting shouldn't matter here, but we do it for consistency # across runs. Ar.DefaultResolver.SetDefaultSearchPath(sorted(list(resourcePaths)))
def test_ManufacturingCppDerivedClasses(self): # Construct and verify an instance of _TestPlugBase<1> tb1 = Plug._TestPlugBase1() self.assertEqual(tb1.GetTypeName(), '_TestPlugBase<1>') # Get the plugin for TestPlugDerived1 pd1 = Plug.Registry().GetPluginForType('TestPlugDerived1') self.assertIsNotNone(pd1) self.assertFalse(pd1.isLoaded) # Manufacture and verify an instance of TestPlugDerived1 td1 = Plug._TestPlugBase1('TestPlugDerived1') self.assertTrue(td1 and not td1.expired) self.assertEqual(td1.GetTypeName(), 'TestPlugDerived1') self.assertTrue(pd1.isLoaded) # Construct and verify an instance of _TestPlugBase<2> tb2 = Plug._TestPlugBase2() self.assertEqual(tb2.GetTypeName(), '_TestPlugBase<2>') # Get the plugin for TestPlugDerived2 pd2 = Plug.Registry().GetPluginForType('TestPlugDerived2') self.assertIsNotNone(pd2) self.assertFalse(pd2.isLoaded) # Manufacture and verify an instance of TestPlugDerived2 td2 = Plug._TestPlugBase2('TestPlugDerived2') self.assertTrue(td2 and not td2.expired) self.assertEqual(td2.GetTypeName(), 'TestPlugDerived2') self.assertTrue(pd2.isLoaded) # Check that plugin correctly reports its declared types. self.assertFalse( pd1.DeclaresType(Tf.Type('_TestPlugBase<1>'), includeSubclasses=False)) self.assertTrue( pd1.DeclaresType(Tf.Type('_TestPlugBase<1>'), includeSubclasses=True)) self.assertTrue( pd1.DeclaresType(Tf.Type('TestPlugDerived1'), includeSubclasses=False)) self.assertTrue( pd1.DeclaresType(Tf.Type('TestPlugDerived1'), includeSubclasses=True))
# We write directly to the weaker_attr, as opposed to # writing to stronger_attr with an edit target (which # would give the same result). weaker_attr.Set("abc_0", 0.0) weaker_attr.Set("def_10", 10.0) stronger_attr = stronger.GetAttribute('attr') # Confirm resolved metadata. weaker_expectedTimeSamples = {0.0: 'abc_0', 10.0: 'def_10'} self.assertEqual( weaker_attr.GetTimeSamples(), sorted(weaker_expectedTimeSamples.keys())) self.assertEqual( weaker_attr.GetMetadata('timeSamples'), weaker_expectedTimeSamples) # Stronger attribute will be affected by the offset. stronger_expectedTimeSamples = {10.0: 'abc_0', 20.0: 'def_10'} self.assertEqual( stronger_attr.GetTimeSamples(), sorted(stronger_expectedTimeSamples.keys())) self.assertEqual( stronger_attr.GetMetadata('timeSamples'), stronger_expectedTimeSamples) if __name__ == '__main__': # Register test plugin defining list op metadata fields. testDir = os.path.abspath(os.getcwd()) assert len(Plug.Registry().RegisterPlugins(testDir)) == 1 unittest.main()