Esempio n. 1
0
    def test_EnumConversion(self):
        value1 = Tf._Alpha | Tf._Delta
        # Conversions of TfEnum objects to python should retain the correct type.'''
        self.assertIs(Tf._returnsTfEnum(value1), value1)

        # The auto-generated python object should be convertible to the original type.
        Tf._takesTestEnum(value1)
Esempio n. 2
0
    def test_PythonSubclassOfCppClass(self):
        class TestPyDerived( Tf.TestCppBase ):
            def TestVirtual(self):
                return 123

        tTestCppBase = Tf.Type.Find( Tf.TestCppBase )
        tTestPyDerived = Tf.Type.Define( TestPyDerived )

        self.assertFalse(tTestCppBase.isUnknown)
        self.assertFalse(tTestPyDerived.isUnknown)

        self.assertEqual(Tf.TestCppBase, tTestCppBase.pythonClass)
        self.assertEqual(tTestCppBase, Tf.Type.Find( Tf.TestCppBase ))

        self.assertIn(TestPyDerived.__name__, tTestPyDerived.typeName)
        self.assertEqual(TestPyDerived, tTestPyDerived.pythonClass)
        self.assertEqual(tTestPyDerived, Tf.Type.Find( TestPyDerived ))
        self.assertEqual(tTestPyDerived, Tf.Type.FindByName( tTestPyDerived.typeName ))
        self.assertEqual((tTestCppBase,), tTestPyDerived.baseTypes)
        self.assertEqual((), tTestPyDerived.derivedTypes)

        self.assertFalse(tTestCppBase.IsA( tTestPyDerived ))
        self.assertTrue(tTestPyDerived.IsA( tTestCppBase ))

        # Test C++ TfType::Find() on a polymorphic base C++ type with a python
        # subclass.
        self.assertNotEqual(tTestPyDerived, tTestCppBase)
        self.assertEqual(tTestCppBase, Tf._TestFindType(Tf.TestCppBase()))
        self.assertEqual(tTestPyDerived, Tf._TestFindType(TestPyDerived()))
Esempio n. 3
0
    def test_Factory(self):
        df = Tf._DerivedFactory()
        self.assertIsInstance(df, Tf._TestDerived)
        self.assertTrue(hasattr(df, '__owner'))
        self.assertEqual((True, 'cpp derived'), Tf._TakesBase(df))
        Tf._TakesReference(df)
        self.assertFalse(hasattr(df, '__owner'))

        self.assertIs(Tf._DerivedNullFactory(), None)
Esempio n. 4
0
 def StandardTests(allowExtraArgs):
     CheckResults(Tf._ClassWithVarArgInit(allowExtraArgs),
                 allowExtraArgs, (), {})
     CheckResults(Tf._ClassWithVarArgInit(allowExtraArgs, 1),
                 allowExtraArgs, (), {'a':1})
     CheckResults(Tf._ClassWithVarArgInit(allowExtraArgs, 1, 2, 3),
                 allowExtraArgs, (), {'a':1, 'b':2, 'c':3})
     CheckResults(Tf._ClassWithVarArgInit(allowExtraArgs, 1, 2, c=3),
                 allowExtraArgs, (), {'a':1, 'b':2, 'c':3})
Esempio n. 5
0
    def test_Listening(self):
        for pkg in args:
            self.assertEqual(pkg[0], testListening(*pkg[1:]))


        lc = listenerClass()
        testSender = Tf._TestDerived()
        listener = Tf.Notice.Register(Tf.Notice, lc.cb, testSender)
        Tf._sendTfNoticeWithSender(testSender)
        self.assertEqual(1, lc.received)
Esempio n. 6
0
    def test_boolResult(self):
        result = Tf._TestAnnotatedBoolResult(True, 'This is true')
        self.assertTrue(result)
        self.assertEqual(result.annotation, 'This is true')
        boolResult, annotation = result
        self.assertTrue(boolResult)
        self.assertEqual(annotation, 'This is true')

        result = Tf._TestAnnotatedBoolResult(False, 'This is false')
        self.assertFalse(result)
        self.assertEqual(result.annotation, 'This is false')
        boolResult, annotation = result
        self.assertFalse(boolResult)
        self.assertEqual(annotation, 'This is false')
    def _RunPerfTest(self):
        mayaSceneFile = 'Grid_5_of_CubeGrid%s_10.ma' % self._testName
        mayaSceneFullPath = os.path.join(self._inputDir, mayaSceneFile)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        Tf.Status("Maya Scene File: %s" % mayaSceneFile)

        # Get the QWidget for the viewport window.
        self.assertTrue(self._IsViewportRendererViewport20())
        self._viewWidget = self._GetViewportWidget(self._cameraName,
            'vp2Renderer')
        self.assertTrue(self._viewWidget)

        # Force the initial view to draw so that the viewport size stabilizes.
        animStartTime = cmds.playbackOptions(query=True,
            animationStartTime=True)
        cmds.currentTime(animStartTime, edit=True)
        QApplication.processEvents()

        # Render an image and validate that nothing is selected to start.
        self._WriteViewportImage(self._testName, 'before_selection')
        expectedSelection = set()
        actualSelection = set(cmds.ls(selection=True) or [])
        self.assertEqual(actualSelection, expectedSelection)


        self._TestSelectCenterSingle()
        expectedSelection = set(['AssetRef_2_0_2'])
        actualSelection = set(cmds.ls(selection=True) or [])
        self.assertEqual(actualSelection, expectedSelection)


        self._TestSelectCenterArea()
        expectedSelection = set([
            'AssetRef_2_0_2',
            'AssetRef_2_1_2',
            'AssetRef_2_2_2',
            'AssetRef_2_3_2',
            'AssetRef_2_4_2'])
        actualSelection = set(cmds.ls(selection=True) or [])
        self.assertEqual(actualSelection, expectedSelection)


        self._TestUnselect()
        expectedSelection = set()
        actualSelection = set(cmds.ls(selection=True) or [])
        self.assertEqual(actualSelection, expectedSelection)


        self._TestSelectionAppend()
        expectedSelection = set([
            'AssetRef_0_0_4',
            'AssetRef_4_0_4',
            'AssetRef_4_0_0',
            'AssetRef_0_0_0'])
        actualSelection = set(cmds.ls(selection=True) or [])
        self.assertEqual(actualSelection, expectedSelection)
