本文整理汇总了Python中lsst.pex.policy.Policy.set方法的典型用法代码示例。如果您正苦于以下问题:Python Policy.set方法的具体用法?Python Policy.set怎么用?Python Policy.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lsst.pex.policy.Policy
的用法示例。
在下文中一共展示了Policy.set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testSetNothing
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def testSetNothing(self):
p = Policy()
try:
p.set("foo", None)
self.assert_(False, "Setting value to None succeeded.")
except RuntimeError:
self.assertFalse(p.exists("foo"))
示例2: main
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def main(self, argv=None):
self.parseArgs(argv)
# 1. load policy
policy = self.tryThis(Policy,
"Reading policy file \"" + self.policyFile + "\"",
self.policyFile)
# resolve policy file references
polLoadDir = self.options.loadPolicy
polLoadDesc = polLoadDir
if polLoadDir is None:
if self.policyFile.find("/") >= 0:
polLoadDir = self.policyFile.rpartition("/")[0]
polLoadDesc = polLoadDir
else:
polLoadDir = ""
polLoadDesc = "current directory; " \
"try -l DIR or --load-policy-references=DIR"
if self.verbose:
print("No policy load dir specified; defaulting to " + polLoadDesc)
message = "Resolving references in " + self.policyFile \
+ ",\n using " + polLoadDesc
self.tryThis(policy.loadPolicyFiles, message, polLoadDir, True)
# derive short name by trimming off path & suffix
shortname = self.policyFile
if shortname.endswith(".paf"):
shortname = shortname.rpartition(".paf")[0]
if shortname.find("/") >= 0:
shortname = shortname.rpartition("/")[2]
if self.verbose:
print("Short name =", shortname)
# 2. create a dictionary from it
dictionary = Policy()
dictionary.set("target", shortname)
self.generateDict(policy, dictionary)
# TODO: remove commas from lists
if self.verbose:
print("Generating Dictionary for Policy " + self.policyFile + ":")
print("---------------------------Policy---------------------------")
print(policy)
print("-------------------------Dictionary-------------------------")
realDict = Dictionary(dictionary)
try:
realDict.validate(policy)
print("#<?cfg paf dictionary ?>")
writer = PAFWriter()
writer.write(dictionary)
print(writer.toString())
# print(dictionary)
except lsst.pex.exceptions.Exception as e:
ve = e.args[0]
print("Internal error: validation fails against extrapolated dictionary:")
print(ve.describe(" - "))
示例3: testFromPolicy
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def testFromPolicy(self):
type = "CalExp"
path = "goob/CalExp-v88-c12.fits"
ccdid = 12
visitid = 88
p = Policy()
p.set("type", type)
# pdb.set_trace()
ds = Dataset.fromPolicy(p)
self.assertEquals(ds.type, type)
self.assert_(ds.path is None)
self.assert_(ds.ids is None)
p.set("path", path)
ds = Dataset.fromPolicy(p)
self.assertEquals(ds.type, type)
self.assertEquals(ds.path, path)
self.assert_(ds.ids is None)
p.set("ids.ccdid", ccdid)
p.set("ids.visitid", visitid)
ds = Dataset.fromPolicy(p)
self.assertEquals(ds.type, type)
self.assertEquals(ds.path, path)
self.assert_(ds.ids is not None)
self.assertEquals(ds.ids["ccdid"], ccdid)
self.assertEquals(ds.ids["visitid"], visitid)
示例4: testSampleCode
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def testSampleCode(self):
policyFile = DefaultPolicyFile("pex_policy", "defaults_dictionary_complete.paf",
"tests/dictionary")
defaults = Policy.createPolicy(policyFile, policyFile.getRepositoryPath(), True)
policy = Policy()
policy.mergeDefaults(defaults)
self.assert_(policy.canValidate())
policy = Policy()
policy.mergeDefaults(defaults, False)
self.assert_(not policy.canValidate())
# even if not keeping it around for future validation, validate the merge now
policy = Policy()
policy.set("bad", "worse")
self.assertValidationError(ValidationError.UNKNOWN_NAME,
policy.mergeDefaults, defaults, False)
self.assert_(not policy.canValidate())
示例5: PolicyOutStringTestCase
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
class PolicyOutStringTestCase(unittest.TestCase):
def setUp(self):
self.policy = Policy()
self.policy.set("answer", 42)
self.policy.set("name", "ray")
def tearDown(self):
pass
def testDest(self):
dest = PolicyStringDestination("#<?cfg paf policy ?>")
self.assertEquals(dest.getData(), "#<?cfg paf policy ?>")
def testWrite(self):
writer = PAFWriter()
writer.write(self.policy, True)
out = writer.toString();
self.assert_(out.startswith("#<?cfg paf policy ?>"))
示例6: toPolicy
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def toPolicy(self, policy=None):
"""
return a policy that describes this dataset.
@param policy a policy instance to write into. If not provided
(default) a new one is created.
@return Policy the policy containing the description of this dataset.
"""
if not policy:
policy = Policy()
if self.type: policy.set("type", self.type)
if self.ids:
ids = Policy()
policy.set("ids", ids)
for id in self.ids.keys():
ids.set(id, self.ids[id])
if self.path: policy.set("path", self.path)
if self.valid is not None: policy.set("valid", self.valid)
return policy
示例7: testSelfValidation
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def testSelfValidation(self):
# assign a dictionary after creation
p = Policy(self.getTestDictionary("types_policy_good.paf"))
p.loadPolicyFiles(self.getTestDictionary(), True)
typesDict = Dictionary(self.getTestDictionary("types_dictionary.paf"))
valuesDict = Dictionary(self.getTestDictionary("values_dictionary.paf"))
self.assert_(not p.canValidate())
p.setDictionary(typesDict)
self.assert_(p.canValidate())
p.validate()
p.set("bool_type", True)
self.assertValidationError(
ValidationError.WRONG_TYPE, p.set, "bool_type", "foo")
# create with dictionary
p = Policy.createPolicy(self.getTestDictionary("types_dictionary.paf"), "", True)
self.assert_(p.canValidate())
p.set("bool_type", True)
self.assertValidationError(
ValidationError.WRONG_TYPE, p.set, "bool_type", "foo")
# assign a dictionary after invalid modifications
p = Policy()
p.set("bool_type", "foo")
p.setDictionary(typesDict)
ve = ValidationError("Dictionary_1.py", 1, "testSelfValidation")
p.validate(ve)
self.assert_(ve.getErrors("bool_type") == ValidationError.WRONG_TYPE)
try:
p.validate()
except ValidationError, e:
ve = e.args[0]
self.assert_(ve.getErrors("bool_type") == ValidationError.WRONG_TYPE)
self.assert_(ve.getParamCount() == 1)
示例8: setUp
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def setUp(self):
p = Policy()
p.set("foo", "bar")
p.set("count", 3)
p.set("files", "goob")
p.add("files", "gurn")
impl = bb.PolicyBlackboardItem()
impl._props = p
self.bbi = bb.ImplBlackboardItem(impl)
self.initCount = 3
示例9: testEmptySubdict
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def testEmptySubdict(self):
d = Dictionary(self.getTestDictionary("empty_subdictionary.paf"))
p = Policy()
p.set("empty_required", Policy(self.getTestDictionary("simple_policy.paf")))
p.mergeDefaults(d)
self.assert_(p.get("empty_sub_with_default.foo") == "bar")
p.setDictionary(d)
# this works because there is a definition for "empty_sub_with_default.foo"
p.set("empty_sub_with_default.foo", "baz")
p2 = Policy()
p2.set("foo", "baz")
p.set("empty_sub_no_default", p2)
# this fails because Policy tries to makeDef("empty_sub_no_default.foo")
# which fails because there's only a definition for "empty_sub_no_default",
# but it doesn't contain any sub-definitions
# p.set("empty_sub_no_default.foo", "baz")
self.assertRaiseLCE(DictionaryError,
"empty_sub_no_default.dictionary not found",
p.set, "Empty policy definition -- if this fails, "
"it means a known bug has been fixed. That's good.",
"empty_sub_no_default.foo", "baz")
示例10: testReference
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def testReference(self):
addr = "pex_policy:examples:EventTransmitter_policy.paf"
p = Policy()
p.set("transmitter.logVerbosity", "not")
UrnPolicyFile(addr).load(p)
self.assertEqual(p.get("transmitter.logVerbosity"), "debug")
p.set("transmitter.logVerbosity", "not")
UrnPolicyFile("urn:eupspkg:" + addr).load(p)
self.assertEqual(p.get("transmitter.logVerbosity"), "debug")
p.set("transmitter.logVerbosity", "not")
UrnPolicyFile("@@" + addr).load(p)
self.assertEqual(p.get("transmitter.logVerbosity"), "debug")
示例11: testMergeDefaults
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def testMergeDefaults(self):
# from a non-trivial dictionary
p = Policy(self.getTestDictionary("defaults_policy_partial.paf"))
p.set("required", "foo")
d = Dictionary(self.getTestDictionary("defaults_dictionary_good.paf"))
d.loadPolicyFiles(self.getTestDictionary(), True)
self.assert_(p.nameCount() == 2)
p.mergeDefaults(d)
self.assert_(p.valueCount("int_range_count") == 3)
self.assert_(p.nameCount() == 7)
# from a policy that's really a dictionary
p = Policy()
pd = Policy(self.getTestDictionary("defaults_dictionary_indirect.paf"))
p.mergeDefaults(pd)
self.assert_(p.getString("string_type") == "foo")
self.assert_(p.getDictionary().isDictionary())
# from a policy that's really a non-trivial dictionary
p = Policy(self.getTestDictionary("defaults_policy_partial.paf"))
p.set("required", "foo")
pd = Policy(self.getTestDictionary("defaults_dictionary_policy.paf"))
pd.loadPolicyFiles(self.getTestDictionary(), True)
self.assert_(p.nameCount() == 2)
p.mergeDefaults(pd)
self.assert_(p.valueCount("int_range_count") == 3)
self.assert_(p.nameCount() == 5)
# ensure post-load validation
p.set("int_range_count", -5)
self.assertValidationError(ValidationError.UNKNOWN_NAME,
p.add, "unknown", 0)
# test throwing validation
p = Policy(self.getTestDictionary("defaults_policy_partial.paf"))
try:
p.mergeDefaults(pd)
except ValidationError, e:
self.assert_(e.args[0].getErrors("required")
== ValidationError.MISSING_REQUIRED)
示例12: PolicyBlackboardItem
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
class PolicyBlackboardItem(BlackboardItem):
"""
An implementation of a BlackboardItem that stores properities via a
policy
"""
def __init__(self, policyfile=None):
"""
create an item with the given properties.
@param policyfile A policy
"""
# the properties attached to this items
self._props = None
if policyfile:
self._props = Policy.createPolicy(policyfile)
else:
self._props = Policy()
def getProperty(self, name, default=None):
"""
return the value for a property
@param name the property name
@parma default the default value to return if the name is not set
"""
if not self._props.exists(name):
return default
elif self._props.isArray(name):
return self._props.getArray(name)
else:
return self._props.get(name)
def hasProperty(self, name):
"""
return True if the property with the given name is available
"""
return self._props.exists(name)
def __getitem__(self, name):
if not self._props.exists(name):
raise KeyError(name)
return BlackboardItem.__getitem__(self, name)
def _setProperty(self, name, val):
# set a property value
if isinstance(val, list):
self._props.set(name, val.pop(0))
for v in val:
self._props.add(name, v)
else:
self._props.set(name, val)
def getPropertyNames(self):
"""
return the property names that make up this item
"""
return self._props.names()
def _copyFrom(self, item):
for name in item.getPropertyNames():
self._setProperty(name, item.getProperty(name))
@staticmethod
def createFormatter():
return PolicyBlackboardItem._Fmtr()
class _Fmtr(object):
def write(self, filename, item):
pol = None
if isinstance(item, PolicyBlackboardItem):
pol = item._props
else:
delegate = PolicyBlackboardItem()
delegate._copyFrom(item)
pol = delegate._props
writer = PAFWriter(filename)
try:
writer.write(pol, True)
finally:
writer.close()
def openItem(self, filename):
out = PolicyBlackboardItem()
out._props = Policy.createPolicy(filename)
return out
def filenameExt(self):
"""
return the recommended extension for the format this writes out
"""
return "paf"
示例13: testFromPolicy
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def testFromPolicy(self):
p = Policy()
p.set("name", "visit")
idf = id.IntegerIDFilter.fromPolicy(p)
self.testNoConstraints(idf)
idf = id.IDFilter.fromPolicy(p)
self.assert_(isinstance(idf, id.StringIDFilter))
p.set("className", "String")
idf = id.IDFilter.fromPolicy(p)
self.assert_(isinstance(idf, id.StringIDFilter))
self.testNoConstraints(idf)
p.set("className", "StringIDFilter")
idf = id.IDFilter.fromPolicy(p)
self.assert_(isinstance(idf, id.StringIDFilter))
self.testNoConstraints(idf)
p.set("className", "lsst.ctrl.sched.joboffice.id.StringIDFilter")
self.assertRaises(RuntimeError, id.IDFilter.fromPolicy, p)
p.set("className", "String")
p.set("value", "-8")
p.add("value", "r")
p.add("value", "6,0")
idf = id.IDFilter.fromPolicy(p)
self.assert_(isinstance(idf, id.StringIDFilter))
self.testValues2(idf)
示例14: Policy
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
try:
p.mergeDefaults(pd)
except ValidationError, e:
self.assert_(e.args[0].getErrors("required")
== ValidationError.MISSING_REQUIRED)
# non-throwing validation
p = Policy(self.getTestDictionary("defaults_policy_partial.paf"))
ve = ValidationError("Dictionary_1.py", 1, "testMergeDefaults")
p.mergeDefaults(pd, False, ve)
self.assert_(ve.getErrors("required") == ValidationError.MISSING_REQUIRED)
self.assert_(ve.getParamCount() == 1)
# non-retention
p = Policy(self.getTestDictionary("defaults_policy_partial.paf"))
p.set("required", "foo")
p.mergeDefaults(pd, False)
# make sure validate() fails gracefully when no dictionary present
self.assertRaisesEx(DictionaryError, "No dictionary",
p.validate, "No dictionary assigned")
p.add("unknown", 0) # would be rejected if dictionary was kept
# deep merge from a Policy that's not a Dictionary
p = Policy(self.getTestDictionary("defaults_policy_partial.paf"))
p.mergeDefaults(Policy(self.getTestDictionary("defaults_policy_most.paf")))
self.assert_(p.nameCount() == 3)
self.assert_(p.getBool("bool_set_count") == True)
self.assert_(p.getString("indirect.string_type") == "bar")
# propagation of a Dictionary from one Policy to another via mergeDefaults
d = Dictionary(self.getTestDictionary("defaults_dictionary_complete.paf"))
示例15: generateDict
# 需要导入模块: from lsst.pex.policy import Policy [as 别名]
# 或者: from lsst.pex.policy.Policy import set [as 别名]
def generateDict(self, policy, dictionary, prefix=""):
definitions = Policy()
dictionary.set("definitions", definitions)
names = policy.names(True)
for name in names:
values = policy.getArray(name)
defin = Policy()
definitions.set(name, defin)
defin.set("type", policy.getTypeName(name))
defin.set("minOccurs", 1)
defin.set("maxOccurs", len(values))
type = policy.getValueType(name)
if type == Policy.POLICY:
newPrefix = prefix + "." + name
subdict = Policy()
defin.set("dictionary", subdict)
if len(values) > 1:
print("# Warning: only using first value of", newPrefix)
self.generateDict(values[0], subdict, newPrefix)
else:
allowed = Policy()
defin.set("allowed", allowed)
orderable = type == Policy.INT or type == Policy.DOUBLE \
or type == Policy.STRING
if orderable:
allowed.set("min", min(values))
allowed.set("max", max(values))
for value in values:
defin.add("default", value)
allowed.add("value", value)