Skip to content

Commit

Permalink
Schema.has_entity and Schema.has_field
Browse files Browse the repository at this point in the history
  • Loading branch information
mikeboers committed Oct 29, 2015
1 parent b34eeb4 commit 94f6c7b
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
22 changes: 22 additions & 0 deletions sgschema/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,28 @@ def resolve_one_field(self, entity_type, field_spec, **kwargs):
else:
raise ValueError('%r returned %s %s fields' % (field_spec, len(res), entity_type))

def has_entity(self, entity_spec, **kwargs):
kwargs['strict'] = True
try:
entities = self.resolve_entity(entity_spec, **kwargs)
return bool(entities)
except ValueError as e:
if 'is not an entity' in e.args[0]:
return False
else:
raise

def has_field(self, entity_type, field_spec, **kwargs):
kwargs['strict'] = True
try:
fields = self.resolve_field(entity_type, field_spec, **kwargs)
return bool(fields)
except ValueError as e:
if 'is not a field' in e.args[0]:
return False
else:
raise

def resolve_structure(self, x, entity_type=None, **kwargs):
"""Traverse a nested structure resolving names in entities.
Expand Down
10 changes: 9 additions & 1 deletion tests/test_entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,12 @@ def test_one(self):
self.assertEqual(self.s.resolve_one_entity('$Alias'), 'Entity')
self.assertEqual(self.s.resolve_one_entity('#TagOne'), 'Entity')
self.assertRaises(ValueError, self.s.resolve_one_entity, '#TagNone')
self.assertRaises(ValueError, self.s.resolve_one_entity, '#TagTwo')
self.assertRaises(ValueError, self.s.resolve_one_entity, '#TagTwo')

def test_has_entity(self):
self.assertTrue(self.s.has_entity('Entity'))
self.assertTrue(self.s.has_entity('!Entity'))
self.assertTrue(self.s.has_entity('$Alias'))
self.assertTrue(self.s.has_entity('#TagOne'))
self.assertFalse(self.s.has_entity('NotAnEntity'))
self.assertFalse(self.s.has_entity('#TagNone'))
10 changes: 10 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,13 @@ def test_many(self):
'sg_type', 'sg_version', 'attr', 'multi_a', 'multi_b',
])

def test_has_field(self):
self.assertTrue(self.s.has_field('Entity', 'sg_type'))
self.assertTrue(self.s.has_field('Entity', 'version'))
self.assertTrue(self.s.has_field('Entity', '$alias'))
self.assertTrue(self.s.has_field('Entity', '#tagone'))
self.assertTrue(self.s.has_field('Entity', '#tagtwo'))
self.assertFalse(self.s.has_field('Entity', '#tagnone'))
self.assertFalse(self.s.has_field('Entity', 'notafield'))
self.assertRaises(ValueError, self.s.has_field, 'NotAnEntity', 'whatever')

0 comments on commit 94f6c7b

Please sign in to comment.