def Replace(tmpl, safe=False, **kw):
    ts = Tf.TemplateString(tmpl)
    result = ''
    if safe:
        result = ts.SafeSubstitute(kw)
    else:
        result = ts.Substitute(kw)
    print repr(tmpl), ' -> ', repr(result)
    return result
Esempio n. 9
0
    def test_RootType(self):
        self._TestCppType(self.tRoot)
        self.assertFalse(self.tRoot.baseTypes)

        # We should already have some builtInTypes defined:
        self.assertGreater(len(self.tRoot.derivedTypes), 1)
        self.assertEqual(hash(self.tRoot), hash(Tf.Type.GetRoot()))
        self.assertNotEqual(hash(self.tRoot), hash(Tf.Type()))
        self.assertTrue(self.tRoot)
 def _set_scene_camera(self, renderer, scene):
     if scene.hdusd.final.nodetree_camera != '' and scene.hdusd.final.data_source:
         usd_camera = UsdAppUtils.GetCameraAtPath(self.stage, scene.hdusd.final.nodetree_camera)
     else:
         usd_camera = UsdAppUtils.GetCameraAtPath(self.stage, Tf.MakeValidIdentifier(scene.camera.data.name))
    
     gf_camera = usd_camera.GetCamera(scene.frame_current)
     renderer.SetCameraState(gf_camera.frustum.ComputeViewMatrix(),
                             gf_camera.frustum.ComputeProjectionMatrix())
    def _GetViewWidgetCenter(self, viewWidget):
        width = viewWidget.width()
        height = viewWidget.height()
        viewSize = Gf.Vec2f(width, height)
        Tf.Status("Maya Viewport Widget Dimensions: %s" % viewSize)

        viewCenter = viewSize / 2.0

        return viewCenter
Esempio n. 12
0
    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))
