def test_Write(self): # Create a usda and abc temporary files. # NOTE: This files will automatically be deleted when the test quits, # if you want to keep them around for debugging, pass in delete=False with Tf.NamedTemporaryFile(suffix='.abc') as tempAbcFile, \ Tf.NamedTemporaryFile(suffix='.usda') as tempUsdFile: # Create a USD file that we'll save out as .abc stage = Usd.Stage.CreateNew(tempUsdFile.name) stage.OverridePrim('/Prim') stage.GetRootLayer().Save() # Write out the USD file as .abc UsdAbc._WriteAlembic(tempUsdFile.name, tempAbcFile.name) # Read it back in and expect to read back a prim. roundTrippedStage = Usd.Stage.Open(tempAbcFile.name) prim = roundTrippedStage.GetPrimAtPath('/Prim') self.assertTrue(prim) # Verify that timeCodesPerSecond and framesPerSecond values are preserved # when round-tripping. self.assertTrue( roundTrippedStage.GetRootLayer().HasTimeCodesPerSecond()) self.assertEqual(roundTrippedStage.GetTimeCodesPerSecond(), stage.GetTimeCodesPerSecond()) self.assertTrue( roundTrippedStage.GetRootLayer().HasFramesPerSecond()) self.assertEqual(roundTrippedStage.GetFramesPerSecond(), stage.GetTimeCodesPerSecond())
def test_ContextUsage(self): print 'Running context manager test' with Tf.NamedTemporaryFile(**self.aArgs) as a, \ Tf.NamedTemporaryFile(**self.bArgs) as b: self._runTests([a, b])
def _runDiff(baseline, comparison, compose, noeffect): from pxr import Tf diffResult = 0 # Generate recognizable suffixes for our files in the temp dir # location of the form /temp/string__originalFileName.usda # where originalFileName is the basename(no extension) of the original file. # This allows users to tell which file is which when diffing. tempBaselineFileName = ("__" + os.path.splitext(os.path.basename(baseline))[0] + '.usda') tempComparisonFileName = ("__" + os.path.splitext(os.path.basename(comparison))[0] + '.usda') with Tf.NamedTemporaryFile(suffix=tempBaselineFileName) as tempBaseline, \ Tf.NamedTemporaryFile(suffix=tempComparisonFileName) as tempComparison: usdcatCmd, diffCmd = _findDiffTools() baselineFileType = _getFileFormat(baseline) comparisonFileType = _getFileFormat(comparison) pluginError = 'Error: Cannot find supported file format plugin for %s' if baselineFileType is None: sys.exit(pluginError % baseline) if comparisonFileType is None: sys.exit(pluginError % comparison) # Dump the contents of our files into the temporaries _convertTo(baseline, tempBaseline.name, usdcatCmd, flatten=compose, fmt=None) _convertTo(comparison, tempComparison.name, usdcatCmd, flatten=compose, fmt=None) tempBaselineTimestamp = os.path.getmtime(tempBaseline.name) tempComparisonTimestamp = os.path.getmtime(tempComparison.name) diffResult = call([diffCmd, tempBaseline.name, tempComparison.name]) tempBaselineChanged = ( os.path.getmtime(tempBaseline.name) != tempBaselineTimestamp) tempComparisonChanged = ( os.path.getmtime(tempComparison.name) != tempComparisonTimestamp) # If we intend to edit either of the files if not noeffect: if tempBaselineChanged: _tryEdit(baseline, tempBaseline.name, usdcatCmd, baselineFileType, compose) if tempComparisonChanged: _tryEdit(comparison, tempComparison.name, usdcatCmd, comparisonFileType, compose) return diffResult
def _TestLayerReload(fmt): # First, test case where the reloaded layer is in the # stage's root LayerStack. with Tf.NamedTemporaryFile(suffix='.%s' % fmt) as l1name, \ Tf.NamedTemporaryFile(suffix='.%s' % fmt) as l2name: l1 = Sdf.Layer.CreateAnonymous() Sdf.CreatePrimInLayer(l1, '/foo') l1.Export(l1name.name) l2 = Sdf.Layer.CreateAnonymous() Sdf.CreatePrimInLayer(l2, '/bar') l2.Export(l2name.name) s = Usd.Stage.Open(l1name.name) assert s.GetPrimAtPath('/foo') assert not s.GetPrimAtPath('/bar') shutil.copyfile(l2name.name, l1name.name) # Force layer reload to avoid issues where mtime does not # change after file copy due to low resolution. s.GetRootLayer().Reload(force=True) assert not s.GetPrimAtPath('/foo') assert s.GetPrimAtPath('/bar') # Now test the case where the reloaded layer is in a referenced # LayerStack. with Tf.NamedTemporaryFile(suffix='.%s' % fmt) as rootLayerName, \ Tf.NamedTemporaryFile(suffix='.%s' % fmt) as refLayerName: refLayer = Sdf.Layer.CreateAnonymous() Sdf.CreatePrimInLayer(refLayer, '/foo/bar') refLayer.Export(refLayerName.name) rootLayer = Sdf.Layer.CreateAnonymous() rootPrim = Sdf.CreatePrimInLayer(rootLayer, '/foo') rootPrim.referenceList.Add( Sdf.Reference(refLayerName.name, '/foo')) rootLayer.Export(rootLayerName.name) s = Usd.Stage.Open(rootLayerName.name) assert s.GetPrimAtPath('/foo/bar') del refLayer.GetPrimAtPath('/foo').nameChildren['bar'] refLayer.Export(refLayerName.name) Sdf.Layer.Find(refLayerName.name).Reload(force=True) assert s.GetPrimAtPath('/foo') assert not s.GetPrimAtPath('/foo/bar')
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')
def test_USD_5196(self): from pxr import Usd, Sdf, Vt, Tf import os, random # Test that usdc files corrupted by truncation (such that the table of # contents is past the end of the file) are detected and fail to open # with an error. with Tf.NamedTemporaryFile(suffix=".usdc") as f: layer = Sdf.Layer.CreateNew(f.name) foo = Sdf.CreatePrimInLayer(layer, '/foo') attr = Sdf.AttributeSpec(foo, 'attr', Sdf.ValueTypeNames.IntArray) ints = range(1024**2) random.shuffle(ints) attr.default = Vt.IntArray(ints) layer.Save() del layer # Now truncate layer to corrupt it. fobj = open(f.name, "rw+") size = os.path.getsize(f.name) fobj.truncate(size / 2) fobj.close() # Attempting to open the file should raise an exception. with self.assertRaises(Tf.ErrorException): layer = Sdf.Layer.FindOrOpen(f.name)
def test_UnknownFieldsRoundTripThroughUsdc(self): import tempfile, difflib s = Usd.Stage.CreateInMemory('testBadFields.usda') s.GetRootLayer().ImportFromString('''#usda 1.0 ( delete badListOpTest = [10, 20, 30] add badListOpTest = [1, 2, 3] reorder badListOpTest = [3, 2, 1] noSuchListOpTest = [10, 20, 30] ) def "BadDict" ( badDictTest = { bool someBool = 1 double[] someDoubleArray = [0, 1] } ) { } def "BadListOp" { double ExplicitAttr ( badListOpTest = [-2147483648, 1, 2, 3, 4, 5, 2147483647] ) rel ExplicitRel ( badListOpTest = [-2147483648, 1, 2, 3, 4, 5, 2147483647] ) double NoneAttr ( badListOpTest = None ) rel NoneRel ( badListOpTest = None ) double NonExplicitAttr ( delete badListOpTest = [-2147483648, 10, 20, 30, 2147483647] add badListOpTest = [-2147483648, 1, 2, 3, 2147483647] reorder badListOpTest = [2147483647, 3, 2, 1, -2147483648] ) rel NonExplicitRel ( delete badListOpTest = [-2147483648, 10, 20, 30, 2147483647] add badListOpTest = [-2147483648, 1, 2, 3, 2147483647] reorder badListOpTest = [2147483647, 3, 2, 1, -2147483648] ) def "Explicit" ( badListOpTest = [-2147483648, 1, 2, 3, 4, 5, 2147483647] ) { } def "None" ( badListOpTest = None ) { } def "NonExplicit" ( delete badListOpTest = [-2147483648, 10, 20, 30, 2147483647] add badListOpTest = [-2147483648, 1, 2, 3, 2147483647] reorder badListOpTest = [2147483647, 3, 2, 1, -2147483648] ) { } } def "Foo" ( nosuchfield = 1234 ) { } ''') # Now export to both .usdc and .usda, then export the usdc to usda, and # compare -- they should match. with Tf.NamedTemporaryFile(suffix='.usda') as textFile, \ Tf.NamedTemporaryFile(suffix='.usda') as roundTripFile, \ Tf.NamedTemporaryFile(suffix='.usdc') as binFile: s.GetRootLayer().Export(textFile.name) s.GetRootLayer().Export(binFile.name) binLayer = Sdf.Layer.FindOrOpen(binFile.name) assert binLayer binLayer.Export(roundTripFile.name) # NOTE: binFile will want to delete the underlying file # on __exit__ from the context manager. But binLayer # may have the file open. If so the deletion will # fail on Windows. Explicitly release our reference # to the layer to close the file. del binLayer # Now textFile and roundTripFile should match. a = open(textFile.name).read() b = open(roundTripFile.name).read() if a != b: print '\n'.join(difflib.unified_diff(a.split('\n'), b.split('\n'))) assert a == b
def test_ResolvedAssetPaths(self): print 'Testing that asset-path-valued attributes give resolved values' import os for fmt in allFormats: with Tf.NamedTemporaryFile(suffix='.'+fmt) as rootFile, \ Tf.NamedTemporaryFile(suffix='.'+fmt) as targetFile: self.assertEqual( os.path.split(rootFile.name)[0], os.path.split(targetFile.name)[0]) print rootFile.name, targetFile.name s = Usd.Stage.CreateNew(rootFile.name) foo = s.DefinePrim('/foo') singleAsset = foo.CreateAttribute('singleAsset', Sdf.ValueTypeNames.Asset) arrayAsset = foo.CreateAttribute('arrayAsset', Sdf.ValueTypeNames.AssetArray) singleAssetQuery = Usd.AttributeQuery(foo, 'singleAsset') arrayAssetQuery = Usd.AttributeQuery(foo, 'arrayAsset') relPath = './' + os.path.split(targetFile.name)[1] relPathArray = Sdf.AssetPathArray(42, [relPath]) self.assertNotEqual(relPath, targetFile.name) singleAsset.Set(relPath) arrayAsset.Set(relPathArray) singleAssetValue = singleAsset.Get() arrayAssetValue = arrayAsset.Get() singleAssetQueryValue = singleAssetQuery.Get() arrayAssetQueryValue = arrayAssetQuery.Get() self.assertEqual(singleAssetValue.path, relPath) self.assertTrue( all([ap.path == relPath for ap in arrayAssetValue])) # Ensure that attribute query also resolves paths self.assertEqual(singleAssetValue.path, singleAssetQueryValue.path) self.assertEqual([ap.path for ap in arrayAssetValue], [ap.path for ap in arrayAssetQueryValue]) # NOTE: We use os.path.abspath() to ensure the paths can be # accurately compared. On Windows this will change # forward slash directory separators to backslashes. self.assertEqual( os.path.abspath(singleAssetValue.resolvedPath), targetFile.name) self.assertTrue( all([ os.path.abspath(ap.resolvedPath) == targetFile.name for ap in arrayAssetValue ])) self.assertEqual(singleAssetValue.resolvedPath, singleAssetQueryValue.resolvedPath) self.assertEqual( [ap.resolvedPath for ap in arrayAssetValue], [ap.resolvedPath for ap in arrayAssetQueryValue]) # Test a case where the file does not exist, which the default # resolver doesn't resolve relPath = './nonexistent_file_for_testUsdCreateProperties.xxx' relPathArray = Sdf.AssetPathArray(42, [relPath]) singleAsset.Set(relPath) arrayAsset.Set(relPathArray) singleAssetValue = singleAsset.Get() arrayAssetValue = arrayAsset.Get() self.assertEqual(singleAssetValue.path, relPath) self.assertTrue( all([ap.path == relPath for ap in arrayAssetValue])) self.assertEqual(singleAssetValue.resolvedPath, '') self.assertTrue( all([ap.resolvedPath == '' for ap in arrayAssetValue])) # NOTE: rootFile will want to delete the underlying file # on __exit__ from the context manager. But stage s # may have the file open. If so the deletion will # fail on Windows. Explicitly release our reference # to the stage to close the file. del s
def _runDiff(baseline, comparison, flatten, noeffect): from pxr import Tf diffResult = 0 usdcatCmd, diffCmd = _findDiffTools() baselineFileType = _getFileFormat(baseline) comparisonFileType = _getFileFormat(comparison) pluginError = 'Error: Cannot find supported file format plugin for %s' if baselineFileType is None: _exit(pluginError % baseline, ERROR_EXIT_CODE) if comparisonFileType is None: _exit(pluginError % comparison, ERROR_EXIT_CODE) # Generate recognizable suffixes for our files in the temp dir # location of the form /temp/string__originalFileName.usda # where originalFileName is the basename(no extension) of the original file. # This allows users to tell which file is which when diffing. tempBaselineFileName = ("__" + os.path.splitext(os.path.basename(baseline))[0] + '.usda') tempComparisonFileName = ( "__" + os.path.splitext(os.path.basename(comparison))[0] + '.usda') with Tf.NamedTemporaryFile(suffix=tempBaselineFileName) as tempBaseline, \ Tf.NamedTemporaryFile(suffix=tempComparisonFileName) as tempComparison: # Dump the contents of our files into the temporaries convertError = 'Error: failed to convert from %s to %s.' if _convertTo( baseline, tempBaseline.name, usdcatCmd, flatten, fmt=None) != 0: _exit(convertError % (baseline, tempBaseline.name), ERROR_EXIT_CODE) if _convertTo( comparison, tempComparison.name, usdcatCmd, flatten, fmt=None) != 0: _exit(convertError % (comparison, tempComparison.name), ERROR_EXIT_CODE) tempBaselineTimestamp = os.path.getmtime(tempBaseline.name) tempComparisonTimestamp = os.path.getmtime(tempComparison.name) if diffCmd: # Run the external diff tool. diffResult = call( [diffCmd, tempBaseline.name, tempComparison.name]) else: # Read the files. with open(tempBaseline.name, "r") as f: baselineData = f.readlines() with open(tempComparison.name, "r") as f: comparisonData = f.readlines() # Generate unified diff and output if there are any differences. diff = list( difflib.unified_diff(baselineData, comparisonData, tempBaseline.name, tempComparison.name, n=0)) if diff: # Skip the file names. for line in diff[2:]: print line, diffResult = 1 tempBaselineChanged = (os.path.getmtime(tempBaseline.name) != tempBaselineTimestamp) tempComparisonChanged = (os.path.getmtime(tempComparison.name) != tempComparisonTimestamp) # If we intend to edit either of the files if not noeffect: if tempBaselineChanged: if _tryEdit(baseline, tempBaseline.name, usdcatCmd, baselineFileType, flatten) != 0: _exit(convertError % (baseline, tempBaseline.name), ERROR_EXIT_CODE) if tempComparisonChanged: if _tryEdit(comparison, tempComparison.name, usdcatCmd, comparisonFileType, flatten) != 0: _exit(convertError % (comparison, tempComparison.name), ERROR_EXIT_CODE) return diffResult
def test_Types(self): # Create a usda and abc temporary files. # NOTE: This files will automatically be deleted when the test quits, # if you want to keep them around for debugging, pass in delete=False with Tf.NamedTemporaryFile(suffix='.abc') as tempAbcFile, \ Tf.NamedTemporaryFile(suffix='.usda') as tempUsdFile: stage = Usd.Stage.CreateNew(tempUsdFile.name) prim = stage.OverridePrim('/Prim') # Note these test cases come from testSdTypes.py usdValuesToTest = [ ("hello", 'string', 'myString'), (True, 'bool', 'myBool'), (1, 'uchar', 'myUChar'), (1, 'int', 'myInt'), (1, 'uint', 'myUInt'), (1, 'int64', 'myInt64'), (1, 'uint64', 'myUInt64'), (1.0, 'half', 'myHalf'), (1.0, 'float', 'myFloat'), (1.0, 'double', 'myDouble'), (Gf.Vec2d(1, 2), 'double2', 'myVec2d'), (Gf.Vec2f(1, 2), 'float2', 'myVec2f'), (Gf.Vec2h(1, 2), 'half2', 'myVec2h'), (Gf.Vec2i(1, 2), 'int2', 'myVec2i'), (Gf.Vec3d(1, 2, 3), 'double3', 'myVec3d'), (Gf.Vec3f(1, 2, 3), 'float3', 'myVec3f'), (Gf.Vec3h(1, 2, 3), 'half3', 'myVec3h'), (Gf.Vec3i(1, 2, 3), 'int3', 'myVec3i'), (Gf.Vec4d(1, 2, 3, 4), 'double4', 'myVec4d'), (Gf.Vec4f(1, 2, 3, 4), 'float4', 'myVec4f'), (Gf.Vec4h(1, 2, 3, 4), 'half4', 'myVec4h'), (Gf.Vec4i(1, 2, 3, 4), 'int4', 'myVec4i'), (Gf.Matrix4d(3), 'matrix4d', 'myMatrix4d'), (Gf.Quatf(1.0, [2.0, 3.0, 4.0]), 'quatf', 'myQuatf'), (Gf.Quatd(1.0, [2.0, 3.0, 4.0]), 'quatd', 'myQuatd'), (Vt.StringArray(), 'string[]', 'myStringArray'), (Vt.Vec2dArray(), 'double2[]', 'myVec2dArray'), (Vt.Vec2fArray(), 'float2[]', 'myVec2fArray'), (Vt.Vec2hArray(), 'half2[]', 'myVec2hArray'), (Vt.Vec2iArray(), 'int2[]', 'myVec2iArray'), ] for value, typeName, attrName in usdValuesToTest: prim.CreateAttribute(attrName, Sdf.ValueTypeNames.Find(typeName)) prim.GetAttribute(attrName).Set(value) stage.GetRootLayer().Save() # Write out the USD file as .abc UsdAbc._WriteAlembic(tempUsdFile.name, tempAbcFile.name) # Read it back in and expect the same attributes and values stage = Usd.Stage.Open(tempAbcFile.name) prim = stage.GetPrimAtPath('/Prim') self.assertTrue(prim) for value, typeName, attrName in usdValuesToTest: attr = prim.GetAttribute(attrName) self.assertTrue(attr) self.assertEqual(attr.GetTypeName(), typeName) self.assertEqual(attr.Get(), value)
def test_ValidFileCreation(self): with Tf.NamedTemporaryFile(suffix='usda') as tempUsd: self.assertTrue(self.layers[0].Export(tempUsd.name))
def test_ResolvedAssetPaths(self): print 'Testing that asset-path-valued attributes give resolved values' import os for fmt in allFormats: with Tf.NamedTemporaryFile(suffix='.'+fmt) as rootFile, \ Tf.NamedTemporaryFile(suffix='.'+fmt) as targetFile: self.assertEqual(os.path.split(rootFile.name)[0], os.path.split(targetFile.name)[0]) print rootFile.name, targetFile.name s = Usd.Stage.CreateNew(rootFile.name) foo = s.DefinePrim('/foo') singleAsset = foo.CreateAttribute('singleAsset', Sdf.ValueTypeNames.Asset) arrayAsset = foo.CreateAttribute('arrayAsset', Sdf.ValueTypeNames.AssetArray) singleAssetQuery = Usd.AttributeQuery(foo, 'singleAsset') arrayAssetQuery = Usd.AttributeQuery(foo, 'arrayAsset') relPath = './' + os.path.split(targetFile.name)[1] relPathArray = Sdf.AssetPathArray(42, [relPath]) self.assertNotEqual(relPath, targetFile.name) singleAsset.Set(relPath) arrayAsset.Set(relPathArray) singleAssetValue = singleAsset.Get() arrayAssetValue = arrayAsset.Get() singleAssetQueryValue = singleAssetQuery.Get() arrayAssetQueryValue = arrayAssetQuery.Get() self.assertEqual(singleAssetValue.path, relPath) self.assertTrue(all([ap.path == relPath for ap in arrayAssetValue])) # Ensure that attribute query also resolves paths self.assertEqual(singleAssetValue.path, singleAssetQueryValue.path) self.assertEqual([ap.path for ap in arrayAssetValue], [ap.path for ap in arrayAssetQueryValue]) self.assertEqual(singleAssetValue.resolvedPath, targetFile.name) self.assertTrue(all([ap.resolvedPath == targetFile.name for ap in arrayAssetValue])) self.assertEqual(singleAssetValue.resolvedPath, singleAssetQueryValue.resolvedPath) self.assertEqual([ap.resolvedPath for ap in arrayAssetValue], [ap.resolvedPath for ap in arrayAssetQueryValue]) # Test a case where the file does not exist, which the default # resolver doesn't resolve relPath = './nonexistent_file_for_testUsdCreateProperties.xxx' relPathArray = Sdf.AssetPathArray(42, [relPath]) singleAsset.Set(relPath) arrayAsset.Set(relPathArray) singleAssetValue = singleAsset.Get() arrayAssetValue = arrayAsset.Get() self.assertEqual(singleAssetValue.path, relPath) self.assertTrue(all([ap.path == relPath for ap in arrayAssetValue])) self.assertEqual(singleAssetValue.resolvedPath, '') self.assertTrue(all([ap.resolvedPath == '' for ap in arrayAssetValue]))