def test_module_provides(self): from BTrees import family64 from zope.interface import providedBy for name in IBTreeFamily: if 'int' in name: continue module = getattr(btrees.family64LargeBuckets, name) assert_that(module, verifiably_provides(IBTreeModule)) assert_that( module, verifiably_provides(*providedBy(getattr(family64, name)))) # That checks the un-adorned names like BTree; it doesn't # check that the prefix names are available. for attr_name in IBTreeModule: # The names are generic for 32-bit; the real named objects # are 64-bit prefix = name.replace('I', 'L').replace('U', 'Q') dec_attr_name = prefix + attr_name tree = getattr(module, attr_name) assert_that(module, has_property(dec_attr_name, same_instance(tree))) assert_that( tree, has_property('max_leaf_size', btrees.MAX_LEAF_SIZE)) assert_that( tree, has_property('max_internal_size', btrees.MAX_INTERNAL_SIZE))
def test_normalize_html_text_to_par(self): html = u'<html><body><p style=" text-align: left;"><span style="font-family: \'Helvetica\'; font-size: 12pt; color: black;">The pad replies to my note.</span></p>The server edits it.</body></html>' exp = u'<html><body><p style="text-align: left;"><span>The pad replies to my note.</span></p><p style="text-align: left;">The server edits it.</p></body></html>' sanitized = _check_sanitized(html, exp, frg_interfaces.ISanitizedHTMLContentFragment) plain_text = frg_interfaces.IPlainTextContentFragment(sanitized) assert_that(plain_text, verifiably_provides(frg_interfaces.IPlainTextContentFragment)) assert_that(plain_text, is_("The pad replies to my note.The server edits it."))
def test_provides(self): cat = self._makeOne() assert_that(type(cat), implements(self.main_interface)) assert_that(cat, validly_provides(self.main_interface)) assert_that(cat, validly_provides(*self.extra_interfaces)) assert_that( cat, does_not(verifiably_provides(*self.doesnt_provide_interfaces)))
def test_sanitize_user_html_chat(self): exp = u'<html><a href=\'http://tag:nextthought.com,2011-10:julie.zhu-OID-0x148a37:55736572735f315f54657374:hjJe3dfZMVb,"body":["5:::{\\"args\\\'>foo</html>' plain_text = frg_interfaces.IPlainTextContentFragment(exp) assert_that(plain_text, verifiably_provides(frg_interfaces.IPlainTextContentFragment)) # idempotent assert_that(frag_html._sanitize_user_html_to_text(plain_text), is_(same_instance(plain_text))) assert_that(frag_html._html_to_sanitized_text(plain_text), is_(same_instance(plain_text)))
def test_pickle(self): with mock_db_trans() as conn: user = self._create_user('*****@*****.**', conn) ref = wref.WeakRef(user) assert_that(ref, has_property('_v_entity_cache', user)) copy = pickle.loads(pickle.dumps(ref)) assert_that(copy, has_property('_v_entity_cache', none())) assert_that(copy(), is_(user)) assert_that(ref, is_(copy)) assert_that(copy, is_(ref)) assert_that(repr(copy), is_(repr(ref))) assert_that(hash(copy), is_(hash(ref))) assert_that(ref, verifiably_provides(IWeakRef)) assert_that(ref, verifiably_provides(ICachingWeakRef)) assert_that(ref, verifiably_provides(IWeakRefToMissing))
def test_cannot_set_attributes_but_can_provide_interfaces_across_pickles(self): all_ucf_subclasses = set() def r(t): if t in all_ucf_subclasses: return all_ucf_subclasses.add(t) for x in t.__subclasses__(): r(x) r(UnicodeContentFragment) # Plus some fixed one just 'cause all_ucf_subclasses.update((SanitizedHTMLContentFragment, HTMLContentFragment, PlainTextContentFragment, UnicodeContentFragment)) for t in all_ucf_subclasses: if t.__module__ != 'nti.contentfragments.interfaces': continue s1 = t('safe') assert_that(calling(setattr).with_args(s1, '__parent__', 'foo'), raises(AttributeError)) # If we do sneak one into the dictionary, it doesn't survive pickling try: s1dict = unicode.__getattribute__(s1, '__dict__') s1dict['__parent__'] = 'foo' except AttributeError: if t is not UnicodeContentFragment: # The root really doesn't allow this, # but for some reason of inheritance the # subclasses do? raise copy = pickle.loads(pickle.dumps(s1)) assert_that(copy, is_(s1)) try: copy_dict = unicode.__getattribute__(copy, '__dict__') except AttributeError: if t is not UnicodeContentFragment: raise copy_dict = {} assert_that(copy_dict, is_({})) # But if they provided extra interfaces, this does persist interface.alsoProvides(s1, ITest) copy = pickle.loads(pickle.dumps(s1)) assert_that(copy, verifiably_provides(ITest))
def test_to_stand_dict_uses_dubcore(self): @interface.implementer(dub_interfaces.IDCTimes) class X(object): created = datetime.datetime.now() modified = datetime.datetime.now() assert_that(X(), verifiably_provides(dub_interfaces.IDCTimes)) ex_dic = to_standard_external_dictionary(X()) assert_that( ex_dic, has_entry(StandardExternalFields.LAST_MODIFIED, is_(Number))) assert_that( ex_dic, has_entry(StandardExternalFields.CREATED_TIME, is_(Number)))
def test_to_stand_dict_prefers_direct_fields(self): @interface.implementer(dub_interfaces.IDCTimes) class X(object): created = datetime.datetime.now() modified = created createdTime = 123456789 lastModified = 8675309 assert_that(X(), verifiably_provides(dub_interfaces.IDCTimes)) ex_dic = to_standard_external_dictionary(X()) assert_that( ex_dic, has_entry(StandardExternalFields.LAST_MODIFIED, is_(X.lastModified))) assert_that( ex_dic, has_entry(StandardExternalFields.CREATED_TIME, is_(X.createdTime)))
def test_parse_ntiid(self): ntiid = get_parts(ROOT) assert_that(ntiid, verifiably_provides(INTIID)) ntiid = get_parts(u'mystrįng') assert_that(ntiid, has_property('provider', is_(none()))) assert_that(ntiid, has_property('nttype', is_(none()))) assert_that(ntiid, has_property('specific', is_(none()))) assert_that(ntiid, has_property('date', is_(none()))) ntiid = u'tag:nextthought.com,2011-10:Foo-Bar-With:Many:Colons' validate_ntiid_string(ntiid) ntiid = get_parts(ntiid) assert_that(ntiid, has_property('provider', 'Foo')) assert_that(ntiid, has_property('nttype', 'Bar')) assert_that(ntiid, has_property('specific', 'With:Many:Colons')) ntiid = get_parts(u'tag:nextthought.com,20:Foo-Bar') assert_that(ntiid, has_property('provider', is_(none()))) assert_that(ntiid, has_property('nttype', 'Foo')) assert_that(ntiid, has_property('specific', 'Bar')) assert_that(ntiid, has_property('date', '20')) with self.assertRaises(InvalidNTIIDError): validate_ntiid_string(u'mystrįng') if six.PY2: with self.assertRaises(InvalidNTIIDError): validate_ntiid_string('いちご', 'ascii') with self.assertRaises(InvalidNTIIDError): validate_ntiid_string(u'tag:nextthought.com,20') with self.assertRaises(InvalidNTIIDError): validate_ntiid_string(u'tag:nextthought.com,20:NTI-HTML-764-85-31-19910') with self.assertRaises(InvalidNTIIDError): validate_ntiid_string(u'tag:nextthought.com,20:NTI-HTML-????')
def test_to_stand_dict_uses_dubcore_iso8601(self): from ..interfaces import ExternalizationPolicy from ..datetime import datetime_to_string policy = ExternalizationPolicy(use_iso8601_for_unix_timestamp=True) @interface.implementer(dub_interfaces.IDCTimes) class X(object): created = datetime.datetime.now() modified = created assert_that(X(), verifiably_provides(dub_interfaces.IDCTimes)) expected_string = datetime_to_string(X.created).toExternalObject() ex_dic = to_standard_external_dictionary(X(), policy=policy) assert_that( ex_dic, has_entry(StandardExternalFields.LAST_MODIFIED, is_(expected_string))) assert_that( ex_dic, has_entry(StandardExternalFields.CREATED_TIME, is_(expected_string)))
def test_subclass(self): from nti.externalization.interfaces import IInternalObjectExternalizer from nti.externalization.datastructures import StandardInternalObjectExternalizer from nti.externalization._compat import PURE_PYTHON class X(StandardInternalObjectExternalizer): def __init__(self, context): StandardInternalObjectExternalizer.__init__(self, context) self.__external_class_name__ = 'Foo' class Ext(object): creator = 'sjohnson' o = X(Ext()) assert_that(o, verifiably_provides(IInternalObjectExternalizer)) ext = o.toExternalObject() assert_that(ext, is_({ 'Class': 'Foo', 'Creator': 'sjohnson', })) # Now non-native-strs ext = Ext() ext.creator = u'sjohnson' o.context = ext if not PURE_PYTHON: # XXX: pure-python mode allows anything. with self.assertRaises(TypeError): o.__external_class_name__ = u'Foo' if bytes is str else b'Foo' ext = o.toExternalObject() assert_that(ext, is_({ 'Class': 'Foo', 'Creator': 'sjohnson', }))
def test_provides(self): from nti.externalization.interfaces import IInternalObjectExternalizer from nti.externalization.datastructures import StandardInternalObjectExternalizer o = StandardInternalObjectExternalizer(object()) assert_that(o, verifiably_provides(IInternalObjectExternalizer))
def test_interface(self): u = IntIds("_ds_id") assert_that(u, validly_provides(IIntIds)) assert_that(u, verifiably_provides(IIntIds)) assert_that(repr(u), is_not(none()))
def test_site_sync(self): for site in _SITES: assert_that(_find_site_components((site.__name__,)), is_(not_none())) with mock_db_trans() as conn: for site in _SITES: assert_that(_find_site_components((site.__name__,)), is_(not_none())) ds = conn.root()['nti.dataserver'] assert ds is not None sites = ds['++etc++hostsites'] for site in _SITES: assert_that(sites, does_not(has_key(site.__name__))) synchronize_host_policies() synchronize_host_policies() assert_that(self._events, has_length(len(_SITES))) # These were put in in order # assert_that( self._events[0][0].__parent__, # has_property('__name__', EVAL.__name__)) # XXX These two lines are cover only. get_host_site(DEMO.__name__) get_host_site('DNE', True) assert_that(calling(get_host_site).with_args('dne'), raises(LookupError)) with mock_db_trans() as conn: for site in _SITES: assert_that(_find_site_components((site.__name__,)), is_(not_none())) ds = conn.root()['nti.dataserver'] assert ds is not None sites = ds['++etc++hostsites'] assert_that(sites, has_key(EVAL.__name__)) assert_that(sites[EVAL.__name__], verifiably_provides(ISite)) # If we ask the demoalpha persistent site for an ITestSyteSync, # it will find us, because it goes to the demo global site assert_that(sites[DEMOALPHA.__name__].getSiteManager().queryUtility(ITestSiteSync), is_(ASync)) # However, if we put something in the demo *persistent* site, it # will find that sites[DEMO.__name__].getSiteManager().registerUtility(OtherSync()) assert_that(sites[DEMOALPHA.__name__].getSiteManager().queryUtility(ITestSiteSync), is_(OtherSync)) # Verify the resolution order too def _name(x): if x.__name__ == '++etc++site': return 'P' + str(x.__parent__.__name__) return x.__name__ assert_that([_name(x) for x in ro.ro(sites[DEMOALPHA.__name__].getSiteManager())], is_([u'Pdemo-alpha.nextthoughttest.com', u'demo-alpha.nextthoughttest.com', u'Pdemo.nextthoughttest.com', u'demo.nextthoughttest.com', u'Peval.nextthoughttest.com', u'eval.nextthoughttest.com', u'Pdataserver2', u'PNone', 'base'])) # including if we ask to travers from top to bottom names = list() def func(): names.append(_name(component.getSiteManager())) run_job_in_all_host_sites(func) # Note that PDemo and Peval-alpha are arbitrary, they both # descend from eval; # TODO: why aren't we maintaining alphabetical order? # we should be, but sometimes we don't assert_that(names, is_(any_of( [u'Peval.nextthoughttest.com', u'Pdemo.nextthoughttest.com', u'Peval-alpha.nextthoughttest.com', u'Pdemo-alpha.nextthoughttest.com'], [u'Peval.nextthoughttest.com', u'Peval-alpha.nextthoughttest.com', u'Pdemo.nextthoughttest.com', u'Pdemo-alpha.nextthoughttest.com']))) # And that it's what we get back if we ask for it assert_that(get_site_for_site_names((DEMOALPHA.__name__,)), is_(same_instance(sites[DEMOALPHA.__name__]))) # No new sites created assert_that(self._events, has_length(len(_SITES)))
def test_blog_html_to_text(self): exp = u'<html><body>Independence<br />America<br />Expecting<br />Spaces</body></html>' plain_text = frg_interfaces.IPlainTextContentFragment(exp) assert_that(plain_text, verifiably_provides(frg_interfaces.IPlainTextContentFragment)) assert_that(plain_text, is_("Independence\nAmerica\nExpecting\nSpaces"))
def test_provides(self): assert_that(btrees.family64LargeBuckets, verifiably_provides(IBTreeFamily))
def test_numeric_value_interface(self): val = self._makeOne() assert_that(val, verifiably_provides(interfaces.INumericValue))
def test_provides(self): assert_that(PlainTextToLatexFragmentConverter, implements(ILatexContentFragment)) assert_that(PlainTextToLatexFragmentConverter('foo'), verifiably_provides(ILatexContentFragment))
def _check_sanitized(inp, expect, expect_iface=frg_interfaces.IUnicodeContentFragment): was = frg_interfaces.IUnicodeContentFragment(inp) __traceback_info__ = inp, type(inp), was, type(was) assert_that(was, is_(expect.strip())) assert_that(was, verifiably_provides(expect_iface)) return was
def test_provides_interface(self): assert_that(self._makeOne(), verifiably_provides(ITPCStateVoting))
def test_adapts(self): request = Request.blank('/') zrequest = IBrowserRequest(request) assert_that(zrequest, verifiably_provides(IBrowserRequest)) # and it's still a valid pyramid request assert_that(zrequest, verifiably_provides(IRequest))
def test_html_to_text(self): exp = frg_interfaces.HTMLContentFragment('<html><body><p style="text-align: left;"><span>The pad replies to my note.</span></p><p style="text-align: left;">The server edits it.</p></body></html>') plain_text = frg_interfaces.IPlainTextContentFragment(exp) assert_that(plain_text, verifiably_provides(frg_interfaces.IPlainTextContentFragment)) assert_that(plain_text, is_("The pad replies to my note.The server edits it."))
def test_implements_interface(self): inst = self._makeOne() assert_that(inst, verifiably_provides(self._getTargetInterface()))