Esempio n. 13
0
    def testSceneImportAndReference(self):
        """
        Tests that importing or referencing a Maya scene does not reset the
        batch renderer.

        The batch renderer listens for kBeforeFileRead scene messages, but
        those are also emitted when a scene is imported or referenced into the
        current scene. In that case, we want to make sure that the batch
        renderer does not get reset.
        """
        mayaSceneFile = 'ProxyShapeBatchRendererResetTest.ma'
        mayaSceneFullPath = os.path.abspath(mayaSceneFile)
        Tf.Status('Opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        # Force a draw to complete by switching frames.
        animStartTime = cmds.playbackOptions(query=True,
                                             animationStartTime=True)
        cmds.currentTime(animStartTime + 1.0, edit=True)

        # Import another scene file into the current scene.
        mayaSceneFile = 'EmptyScene.ma'
        mayaSceneFullPath = os.path.abspath(mayaSceneFile)
        Tf.Status('Importing Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, i=True)

        # Force a draw to complete by switching frames.
        cmds.currentTime(animStartTime + 1.0, edit=True)

        # Try to select the proxy shape.
        cmds.select('CubeProxy')

        # Force a draw to complete by switching frames.
        cmds.currentTime(animStartTime + 1.0, edit=True)

        # Reference another scene file into the current scene.
        Tf.Status('Referencing Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, reference=True)

        # Force a draw to complete by switching frames.
        cmds.currentTime(animStartTime + 1.0, edit=True)

        # Try to select the proxy shape.
        cmds.select('CubeProxy')
Esempio n. 14
0
    def testSceneOpenAndReopen(self):
        """
        Tests opening and then re-opening scenes after having drawn a USD proxy
        shape.

        The batch renderer needs to be reset when opening a new scene, but
        kBeforeOpen and kAfterOpen scene messages are not always delivered at
        the right time. With the former, the current scene may still be active
        when the message is received in which case another draw may occur
        before the scene is finally closed. With the latter, the scene may have
        been fully read and an initial draw may have happened by the time the
        message is received. Either case results in the batch renderer being
        reset in the middle of an active scene and a possible crash.

        This test depends on the proxy shape node directly and not the assembly
        node. The proxy shape will be drawn immediately when the scene is
        opened, as opposed to an assembly that must first be loaded to create
        the proxy shape node underneath it.
        """
        mayaSceneFile = 'ProxyShapeBatchRendererResetTest.ma'
        mayaSceneFullPath = os.path.abspath(mayaSceneFile)
        Tf.Status('Opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        # Force a draw to complete by switching frames.
        animStartTime = cmds.playbackOptions(query=True,
                                             animationStartTime=True)
        cmds.currentTime(animStartTime + 1.0, edit=True)

        # Re-open the same scene.
        Tf.Status('Re-opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        # Force a draw to complete by switching frames.
        animStartTime = cmds.playbackOptions(query=True,
                                             animationStartTime=True)
        cmds.currentTime(animStartTime + 1.0, edit=True)

        # Try to select the proxy shape.
        cmds.select('CubeProxy')

        # Force a draw to complete by switching frames.
        cmds.currentTime(animStartTime + 1.0, edit=True)
Esempio n. 15
0
    def test_NewUsdLayer(self):
        def _TestNewLayer(layer, expectedFileFormat):
            """Check that the new layer was created successfully and its file
            format is what we expect."""
            self.assertTrue(layer)
            self.assertEqual(layer.GetFileFormat(),
                             Sdf.FileFormat.FindById('usd'))

            # Write something to the layer to ensure it's functional.
            primSpec = Sdf.PrimSpec(layer, 'Scope', Sdf.SpecifierDef, 'Scope')
            self.assertTrue(primSpec)

            # Ensure the layer is saved to disk, then check that its
            # underlying file format matches what we expect.
            self.assertTrue(layer.Save())
            self.assertEqual(GetUnderlyingUsdFileFormat(layer),
                             expectedFileFormat)

        usdFileFormat = Sdf.FileFormat.FindById('usd')

        # Newly-created .usd layers default to the USD_DEFAULT_FILE_FORMAT format.
        _TestNewLayer(Sdf.Layer.CreateNew('testNewUsdLayer.usd'),
                      Tf.GetEnvSetting('USD_DEFAULT_FILE_FORMAT'))
        _TestNewLayer(Sdf.Layer.New(usdFileFormat, 'testNewUsdLayer_2.usd'),
                      Tf.GetEnvSetting('USD_DEFAULT_FILE_FORMAT'))

        # Verify that file format arguments can be used to control the
        # underlying file format for new .usd layers.
        _TestNewLayer(
            Sdf.Layer.CreateNew('testNewUsdLayer_text.usd',
                                args={'format': 'usda'}), 'usda')
        _TestNewLayer(
            Sdf.Layer.New(usdFileFormat,
                          'testNewUsdLayer_text_2.usd',
                          args={'format': 'usda'}), 'usda')

        _TestNewLayer(
            Sdf.Layer.CreateNew('testNewUsdLayer_crate.usd',
                                args={'format': 'usdc'}), 'usdc')
        _TestNewLayer(
            Sdf.Layer.New(usdFileFormat,
                          'testNewUsdLayer_crate_2.usd',
                          args={'format': 'usdc'}), 'usdc')
Esempio n. 16
0
    def test_TfRealPath(self):
        if not os.path.isdir('subdir/e'):
            os.makedirs('subdir/e')
        self.log.info('no symlinks')
        self.assertEqual(os.path.abspath('subdir'),
                         Tf.RealPath('subdir', True))

        if platform.system() == 'Windows':
            if not os.path.isdir(r'C:/symlink-test'):
                os.makedirs(r'C:/symlink-test')

        if hasattr(os, 'symlink'):
            try:
                if not os.path.islink('b'):
                    os.symlink('subdir', 'b')
                if not os.path.islink('c'):
                    os.symlink('b', 'c')
                if not os.path.islink('d'):
                    os.symlink('c', 'd')
                if not os.path.islink('e'):
                    os.symlink('missing', 'e')
                if not os.path.islink('f'):
                    os.symlink('e', 'f')
                if not os.path.islink('g'):
                    os.symlink('f', 'g')

                self.log.info('leaf dir is symlink')
                self.assertEqual(os.path.abspath('subdir'),
                                 Tf.RealPath('d', True))
                self.log.info('symlinks through to dir')
                self.assertEqual(os.path.abspath('subdir/e'),
                                 Tf.RealPath('d/e', True))
                self.log.info('symlinks through to nonexistent dirs')
                self.assertEqual(os.path.abspath('subdir/e/f/g/h'),
                                 Tf.RealPath('d/e/f/g/h', True))
                self.log.info('symlinks through to broken link')
                self.assertEqual('', Tf.RealPath('g', True))

                self.log.info('symlinks through to broken link, '
                              'raiseOnError=True')
                with self.assertRaises(RuntimeError):
                    Tf.RealPath('g', True, raiseOnError=True)

                if platform.system() == 'Windows':
                    # Test repro from USD-6557
                    if not os.path.islink(r'C:/symlink-test-link'):
                        os.symlink(r'C:/symlink-test', 'C:/symlink-test-link')
                        os.chdir(r'C:/symlink-test-link')
                        self.assertEqual(r'C:/symlink-test',
                                         Tf.RealPath(r'C:/symlink-test-link'))

            except OSError:
                # On windows this is expected if run by a non-administrator
                if platform.system() == 'Windows':
                    pass
                else:
                    raise
Esempio n. 17
0
    def testSaveSceneAs(self):
        """
        Tests performing a "Save Scene As..." after having drawn a USD proxy
        shape.

        Previously, the batch renderer listened for kSceneUpdate Maya scene
        messages so that it could reset itself when the scene was changed. This
        was intended to fire for new empty scenes or when opening a different
        scene file. It turns out Maya also emits that message during
        "Save Scene As..." operations, in which case we do *not* want to reset
        the batch renderer, as doing so would lead to a crash, since all of the
        proxy shapes are still in the DAG.

        This test ensures that the batch renderer does not reset and Maya does
        not crash when doing a "Save Scene As..." operation.
        """
        mayaSceneFile = 'AssemblySaveAsTest.ma'
        mayaSceneFullPath = os.path.abspath(mayaSceneFile)
        Tf.Status('Opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)

        animStartTime = cmds.playbackOptions(query=True,
                                             animationStartTime=True)

        UsdMaya.LoadReferenceAssemblies()

        # Force a draw to complete by switching frames.
        cmds.currentTime(animStartTime + 1.0, edit=True)

        saveAsMayaSceneFile = 'SavedScene.ma'
        saveAsMayaSceneFullPath = os.path.abspath(saveAsMayaSceneFile)
        Tf.Status('Saving Maya Scene File As: %s' % saveAsMayaSceneFullPath)
        cmds.file(rename=saveAsMayaSceneFullPath)
        cmds.file(save=True)

        # Try to select the USD assembly/proxy. This will cause the proxy's
        # shape adapter's Sync() method to be called, which would fail if the
        # batch renderer had been reset out from under the shape adapter.
        cmds.select('CubeAssembly')

        # Force a draw to complete by switching frames.
        cmds.currentTime(animStartTime + 1.0, edit=True)
Esempio n. 18
0
    def test_Unicode(self):
        """Testing that we can pass python unicode objects to wrapped
        functions expecting std::string"""
        self.log.info("Testing unicode calls")
        self.assertEqual(Tf.StringSplit('123', '2'), ['1', '3'])
        self.assertEqual(Tf.StringSplit('123', '2'), ['1', '3'])
        self.assertEqual(Tf.StringSplit('123', '2'), ['1', '3'])
        self.assertEqual(Tf.StringSplit('123', '2'), ['1', '3'])

        self.assertEqual(Tf.DictionaryStrcmp('apple', 'banana'), -1)
        self.assertEqual(Tf.DictionaryStrcmp('apple', 'banana'), -1)
        self.assertEqual(Tf.DictionaryStrcmp('apple', 'banana'), -1)
        self.assertEqual(Tf.DictionaryStrcmp('apple', 'banana'), -1)
Esempio n. 19
0
    def test_Callbacks(self):
        global f1called
        Tf._callback(f1)
        self.assertTrue(f1called)

        self.assertEqual('called to python, return string!', Tf._stringCallback(f2))

        self.assertEqual('got string c++ is calling...', Tf._stringStringCallback(f4))

        with self.assertRaises(TypeError):
            Tf._callback(f3)
        with self.assertRaises(TypeError):
            Tf._stringCallback(f1)
def variantNameTextChanged(variantName):
    # The text field cannot be empty. Reset to default value if it is.
    if not variantName:
        cmds.textField('variantNameText',
                       edit=True,
                       text=kDefaultCacheVariantName)
    else:
        # Make sure the name user entered doesn't contain any invalid characters.
        validatedName = Tf.MakeValidIdentifier(variantName)
        if validatedName != variantName:
            cmds.textField('variantNameText', edit=True, text=validatedName)
Esempio n. 21
0
    def convert_to_usd_friendly_node_name(name):
        """Format a glTF name to make it more USD friendly

        Arguments:
            name {str} -- glTF node name

        Returns:
            str -- USD friendly name
        """

        return Tf.MakeValidIdentifier(name)
Esempio n. 22
0
    def test_Callbacks(self):
        global f1called
        Tf._callback(f1)
        self.assertTrue(f1called)

        self.assertEqual('called to python, return string!', Tf._stringCallback(f2))

        self.assertEqual('got string c++ is calling...', Tf._stringStringCallback(f4))

        with self.assertRaises(TypeError):
            Tf._callback(f3)
        with self.assertRaises(TypeError):
            Tf._stringCallback(f1)
    def testBatching_DelegateRemoved(self):
        """Tests removing the diagnostic delegate when the batch context is
        still open."""
        self._StartRecording()
        with mayaUsdLib.DiagnosticBatchContext():
            Tf.Warn("this warning won't be lost")
            Tf.Status("this status won't be lost")

            cmds.unloadPlugin('pxrUsd', force=True)

            for i in range(5):
                Tf.Status("no delegate, this will be lost %d" % i)
        log = self._StopRecording()

        # Note: we use assertItemsEqual because coalescing may re-order the
        # diagnostic messages.
        self.assertItemsEqual(log, [
            ("this warning won't be lost", OM.MCommandMessage.kWarning),
            ("this status won't be lost", OM.MCommandMessage.kInfo),
        ])
Esempio n. 24
0
    def test_ManufacturingPythonDerivedClasses(self):
        ppd1 = Plug.Registry().GetPluginForType('TestPlugPythonDerived1')
        self.assertIsNotNone(ppd1)
        self.assertFalse(ppd1.isLoaded)
        self.assertTrue(ppd1.isPythonModule)

        ppd2 = Plug.Registry().GetPluginForType('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(), '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(), '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('TestPlugPythonDerived1'),
                              includeSubclasses=False))
        self.assertTrue(
            ppd1.DeclaresType(Tf.Type('TestPlugPythonDerived1'),
                              includeSubclasses=True))
Esempio n. 25
0
    def GetChildPath(self, id, index):
        """
        Parameters
        ----------
        id : _InternalId
        index : int

        Returns
        -------
        Sdf.Path
        """
        item = self._idToItem.get(id)
        if item is None:
            raise Tf.ErrorException("Cannot find '%d' in PrimIdTable" % id)

        if index >= len(item.children):
            raise Tf.ErrorException(
                "Index '%d' exceeds number of children of '%s' in PrimIdTable"
                % (index, item.path))

        return item.children[index]
Esempio n. 26
0
        def _TestStageReload(fmt):
            with Tf.NamedTemporaryFile(suffix='.%s' % fmt) as f:
                s = Usd.Stage.CreateNew(f.name)
                s.OverridePrim('/foo')
                s.GetRootLayer().Save()
                s.OverridePrim('/bar')

                assert s.GetPrimAtPath('/foo')
                assert s.GetPrimAtPath('/bar')
                s.Reload()
                assert s.GetPrimAtPath('/foo')
                assert not s.GetPrimAtPath('/bar')
Esempio n. 27
0
def convert(filepath, output, scope_name = "/Cameras/test", aperture_width = 36):
    try:
        # Get fSpy data
        project = fspy.Project(filepath)
        camera_parameters = project.camera_parameters

        # Setup USD scene

        stage = Usd.Stage.CreateInMemory()

        # Setup camera scope

        cameras_scope = Sdf.Path(scope_name)

        for prim in cameras_scope.GetAncestorsRange():
            xform = UsdGeom.Xform.Define(stage, prim)

        camera = UsdGeom.Camera.Define(stage, cameras_scope.AppendChild( Tf.MakeValidIdentifier(project.file_name) ))

        # - Transform
        matrix = Gf.Matrix4d(camera_parameters.camera_transform).GetTranspose()
        rotMat = Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90.0))
        matrix = matrix * rotMat
        camera.AddTransformOp().Set(matrix)

        # - Apperture Size

        hfov = math.degrees(camera_parameters.fov_horiz)
        hfov = math.degrees(camera_parameters.fov_verti)

        width = camera_parameters.image_width
        height = camera_parameters.image_height
    
        aspectRatio = width/height
        iaspectRatio = height/width

        # TODO: We likely need to get this from somewhere
        apWidth = aperture_width
        apHeight = apWidth * iaspectRatio

        camera.CreateHorizontalApertureAttr().Set(apWidth)
        camera.CreateVerticalApertureAttr().Set(apHeight)

        # - Focal Length
        focalLength = (0.5*apHeight)/math.tan((0.5*hfov)/57.296)

        camera.CreateFocalLengthAttr().Set(focalLength)

        print(stage.ExportToString())
        stage.Export(output)
    except Exception as e:
        print("Couldnt convert: " + str(e))
        pass
Esempio n. 28
0
    def test_Notices(self):
        self.log.info("Issuing a couple of different types of errors.")

        try:
            Tf.RaiseRuntimeError("Runtime error!")
            assert False, "expected exception"
        except Tf.ErrorException:
            pass

        try:
            Tf.RaiseCodingError("Coding error!")
            assert False, "expected exception"
        except Tf.ErrorException:
            pass

        self.log.info("Issuing a few generic warnings.")
        Tf.Warn("Warning 1")
        Tf.Warn("Warning 2")
        Tf.Warn("Warning 3")

        self.log.info("Issuing a status message.")
        Tf.Status("Status: Almost done testing.")

        # Assert that two errors, three warnings and one status message were
        # issued.
        self.assertNotIn('IssuedError', self.notices)
        self.assertEqual(self.notices['IssuedWarning'], 3)
        self.assertEqual(self.notices['IssuedStatus'], 1)

        self.outputFile.close()
Esempio n. 29
0
    def test_TfRealPath(self):
        if not os.path.isdir('subdir/e'):
            os.makedirs('subdir/e')
        if not os.path.islink('b'):
            os.symlink('subdir', 'b')
        if not os.path.islink('c'):
            os.symlink('b', 'c')
        if not os.path.islink('d'):
            os.symlink('c', 'd')
        if not os.path.islink('e'):
            os.symlink('missing', 'e')
        if not os.path.islink('f'):
            os.symlink('e', 'f')
        if not os.path.islink('g'):
            os.symlink('f', 'g')

        self.log.info('no symlinks')
        self.assertEqual(os.path.abspath('subdir'),
                         Tf.RealPath('subdir', True))
        self.log.info('leaf dir is symlink')
        self.assertEqual(os.path.abspath('subdir'), Tf.RealPath('d', True))
        self.log.info('symlinks through to dir')
        self.assertEqual(os.path.abspath('subdir/e'), Tf.RealPath('d/e', True))
        self.log.info('symlinks through to nonexistent dirs')
        self.assertEqual(os.path.abspath('subdir/e/f/g/h'),
                         Tf.RealPath('d/e/f/g/h', True))
        self.log.info('symlinks through to broken link')
        self.assertEqual('', Tf.RealPath('g', True))

        self.log.info('symlinks through to broken link, raiseOnError=True')
        with self.assertRaises(RuntimeError):
            Tf.RealPath('g', True, raiseOnError=True)
Esempio n. 30
0
    def test_StringToLong(self):
        def checks(val):
            self.assertEqual(Tf.StringToLong(repr(val)), val)

        def checku(val):
            self.assertEqual(Tf.StringToULong(repr(val)), val)

        # A range of valid values.
        for i in range(1000000):
            checku(i)
        for i in range(-500000, 500000):
            checks(i)

        # A wider range of valid values.
        for i in range(0, 1000000000, 9337):
            checks(i)
        for i in range(-500000000, 500000000, 9337):
            checks(i)

        # Get the max/min values.
        ulmax, lmax, lmin = (Tf._GetULongMax(), Tf._GetLongMax(),
                             Tf._GetLongMin())

        # Check the extrema and one before to ensure they work.
        for n in [ulmax - 1, ulmax]:
            checku(n)

        for n in [lmin, lmin + 1, lmax - 1, lmax]:
            checks(n)

        # Check that some beyond the extrema over/underflow.
        #
        # Unsigned overflow.
        for i in range(1, 1000):
            with self.assertRaises(ValueError):
                checku(ulmax + i)
            with self.assertRaises(ValueError):
                checks(lmax + i)
            with self.assertRaises(ValueError):
                checks(lmin - i)
Esempio n. 31
0
    def render(self, depsgraph):
        if not self.is_synced:
            return

        scene = depsgraph.scene
        width, height = scene.render.resolution_x, scene.render.resolution_y

        renderer = UsdImagingLite.Engine()
        renderer.SetRendererPlugin('HdRprPlugin')
        renderer.SetRendererSetting('rpr:maxSamples', self.SAMPLES_NUMBER)
        renderer.SetRendererSetting('rpr:core:renderQuality', 'Northstar')
        renderer.SetRendererSetting('rpr:alpha:enable', False)
        renderer.SetRendererSetting('rpr:adaptiveSampling:minSamples', 16)
        renderer.SetRendererSetting('rpr:adaptiveSampling:noiseTreshold', 0.05)

        renderer.SetRenderViewport((0, 0, width, height))
        renderer.SetRendererAov('color')

        # setting camera
        usd_camera = UsdAppUtils.GetCameraAtPath(
            self.stage, Tf.MakeValidIdentifier(scene.camera.data.name))

        gf_camera = usd_camera.GetCamera()
        renderer.SetCameraState(gf_camera.frustum.ComputeViewMatrix(),
                                gf_camera.frustum.ComputeProjectionMatrix())

        params = UsdImagingLite.RenderParams()
        image = np.empty((width, height, 4), dtype=np.float32)

        def update_render_result():
            result = self.render_engine.begin_result(0, 0, width, height)
            render_passes = result.layers[0].passes
            render_passes.foreach_set('rect', image.flatten())
            self.render_engine.end_result(result)

        renderer.Render(self.stage.GetPseudoRoot(), params)

        while True:
            if self.render_engine.test_break():
                break

            if renderer.IsConverged():
                break

            renderer.GetRendererAov('color', image.ctypes.data)
            update_render_result()

        renderer.GetRendererAov('color', image.ctypes.data)
        update_render_result()

        # its important to clear data explicitly
        renderer = None
Esempio n. 32
0
    def test_StageMaskDependencyExpansion(self):
        """
        Tests dependency based (rels, attr connections) population expansion.
        """
        if not (Tf.GetEnvSetting("GUSD_STAGEMASK_ENABLE")
                and Tf.GetEnvSetting("GUSD_STAGEMASK_EXPANDRELS")):
            return

        path = "test.usda"
        cache = Gusd.StageCache()

        prim, stage = GetPrim(cache, path, "/Root/Component/B")

        # External prim should have been detected as a dependency and
        # included in the mask.
        assert Sdf.Path("/Root/ExternalDependency") in \
            stage.GetPopulationMask().GetPaths()

        # Make sure the mask composed prims as expected.
        assert stage.GetPrimAtPath("/Root/ExternalDependency")
        assert not stage.GetPrimAtPath("/Root/NonReferencedPrim")
        assert not stage.GetPrimAtPath("/Root2")
Esempio n. 33
0
    def testSceneOpenAndReopen(self):
        """
        Tests opening and then re-opening scenes after having drawn a USD proxy
        shape.

        The batch renderer needs to be reset when opening a new scene, but
        kBeforeOpen and kAfterOpen scene messages are not always delivered at
        the right time. With the former, the current scene may still be active
        when the message is received in which case another draw may occur
        before the scene is finally closed. With the latter, the scene may have
        been fully read and an initial draw may have happened by the time the
        message is received. Either case results in the batch renderer being
        reset in the middle of an active scene and a possible crash.
        """
        mayaSceneFile = '%s.ma' % self._testName
        mayaSceneFullPath = os.path.join(self._inputDir, mayaSceneFile)
        Tf.Status('Opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)
        currentTime = cmds.playbackOptions(query=True, animationStartTime=True)

        # Force a draw to complete by switching frames.
        currentTime += 1
        cmds.currentTime(currentTime, edit=True)

        # Re-open the same scene.
        Tf.Status('Re-opening Maya Scene File: %s' % mayaSceneFullPath)
        cmds.file(mayaSceneFullPath, open=True, force=True)
        currentTime = cmds.playbackOptions(query=True, animationStartTime=True)

        # Force a draw to complete by switching frames.
        currentTime += 1
        cmds.currentTime(currentTime, edit=True)

        # Try to select the proxy shape.
        cmds.select('CubeProxyShape')

        # Force a draw to complete by switching frames.
        currentTime += 1
        cmds.currentTime(currentTime, edit=True)
def sync(obj_prim, obj: bpy.types.Object, **kwargs):
    """Creates Usd camera from obj.data: bpy.types.Camera"""
    scene = kwargs['scene']
    screen_ratio = scene.render.resolution_x / scene.render.resolution_y

    camera = obj.data
    log("sync", camera)

    stage = obj_prim.GetStage()
    usd_camera = UsdGeom.Camera.Define(stage, obj_prim.GetPath().AppendChild(Tf.MakeValidIdentifier(camera.name)))

    settings = CameraData.init_from_camera(camera, obj.matrix_world, screen_ratio)
    settings.export(usd_camera)
Esempio n. 35
0
def _ConfigureSchemaLayer(schemaLayer, schemaSubLayers, skipCodeGeneration):
    # - add sublayers
    subLayers = schemaLayer.subLayerPaths
    subLayersList = list(subLayers)
    subLayersList.extend(schemaSubLayers)
    schemaLayer.subLayerPaths = list(set(subLayersList))

    globalPrim = schemaLayer.GetPrimAtPath('/GLOBAL')
    if not globalPrim:
        Tf.RaiseRuntimeError("Missing /GLOBAL prim in schema.usda.")

    if not globalPrim.customData:
        Tf.RaiseRuntimeError("customData must be defined on the /GLOBAL prim")

    customDataDict = dict(globalPrim.customData)
    if 'libraryName' not in customDataDict:
        Tf.RaiseRuntimeError("customData on /GLOBAL prim must provide a " \
            "libraryName.")
    customDataDict['skipCodeGeneration'] = skipCodeGeneration
    globalPrim.customData = customDataDict

    schemaLayer.Save()
Esempio n. 36
0
    def test_StageMaskComponentExpansion(self):
        """
        Tests kind-based population mask expansion.
        """
        if not Tf.GetEnvSetting("GUSD_STAGEMASK_ENABLE"):
            return

        path = "test.usda"
        cache = Gusd.StageCache()

        prim, stage = GetPrim(cache, path, "/Root/Component/A")

        # Mask should have been expanded to include full /Root/Component.
        assert Sdf.Path("/Root/Component") in \
            stage.GetPopulationMask().GetPaths()

        # Make sure the mask composed prims as expected.
        assert stage.GetPrimAtPath("/Root/Component/B")
        assert not stage.GetPrimAtPath("/Root/NonReferencedPrim")
        assert not stage.GetPrimAtPath("/Root2")

        if not Tf.GetEnvSetting("GUSD_STAGEMASK_EXPANDRELS"):
            assert not stage.GetPrimAtPath("/Root/ExternalDependency")
Esempio n. 37
0
    def GetChildCount(self, id):
        """
        Parameters
        ----------
        id : _InternalId

        Returns
        -------
        int
        """
        item = self._idToItem.get(id)
        if item is None:
            raise Tf.ErrorException("Cannot find '%d' in PrimIdTable" % id)
        return len(item.children)
Esempio n. 38
0
    def test_StringToLong(self):

        def checks(val):
            self.assertEqual(Tf.StringToLong(repr(val)), val)
        def checku(val):
            self.assertEqual(Tf.StringToULong(repr(val)), val)

        # A range of valid values.
        for i in xrange(1000000):
            checku(i)
        for i in xrange(-500000, 500000):
            checks(i)

        # A wider range of valid values.
        for i in xrange(0, 1000000000, 9337):
            checks(i)
        for i in xrange(-500000000, 500000000, 9337):
            checks(i)

        # Get the max/min values.
        ulmax, lmax, lmin = (
            Tf._GetULongMax(), Tf._GetLongMax(), Tf._GetLongMin())

        # Check the extrema and one before to ensure they work.
        map(checku, [ulmax-1, ulmax])
        map(checks, [lmin, lmin+1, lmax-1, lmax])

        # Check that some beyond the extrema over/underflow.
        #
        # Unsigned overflow.
        for i in xrange(1, 1000):
            with self.assertRaises(ValueError):
                checku(ulmax + i)
            with self.assertRaises(ValueError):
                checks(lmax + i)
            with self.assertRaises(ValueError):
                checks(lmin - i)
Esempio n. 39
0
    def test_TfPyClassMethod(self):
        c = Tf._ClassWithClassMethod()

        # Test classmethod invokation.
        def _TestCallable():
            return 123
        self.assertEqual((Tf._ClassWithClassMethod, 123), c.Test(_TestCallable))

        # Test classmethod error handling.
        class _TestException(Exception):
            '''A sample exception to raise.'''
            pass
        def _TestCallableWithException():
            raise _TestException()

        with self.assertRaises(_TestException):
            c.Test(_TestCallableWithException)
Esempio n. 40
0
    def test_Exception(self):
        with self.assertRaises(RuntimeError):
            Tf._TakesBase(Raiser())

        with self.assertRaises(Tf.ErrorException) as cm:
            Tf._mightRaise(True)
        for x in cm.exception:
            self.assertTrue(len(repr(x)))

        with self.assertRaises(Tf.ErrorException):
            Tf.RaiseCodingError("some error")

        with self.assertRaises(Tf.ErrorException):
            Tf.RaiseRuntimeError("some error")

        with self.assertRaises(Tf.ErrorException):
            Tf._doErrors()
Esempio n. 41
0
    def test_EnumValuesRemovedFromTypeScope(self):
        with self.assertRaises(AttributeError):
            Tf._takesTestEnum(Tf._TestEnum._Alpha)

        self.assertEqual((Tf._Alpha, Tf._Bravo, Tf._Charlie, Tf._Delta),
                Tf._TestEnum.allValues)

        with self.assertRaises(TypeError):
            Tf._takesTestEnum(Tf._Enum.One)
        with self.assertRaises(TypeError):
            Tf._takesTestEnum2(Tf._Alpha)

        self.assertEqual((Tf._Enum.One, Tf._Enum.Two, Tf._Enum.Three),
                Tf._Enum.TestEnum2.allValues)

        self.assertEqual(1, Tf._Enum.One.value)
        self.assertEqual(2, Tf._Enum.Two.value)
        self.assertEqual(3, Tf._Alpha.value)
        self.assertEqual('A', Tf._Alpha.displayName)
        self.assertEqual('B', Tf._Bravo.displayName)
        self.assertEqual(Tf._Alpha, Tf.Enum.GetValueFromFullName(Tf._Alpha.fullName))
        self.assertEqual(None, Tf.Enum.GetValueFromFullName("invalid_enum_name"))

        self.assertTrue(Tf._Enum.One == 1)
        self.assertTrue(Tf._Enum.Two == 2)
        self.assertTrue(Tf._Alpha == 3)

        self.assertTrue(1 == Tf._Enum.One)
        self.assertTrue(2 == Tf._Enum.Two)
        self.assertTrue(3 == Tf._Alpha)

        self.assertTrue(Tf._Alpha | Tf._Alpha is Tf._Alpha)
        self.assertTrue(Tf._Alpha & Tf._Alpha is Tf._Alpha)
        self.assertTrue(Tf._Alpha == 3)
        self.assertTrue(Tf._Alpha | 1 is Tf._Alpha)
        self.assertTrue(2 | Tf._Alpha is Tf._Alpha)
        self.assertTrue(4 | Tf._Alpha == 7)

        self.assertTrue(Tf._Alpha & 3 is Tf._Alpha)
        self.assertTrue(3 & Tf._Alpha is Tf._Alpha)
        self.assertTrue(2 & Tf._Alpha == 2)

        self.assertTrue(Tf._Enum.One ^ Tf._Enum.Two == 3)
        self.assertTrue(4 ^ Tf._Alpha == 7)
        self.assertTrue(Tf._Alpha ^ 4 == 7)
Esempio n. 42
0
    def test_Enums(self):
        Tf._takesTfEnum(Tf._Alpha)
        Tf._takesTfEnum(Tf._Delta)

        self.assertEqual(Tf._Delta, Tf._returnsTfEnum(Tf._Delta))
        self.assertIs(Tf._returnsTfEnum(Tf._Delta), Tf._Delta)

        Tf._takesTfEnum(Tf._Enum.One)

        Tf._takesTestEnum(Tf._Alpha)
        Tf._takesTestEnum2(Tf._Enum.One)
Esempio n. 43
0
    def test_BaseDerived(self):
        mb = MyBase()
        d = Tf._TestDerived()
        md = MyDerived()

        self.assertEqual('unwrapped virtual', mb.TestCallVirtual())

        self.assertEqual('cpp base', mb.Virtual4())
        self.assertEqual('python derived v4', md.Virtual4())

        self.assertEqual((False, 'python base'), Tf._TakesBase(mb))
        self.assertEqual((True, 'cpp derived'), Tf._TakesBase(d))
        self.assertEqual((True, 'python derived'), Tf._TakesBase(md))

        self.assertEqual('python base', Tf._TakesConstBase(mb))
        self.assertEqual('cpp derived', Tf._TakesConstBase(d))
        self.assertEqual('python derived', Tf._TakesConstBase(md))

        self.assertEqual('cpp derived', Tf._TakesDerived(d))
        self.assertEqual('python derived', Tf._TakesDerived(md))

        self.assertIs(Tf._ReturnsConstBase(md), md)
        self.assertIs(Tf._ReturnsBase(md), md)
        self.assertIs(Tf._ReturnsBaseRefPtr(md), md)

        try:
            Tf._TestBase().Virtual()
            assert False, 'calling pure virtual'
        except:
            pass
Esempio n. 44
0
    def test_TfPyObjWrapper(self):
        self.assertEqual('a', Tf._RoundTripWrapperTest('a'))
        self.assertEqual(1234, Tf._RoundTripWrapperTest(1234))
        self.assertEqual([], Tf._RoundTripWrapperTest([]))
        self.assertEqual(None, Tf._RoundTripWrapperTest(None))

        self.assertEqual('a', Tf._RoundTripWrapperCallTest(lambda: 'a'))
        self.assertEqual(1234, Tf._RoundTripWrapperCallTest(lambda: 1234))
        self.assertEqual([], Tf._RoundTripWrapperCallTest(lambda: []))
        self.assertEqual(None, Tf._RoundTripWrapperCallTest(lambda: None))

        self.assertEqual('a', Tf._RoundTripWrapperIndexTest(['a','b'], 0))
        self.assertEqual('b', Tf._RoundTripWrapperIndexTest(['a','b'], 1))
        self.assertEqual(4, Tf._RoundTripWrapperIndexTest([1,2,3,4], -1))
Esempio n. 45
0
 def test_TakeVectorOfVectorOfStrings(self):
     self.assertEqual(4, Tf._TakesVecVecString([['1', '2', '3'], ['4', '5'], [], ['6']]))
Esempio n. 46
0
    def test_WeakStrongRefCallbacks(self):
        class Foo(object):
            def method(self):
                return 'python method'
        f = Foo()
        m = f.method

        # the callback is an instancemethod, it should not keep the object 
        # alive.
        Tf._setTestCallback(m)
        self.assertEqual('python method', Tf._invokeTestCallback())
        del f
        del m
        print 'expected warning...'
        self.assertEqual('', Tf._invokeTestCallback())
        print 'end of expected warning'

        l = lambda : 'python lambda'

        # the callback is a lambda, it should stay alive (and will keep f alive)
        Tf._setTestCallback(l)
        self.assertEqual('python lambda', Tf._invokeTestCallback())
        del l
        self.assertEqual('python lambda', Tf._invokeTestCallback())


        # the callback is a function, it should not stay alive
        def func():
            return 'python func'

        Tf._setTestCallback(func)
        self.assertEqual('python func', Tf._invokeTestCallback())
        del func
        print 'expected warning...'
        self.assertEqual('', Tf._invokeTestCallback())
        print 'end of expected warning'

        del Foo
Esempio n. 47
0

class testPySender(object):
    pass

args = [
    # Global notices
    (1, "TfNotice", Tf.Notice()),
    (1, Tf.Notice, Tf.Notice()),
    (1, Tf.Notice, PyNoticeBase()),
    (1, PyNoticeBase, PyNoticeBase()),
    (1, PyNoticeBase, PyNoticeDerived()),
    (0, PyNoticeDerived, PyNoticeBase()),
    
    # Notices from C++ sender.
    (1, "TfNotice", Tf.Notice(), Tf._TestBase()),
    (1, Tf.Notice, Tf.Notice(), Tf._TestBase()),
    (1, Tf.Notice, PyNoticeBase(), Tf._TestBase()),
    (1, PyNoticeBase, PyNoticeBase(), Tf._TestBase()),
    (1, PyNoticeBase, PyNoticeDerived(), Tf._TestBase()),
    (0, PyNoticeDerived, PyNoticeBase(), Tf._TestBase()),

    # Notices from Python sender.
    (1, "TfNotice", Tf.Notice(), testPySender()),
    (1, Tf.Notice, Tf.Notice(), testPySender()),
    (1, Tf.Notice, PyNoticeBase(), testPySender()),
    (1, PyNoticeBase, PyNoticeBase(), testPySender()),
    (1, PyNoticeBase, PyNoticeDerived(), testPySender()),
    (0, PyNoticeDerived, PyNoticeBase(), testPySender())
    ]
Esempio n. 48
0
    def test_TfMakePyConstructorWithVarArgs(self):
        with self.assertRaises(TypeError):
            Tf._ClassWithVarArgInit()

        def CheckResults(c, allowExtraArgs, args, kwargs):
            self.assertEqual(c.allowExtraArgs, allowExtraArgs)
            self.assertEqual(c.args, args)
            self.assertEqual(c.kwargs, kwargs)

        def StandardTests(allowExtraArgs):
            CheckResults(Tf._ClassWithVarArgInit(allowExtraArgs),
                        allowExtraArgs, (), {})
            CheckResults(Tf._ClassWithVarArgInit(allowExtraArgs, 1),
                        allowExtraArgs, (), {'a':1})
            CheckResults(Tf._ClassWithVarArgInit(allowExtraArgs, 1, 2, 3),
                        allowExtraArgs, (), {'a':1, 'b':2, 'c':3})
            CheckResults(Tf._ClassWithVarArgInit(allowExtraArgs, 1, 2, c=3),
                        allowExtraArgs, (), {'a':1, 'b':2, 'c':3})

        # Tests with extra arguments disallowed.
        StandardTests(allowExtraArgs=False)

        # These cases should emit an error because there are unexpected 
        # arguments
        with self.assertRaises(TypeError):
            Tf._ClassWithVarArgInit(False, 1, 2, 3, 4)

        with self.assertRaises(TypeError):
            Tf._ClassWithVarArgInit(False, d=4)

        # This should emit an error because we have multiple values for a single 
        # arg.
        with self.assertRaises(TypeError):
            Tf._ClassWithVarArgInit(False, 1, 2, 3, b=4)

        # Tests with extra arguments allowed.
        StandardTests(allowExtraArgs=True)

        CheckResults(Tf._ClassWithVarArgInit(True, 1, 2, 3, 4, 5),
                    True, (4,5), {'a':1, 'b':2, 'c':3})
        CheckResults(Tf._ClassWithVarArgInit(True, 1, 2, c=3, d=6, f=8),
                    True, (), {'a':1, 'b':2, 'c':3, 'd':6, 'f':8})
        CheckResults(Tf._ClassWithVarArgInit(True, 1, 2, 3, 4, d=8),
                    True, (4,), {'a':1, 'b':2, 'c':3, 'd':8})
Esempio n. 49
0
 def test_ExceptionWithoutCurrentThreadState(self):
     with self.assertRaises(RuntimeError):
         Tf._ThrowCppException()
Esempio n. 50
0
 def test_EnumRegistrationCollision(self):
     with self.assertRaises(Tf.ErrorException):
         Tf._registerInvalidEnum(Tf)