Best Python code snippet using selene_python
test_12_s_utils.py
Source:test_12_s_utils.py
1# !/usr/bin/env python2# -*- coding: utf-8 -*-3import base644import six5from saml2 import s_utils as utils6from saml2 import saml7from saml2 import samlp8from saml2.argtree import set_arg9from saml2.s_utils import do_attribute_statement10from saml2.saml import Attribute, Subject11from saml2.saml import NAME_FORMAT_URI12from py.test import raises13from pathutils import full_path14XML_HEADER = '<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n'15SUCCESS_STATUS_NO_HEADER = (16 '<ns0:Status xmlns:ns0="urn:oasis:names:tc:SAML:2.0:protocol"><ns0'17 ':StatusCode '18 'Value="urn:oasis:names:tc:SAML:2.0:status:Success" /></ns0:Status>')19SUCCESS_STATUS = '%s%s' % (XML_HEADER, SUCCESS_STATUS_NO_HEADER)20ERROR_STATUS_NO_HEADER = (21 '<ns0:Status xmlns:ns0="urn:oasis:names:tc:SAML:2.0:protocol"><ns0'22 ':StatusCode '23 'Value="urn:oasis:names:tc:SAML:2.0:status:Responder"><ns0:StatusCode '24 'Value="urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal" '25 '/></ns0:StatusCode><ns0:StatusMessage>Error resolving '26 'principal</ns0:StatusMessage></ns0:Status>')27ERROR_STATUS_NO_HEADER_EMPTY = (28 '<ns0:Status xmlns:ns0="urn:oasis:names:tc:SAML:2.0:protocol"><ns0'29 ':StatusCode '30 'Value="urn:oasis:names:tc:SAML:2.0:status:Responder"><ns0:StatusCode '31 'Value="urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal" '32 '/></ns0:StatusCode></ns0:Status>')33ERROR_STATUS = '%s%s' % (XML_HEADER, ERROR_STATUS_NO_HEADER)34ERROR_STATUS_EMPTY = '%s%s' % (XML_HEADER, ERROR_STATUS_NO_HEADER_EMPTY)35def _eq(l1, l2):36 return set(l1) == set(l2)37def _oeq(l1, l2):38 if len(l1) != len(l2):39 print("Different number of items")40 return False41 for item in l1:42 if item not in l2:43 print("%s not in l2" % (item,))44 for ite in l2:45 print("\t%s" % (ite,))46 return False47 return True48def test_inflate_then_deflate():49 txt = """Selma Lagerlöf (1858-1940) was born in Ãstra Emterwik, Värmland,50 Sweden. She was brought up on MÃ¥rbacka, the family estate, which she did 51 not leave until 1881, when she went to a teachers' college at Stockholm"""52 if not isinstance(txt, six.binary_type):53 txt = txt.encode('utf-8')54 interm = utils.deflate_and_base64_encode(txt)55 bis = utils.decode_base64_and_inflate(interm)56 if not isinstance(bis, six.binary_type):57 bis = bis.encode('utf-8')58 assert bis == txt59def test_status_success():60 status = utils.success_status_factory()61 status_text = "%s" % status62 assert status_text in (SUCCESS_STATUS_NO_HEADER, SUCCESS_STATUS)63 assert status.status_code.value == samlp.STATUS_SUCCESS64def test_error_status():65 status = utils.status_message_factory("Error resolving principal",66 samlp.STATUS_UNKNOWN_PRINCIPAL,67 samlp.STATUS_RESPONDER)68 status_text = "%s" % status69 print(status_text)70 assert status_text in (ERROR_STATUS_NO_HEADER, ERROR_STATUS)71def test_status_from_exception():72 e = utils.UnknownPrincipal("Error resolving principal")73 stat = utils.error_status_factory(e)74 status_text = "%s" % stat75 print(status_text)76 assert status_text in (ERROR_STATUS_NO_HEADER, ERROR_STATUS)77def test_status_from_tuple():78 stat = utils.error_status_factory((samlp.STATUS_UNKNOWN_PRINCIPAL,79 'Error resolving principal'))80 status_text = "%s" % stat81 assert status_text in (ERROR_STATUS_NO_HEADER, ERROR_STATUS)82def test_status_from_tuple_empty_message():83 stat = utils.error_status_factory((samlp.STATUS_UNKNOWN_PRINCIPAL, None))84 status_text = "%s" % stat85 assert status_text in (ERROR_STATUS_EMPTY, ERROR_STATUS_NO_HEADER_EMPTY)86def test_attribute_sn():87 attr = utils.do_attributes({"surName": ("Jeter", "")})88 assert len(attr) == 189 print(attr)90 inst = attr[0]91 assert inst.name == "surName"92 assert len(inst.attribute_value) == 193 av = inst.attribute_value[0]94 assert av.text == "Jeter"95def test_attribute_age():96 attr = utils.do_attributes({"age": (37, "")})97 assert len(attr) == 198 inst = attr[0]99 print(inst)100 assert inst.name == "age"101 assert len(inst.attribute_value) == 1102 av = inst.attribute_value[0]103 assert av.text == "37"104 assert av.get_type() == "xs:integer"105def test_attribute_onoff():106 attr = utils.do_attributes({"onoff": (False, "")})107 assert len(attr) == 1108 inst = attr[0]109 print(inst)110 assert inst.name == "onoff"111 assert len(inst.attribute_value) == 1112 av = inst.attribute_value[0]113 assert av.text == "false"114 assert av.get_type() == "xs:boolean"115def test_attribute_base64():116 txt = "Selma Lagerlöf"117 if not isinstance(txt, six.binary_type):118 txt = txt.encode("utf-8")119 b64sl = base64.b64encode(txt).decode('ascii')120 attr = utils.do_attributes({"name": (b64sl, "xs:base64Binary")})121 assert len(attr) == 1122 inst = attr[0]123 print(inst)124 assert inst.name == "name"125 assert len(inst.attribute_value) == 1126 av = inst.attribute_value[0]127 assert av.get_type() == "xs:base64Binary"128 assert av.text.strip() == b64sl129def test_attribute_statement():130 statement = do_attribute_statement({"surName": ("Jeter", ""),131 "givenName": ("Derek", "")})132 print(statement)133 assert statement.keyswv() == ["attribute"]134 assert len(statement.attribute) == 2135 attr0 = statement.attribute[0]136 assert _eq(attr0.keyswv(), ["name", "attribute_value", "name_format"])137 assert len(attr0.attribute_value) == 1138 attr1 = statement.attribute[1]139 assert _eq(attr1.keyswv(), ["name", "attribute_value", "name_format"])140 assert len(attr1.attribute_value) == 1141 if attr0.name == "givenName":142 assert attr0.attribute_value[0].text == "Derek"143 assert attr1.name == "surName"144 assert attr1.attribute_value[0].text == "Jeter"145 else:146 assert attr0.name == "surName"147 assert attr0.attribute_value[0].text == "Jeter"148 assert attr1.name == "givenName"149 assert attr1.attribute_value[0].text == "Derek"150def test_audience():151 aud_restr = utils.factory(saml.AudienceRestriction,152 audience=utils.factory(saml.Audience,153 text="urn:foo:bar"))154 assert aud_restr.keyswv() == ["audience"]155 assert aud_restr.audience.text == "urn:foo:bar"156def test_conditions():157 conditions = utils.factory(saml.Conditions,158 not_before="2009-10-30T07:58:10.852Z",159 not_on_or_after="2009-10-30T08:03:10.852Z",160 audience_restriction=[161 utils.factory(saml.AudienceRestriction,162 audience=utils.factory(163 saml.Audience,164 text="urn:foo:bar"))])165 assert _eq(conditions.keyswv(), ["not_before", "not_on_or_after",166 "audience_restriction"])167 assert conditions.not_before == "2009-10-30T07:58:10.852Z"168 assert conditions.not_on_or_after == "2009-10-30T08:03:10.852Z"169 assert conditions.audience_restriction[0].audience.text == "urn:foo:bar"170def test_value_1():171 # FriendlyName="givenName" Name="urn:oid:2.5.4.42"172 # NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"173 attribute = utils.factory(saml.Attribute, name="urn:oid:2.5.4.42",174 name_format=NAME_FORMAT_URI)175 assert _eq(attribute.keyswv(), ["name", "name_format"])176 assert attribute.name == "urn:oid:2.5.4.42"177 assert attribute.name_format == saml.NAME_FORMAT_URI178def test_value_2():179 attribute = utils.factory(saml.Attribute, name="urn:oid:2.5.4.42",180 name_format=NAME_FORMAT_URI,181 friendly_name="givenName")182 assert _eq(attribute.keyswv(), ["name", "name_format", "friendly_name"])183 assert attribute.name == "urn:oid:2.5.4.42"184 assert attribute.name_format == NAME_FORMAT_URI185 assert attribute.friendly_name == "givenName"186def test_value_3():187 attribute = utils.factory(saml.Attribute,188 attribute_value=[utils.factory(189 saml.AttributeValue, text="Derek")],190 name="urn:oid:2.5.4.42",191 name_format=NAME_FORMAT_URI,192 friendly_name="givenName")193 assert _eq(attribute.keyswv(), ["name", "name_format",194 "friendly_name", "attribute_value"])195 assert attribute.name == "urn:oid:2.5.4.42"196 assert attribute.name_format == NAME_FORMAT_URI197 assert attribute.friendly_name == "givenName"198 assert len(attribute.attribute_value) == 1199 assert attribute.attribute_value[0].text == "Derek"200def test_value_4():201 attribute = utils.factory(saml.Attribute,202 attribute_value=[utils.factory(203 saml.AttributeValue, text="Derek")],204 friendly_name="givenName")205 assert _eq(attribute.keyswv(), ["friendly_name", "attribute_value",206 "name_format"])207 assert attribute.friendly_name == "givenName"208 assert len(attribute.attribute_value) == 1209 assert attribute.attribute_value[0].text == "Derek"210def test_do_attribute_statement_0():211 statement = do_attribute_statement({"vo_attr": ("foobar", "")})212 assert statement.keyswv() == ["attribute"]213 assert len(statement.attribute) == 1214 attr0 = statement.attribute[0]215 assert _eq(attr0.keyswv(), ["name", "attribute_value", "name_format"])216 assert attr0.name == "vo_attr"217 assert len(attr0.attribute_value) == 1218 assert attr0.attribute_value[0].text == "foobar"219def test_do_attribute_statement():220 statement = do_attribute_statement({"surName": ("Jeter", ""),221 "givenName": (["Derek",222 "Sanderson"], "")})223 assert statement.keyswv() == ["attribute"]224 assert len(statement.attribute) == 2225 attr0 = statement.attribute[0]226 assert _eq(attr0.keyswv(), ["name", "attribute_value", "name_format"])227 attr1 = statement.attribute[1]228 assert _eq(attr1.keyswv(), ["name", "attribute_value", "name_format"])229 if attr0.name == "givenName":230 assert len(attr0.attribute_value) == 2231 assert _eq([av.text for av in attr0.attribute_value],232 ["Derek", "Sanderson"])233 assert attr1.name == "surName"234 assert attr1.attribute_value[0].text == "Jeter"235 assert len(attr1.attribute_value) == 1236 else:237 assert attr0.name == "surName"238 assert attr0.attribute_value[0].text == "Jeter"239 assert len(attr0.attribute_value) == 1240 assert attr1.name == "givenName"241 assert len(attr1.attribute_value) == 2242 assert _eq([av.text for av in attr1.attribute_value],243 ["Derek", "Sanderson"])244def test_do_attribute_statement_multi():245 statement = do_attribute_statement(246 {("urn:oid:1.3.6.1.4.1.5923.1.1.1.7",247 "urn:oasis:names:tc:SAML:2.0:attrname-format:uri",248 "eduPersonEntitlement"): ("Jeter", "")})249 assert statement.keyswv() == ["attribute"]250 assert len(statement.attribute)251 assert _eq(statement.attribute[0].keyswv(),252 ["name", "name_format", "friendly_name", "attribute_value"])253 attribute = statement.attribute[0]254 assert attribute.name == "urn:oid:1.3.6.1.4.1.5923.1.1.1.7"255 assert attribute.name_format == (256 "urn:oasis:names:tc:SAML:2.0:attrname-format:uri")257 assert attribute.friendly_name == "eduPersonEntitlement"258def test_subject():259 subject = utils.factory(saml.Subject, text="_aaa",260 name_id=saml.NameID(261 text=saml.NAMEID_FORMAT_TRANSIENT))262 assert _eq(subject.keyswv(), ["text", "name_id"])263 assert subject.text == "_aaa"264 assert subject.name_id.text == saml.NAMEID_FORMAT_TRANSIENT265# ---------------------------------------------------------------------------266def test_parse_attribute_map():267 (forward, backward) = utils.parse_attribute_map(268 [full_path("attribute.map")])269 assert _eq(forward.keys(), backward.values())270 assert _eq(forward.values(), backward.keys())271 print(forward.keys())272 assert _oeq(forward.keys(), [273 ('urn:oid:1.3.6.1.4.1.5923.1.1.1.7', NAME_FORMAT_URI),274 ('urn:oid:0.9.2342.19200300.100.1.1', NAME_FORMAT_URI),275 ('urn:oid:1.3.6.1.4.1.5923.1.1.1.1', NAME_FORMAT_URI),276 ('urn:oid:2.5.4.42', NAME_FORMAT_URI),277 ('urn:oid:2.5.4.4', NAME_FORMAT_URI),278 ('urn:oid:0.9.2342.19200300.100.1.3', NAME_FORMAT_URI),279 ('urn:oid:2.5.4.12', NAME_FORMAT_URI)])280 assert _eq(forward.keys(), [281 ('urn:oid:1.3.6.1.4.1.5923.1.1.1.7', NAME_FORMAT_URI),282 ('urn:oid:0.9.2342.19200300.100.1.1', NAME_FORMAT_URI),283 ('urn:oid:1.3.6.1.4.1.5923.1.1.1.1', NAME_FORMAT_URI),284 ('urn:oid:2.5.4.42', NAME_FORMAT_URI),285 ('urn:oid:2.5.4.4', NAME_FORMAT_URI),286 ('urn:oid:0.9.2342.19200300.100.1.3', NAME_FORMAT_URI),287 ('urn:oid:2.5.4.12', NAME_FORMAT_URI)])288 assert _eq(backward.keys(), ["surName", "givenName", "title", "uid", "mail",289 "eduPersonAffiliation",290 "eduPersonEntitlement"])291def test_identity_attribute_0():292 (forward, backward) = utils.parse_attribute_map(293 [full_path("attribute.map")])294 a = Attribute(name="urn:oid:2.5.4.4", name_format=NAME_FORMAT_URI,295 friendly_name="surName")296 assert utils.identity_attribute("name", a, forward) == "urn:oid:2.5.4.4"297 assert utils.identity_attribute("friendly", a, forward) == "surName"298def test_identity_attribute_1():299 (forward, backward) = utils.parse_attribute_map(300 [full_path("attribute.map")])301 a = Attribute(name="urn:oid:2.5.4.4", name_format=NAME_FORMAT_URI)302 assert utils.identity_attribute("name", a, forward) == "urn:oid:2.5.4.4"303 assert utils.identity_attribute("friendly", a, forward) == "surName"304def test_identity_attribute_2():305 (forward, backward) = utils.parse_attribute_map(306 [full_path("attribute.map")])307 a = Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI)308 assert utils.identity_attribute("name", a, forward) == "urn:oid:2.5.4.5"309 # if there would be a map it would be serialNumber310 assert utils.identity_attribute("friendly", a, forward) == "urn:oid:2.5.4.5"311def test_identity_attribute_3():312 a = Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI)313 assert utils.identity_attribute("name", a) == "urn:oid:2.5.4.5"314 # if there would be a map it would be serialNumber315 assert utils.identity_attribute("friendly", a) == "urn:oid:2.5.4.5"316def test_identity_attribute_4():317 a = Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,318 friendly_name="serialNumber")319 assert utils.identity_attribute("name", a) == "urn:oid:2.5.4.5"320 # if there would be a map it would be serialNumber321 assert utils.identity_attribute("friendly", a) == "serialNumber"322def given_name(a):323 assert a["name"] == "urn:oid:2.5.4.42"324 assert a["friendly_name"] == "givenName"325 assert len(a["attribute_value"]) == 1326 assert a["attribute_value"] == [{"text": "Derek"}]327def sur_name(a):328 assert a["name"] == "urn:oid:2.5.4.4"329 assert a["friendly_name"] == "surName"330 assert len(a["attribute_value"]) == 1331 assert a["attribute_value"] == [{"text": "Jeter"}]332def test_nameformat_email():333 assert utils.valid_email("foo@example.com")334 assert utils.valid_email("a@b.com")335 assert utils.valid_email("a@b.se")336 assert utils.valid_email("john@doe@johndoe.com") is False337def test_attribute():338 a = utils.factory(saml.Attribute,339 friendly_name="eduPersonScopedAffiliation",340 name="urn:oid:1.3.6.1.4.1.5923.1.1.1.9",341 name_format="urn:oasis:names:tc:SAML:2.0:attrname"342 "-format:uri")343 assert _eq(a.keyswv(), ["friendly_name", "name", "name_format"])344 a = utils.factory(345 saml.Attribute, friendly_name="eduPersonScopedAffiliation",346 name="urn:oid:1.3.6.1.4.1.5923.1.1.1.9",347 name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri",348 attribute_value=[saml.AttributeValue(text="member@example.com")])349 assert _eq(a.keyswv(), ["friendly_name", "name", "name_format",350 "attribute_value"])351def test_attribute_statement_2():352 statement = utils.factory(saml.Statement,353 attribute=[354 utils.factory(saml.Attribute,355 attribute_value=[356 utils.factory(357 saml.AttributeValue,358 text="Derek")],359 friendly_name="givenName"),360 utils.factory(saml.Attribute,361 attribute_value=[362 utils.factory(363 saml.AttributeValue,364 text="Jeter")],365 friendly_name="surName"),366 ])367 assert statement.keyswv() == ["attribute"]368 assert len(statement.attribute) == 2369def test_subject_confirmation_data():370 s = utils.factory(saml.SubjectConfirmation,371 in_response_to="_12345678",372 not_before="2010-02-11T07:30:00Z",373 not_on_or_after="2010-02-11T07:35:00Z",374 recipient="http://example.com/sp/",375 address="192.168.0.10")376 assert _eq(s.keyswv(), ["in_response_to", "not_before", "not_on_or_after",377 "recipient", "address"])378def test_subject_confirmation():379 s = utils.factory(saml.SubjectConfirmation,380 method="urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser",381 base_id="1234",382 name_id="abcd",383 subject_confirmation_data=utils.factory(384 saml.SubjectConfirmationData,385 in_response_to="_1234567890",386 recipient="http://example.com/sp/"))387 assert _eq(s.keyswv(),388 ["method", "base_id", "name_id", "subject_confirmation_data"])389 assert s.method == "urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser"390def test_authn_context_class_ref():391 a = utils.factory(saml.AuthnContextClassRef,392 text="urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified")393 assert a.keyswv() == ["text"]394 assert a.text == "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified"395def test_authn_context():396 accr = utils.factory(397 saml.AuthnContext,398 text="urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified")399 a = utils.factory(saml.AuthnContext, authn_context_class_ref=accr)400 assert a.keyswv() == ["authn_context_class_ref"]401def test_authn_statement():402 accr = utils.factory(403 saml.AuthnContextClassRef,404 text="urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified")405 ac = utils.factory(saml.AuthnContext,406 authn_context_class_ref=accr)407 ast = utils.factory(saml.AuthnStatement,408 authn_instant="2010-03-10T12:33:00Z",409 session_index="_12345",410 session_not_on_or_after="2010-03-11T12:00:00Z",411 authn_context=ac)412 assert _eq(ast.keyswv(), ["authn_instant", "session_index",413 "session_not_on_or_after",414 "authn_context"])415def test_signature():416 arr = ["foobar", "1234567890"]417 csum = utils.signature("abcdef", arr)418 arr.append(csum)419 assert utils.verify_signature("abcdef", arr)420def test_complex_factory():421 r = set_arg(Subject, 'in_response_to', '123456')422 subject = utils.factory(Subject, **r[0])423 assert _eq(subject.keyswv(), ['subject_confirmation'])424 assert _eq(subject.subject_confirmation.keyswv(),425 ['subject_confirmation_data'])426 assert _eq(subject.subject_confirmation.subject_confirmation_data.keyswv(),427 ['in_response_to'])...
link_prediction_feature_extractor_unittests.py
Source:link_prediction_feature_extractor_unittests.py
1import unittest2from DB.schema_definition import *3import datetime4from configuration.config_class import getConfig5from dataset_builder.feature_extractor.behavior_feature_generator import BehaviorFeatureGenerator6from dataset_builder.feature_extractor.key_author_score_feature_generator import KeyAuthorScoreFeatureGenerator7from dataset_builder.key_authors_model import KeyAuthorsModel8from dataset_builder.autotopic_executor import AutotopicExecutor9from dataset_builder.feature_extractor.syntax_feature_generator import SyntaxFeatureGenerator10from dataset_builder.feature_extractor.account_properties_feature_generator import AccountPropertiesFeatureGenerator11from dataset_builder.feature_extractor.link_prediction_feature_extractor import LinkPredictionFeatureExtractor12class LinkPredictionFeatureExtractorTest(unittest.TestCase):13 def setUp(self):14 self._config_parser = getConfig()15 self._domain = unicode(self._config_parser.get("DEFAULT", "domain"))16 self._db = DB()17 self._db.setUp()18 self._bad_actor_type = u'bad_actor'19 self._good_actor_type = u'good_actor'20 self._create_authors()21 self._graph_types = self._config_parser.eval("LinkPredictionFeatureExtractor", "graph_types")22 for type in self._graph_types:23 self._graph_type = unicode(type)24 self._create_connections()25 self._db.commit()26 authors = self._db.get_authors_by_domain(self._domain)27 posts = []28 parameters = {"authors": authors, "posts": posts}29 self._link_prediction_feature_extractor = LinkPredictionFeatureExtractor(self._db, **parameters)30 self._link_prediction_feature_extractor.execute()31 def tearDown(self):32 self._db.deleteDB()33 self._db.session.close()34 def testCommonNeighborsMeasure(self):35 author_feature = self._db.get_author_feature(u'g_1',36 u'link_prediction_min_common_neighbors_common_post_bad_actor')37 attribute_value = int(author_feature.attribute_value)38 self.assertEqual(attribute_value, 1)39 author_feature = self._db.get_author_feature(u'g_1',40 u"link_prediction_max_common_neighbors_common_post_bad_actor")41 attribute_value = int(author_feature.attribute_value)42 self.assertEqual(attribute_value, 2)43 author_feature = self._db.get_author_feature(u'g_1',44 u"link_prediction_mean_common_neighbors_common_post_bad_actor")45 attribute_value = float(author_feature.attribute_value)46 attribute_value = round(attribute_value, 2)47 self.assertEqual(attribute_value, 1.33)48 self._db.session.close()49 def testFriendsMeasure(self):50 author_feature = self._db.get_author_feature(u'g_5',51 u'link_prediction_min_friends_measure_common_post_bad_actor')52 attribute_value = int(author_feature.attribute_value)53 self.assertEqual(attribute_value, 1)54 author_feature = self._db.get_author_feature(u'g_5',55 u"link_prediction_max_friends_measure_common_post_bad_actor")56 attribute_value = int(author_feature.attribute_value)57 self.assertEqual(attribute_value, 7)58 author_feature = self._db.get_author_feature(u'g_5',59 u"link_prediction_mean_friends_measure_common_post_bad_actor")60 attribute_value = float(author_feature.attribute_value)61 self.assertEqual(attribute_value, 3.0)62 author_feature = self._db.get_author_feature(u'g_5',63 u'link_prediction_min_friends_measure_common_post_good_actor')64 attribute_value = int(author_feature.attribute_value)65 self.assertEqual(attribute_value, 4)66 author_feature = self._db.get_author_feature(u'g_5',67 u"link_prediction_max_friends_measure_common_post_good_actor")68 attribute_value = int(author_feature.attribute_value)69 self.assertEqual(attribute_value, 5)70 author_feature = self._db.get_author_feature(u'g_5',71 u"link_prediction_mean_friends_measure_common_post_good_actor")72 attribute_value = float(author_feature.attribute_value)73 attribute_value = round(attribute_value, 2)74 self.assertEqual(attribute_value, 4.67)75 self._db.session.close()76 def testFriendsMeasureDirectedGraph(self):77 author_feature = self._db.get_author_feature(u'g_5', u'link_prediction_min_friends_measure_citation_bad_actor')78 attribute_value = int(author_feature.attribute_value)79 self.assertEqual(attribute_value, 1)80 author_feature = self._db.get_author_feature(u'g_5', u"link_prediction_max_friends_measure_citation_bad_actor")81 attribute_value = int(author_feature.attribute_value)82 self.assertEqual(attribute_value, 1)83 author_feature = self._db.get_author_feature(u'g_5', u"link_prediction_mean_friends_measure_citation_bad_actor")84 attribute_value = float(author_feature.attribute_value)85 self.assertEqual(attribute_value, 1.0)86 author_feature = self._db.get_author_feature(u'g_5', u'link_prediction_min_friends_measure_citation_good_actor')87 attribute_value = int(author_feature.attribute_value)88 self.assertEqual(attribute_value, 1)89 author_feature = self._db.get_author_feature(u'g_5', u"link_prediction_max_friends_measure_citation_good_actor")90 attribute_value = int(author_feature.attribute_value)91 self.assertEqual(attribute_value, 2)92 author_feature = self._db.get_author_feature(u'g_5', u"link_prediction_mean_friends_measure_citation_good_actor")93 attribute_value = float(author_feature.attribute_value)94 attribute_value = round(attribute_value, 2)95 self.assertEqual(attribute_value, 1.33)96 self._db.session.close()97 def testPreferentialAttachment(self):98 author_feature = self._db.get_author_feature(u'g_1',99 u'link_prediction_min_preferential_attachment_common_post_bad_actor')100 attribute_value = int(author_feature.attribute_value)101 self.assertEqual(attribute_value, 6)102 author_feature = self._db.get_author_feature(u'g_1',103 u"link_prediction_max_preferential_attachment_common_post_bad_actor")104 attribute_value = int(author_feature.attribute_value)105 self.assertEqual(attribute_value, 12)106 author_feature = self._db.get_author_feature(u'g_1',107 u"link_prediction_mean_preferential_attachment_common_post_bad_actor")108 attribute_value = float(author_feature.attribute_value)109 self.assertEqual(attribute_value, 8.0)110 author_feature = self._db.get_author_feature(u'g_1',111 u'link_prediction_min_preferential_attachment_common_post_good_actor')112 attribute_value = int(author_feature.attribute_value)113 self.assertEqual(attribute_value, 3)114 author_feature = self._db.get_author_feature(u'g_1',115 u"link_prediction_max_preferential_attachment_common_post_good_actor")116 attribute_value = int(author_feature.attribute_value)117 self.assertEqual(attribute_value, 6)118 author_feature = self._db.get_author_feature(u'g_1',119 u"link_prediction_mean_preferential_attachment_common_post_good_actor")120 attribute_value = float(author_feature.attribute_value)121 self.assertEqual(attribute_value, 5.0)122 self._db.session.close()123 def testJaccard_Coefficient(self):124 author_feature = self._db.get_author_feature(u'g_1',125 u'link_prediction_min_preferential_attachment_common_post_bad_actor')126 attribute_value = int(author_feature.attribute_value)127 self.assertEqual(attribute_value, 6)128 author_feature = self._db.get_author_feature(u'g_1',129 u"link_prediction_max_preferential_attachment_common_post_bad_actor")130 attribute_value = int(author_feature.attribute_value)131 self.assertEqual(attribute_value, 12)132 author_feature = self._db.get_author_feature(u'g_1',133 u"link_prediction_mean_preferential_attachment_common_post_bad_actor")134 attribute_value = float(author_feature.attribute_value)135 self.assertEqual(attribute_value, 8.0)136 author_feature = self._db.get_author_feature(u'g_1',137 u'link_prediction_min_preferential_attachment_common_post_good_actor')138 attribute_value = int(author_feature.attribute_value)139 self.assertEqual(attribute_value, 3)140 author_feature = self._db.get_author_feature(u'g_1',141 u"link_prediction_max_preferential_attachment_common_post_good_actor")142 attribute_value = int(author_feature.attribute_value)143 self.assertEqual(attribute_value, 6)144 author_feature = self._db.get_author_feature(u'g_1',145 u"link_prediction_mean_preferential_attachment_common_post_good_actor")146 attribute_value = float(author_feature.attribute_value)147 self.assertEqual(attribute_value, 5.0)148 self._db.session.close()149 def testAdamic_Adar(self):150 author_feature = self._db.get_author_feature(u'g_1',151 u'link_prediction_min_adamic_adar_index_common_post_bad_actor')152 attribute_value = float(author_feature.attribute_value)153 attribute_value = round(attribute_value, 2)154 self.assertEqual(attribute_value, 0.72)155 author_feature = self._db.get_author_feature(u'g_1',156 u"link_prediction_max_adamic_adar_index_common_post_bad_actor")157 attribute_value = float(author_feature.attribute_value)158 attribute_value = round(attribute_value, 2)159 self.assertEqual(attribute_value, 2.89)160 author_feature = self._db.get_author_feature(u'g_1',161 u"link_prediction_mean_adamic_adar_index_common_post_bad_actor")162 attribute_value = float(author_feature.attribute_value)163 attribute_value = round(attribute_value, 2)164 self.assertEqual(attribute_value, 1.44)165 self._db.session.close()166 # Tests that error isnt thorwn when there is no author that is classified as one of the optional_classes in the config167 # This test should print Error to the console and log168 @unittest.skip("This test is not relevant here it should test 'AnchorAuthorsCreator' module")169 def testUnclassifiedOptionalClass(self):170 test = True171 try:172 temp = self._link_prediction_feature_extractor._optional_classes173 self._link_prediction_feature_extractor._optional_classes = ["not_an_actor"]174 self._link_prediction_feature_extractor.execute()175 except:176 test = False177 self.assertTrue(test)178 self._link_prediction_feature_extractor._optional_classes = temp179 self._db.session.close()180 # Tests that error isn't thrown when there isn't any function with the same name as measure_names in the config181 # This test should print Error to the console and log182 def testIncorrectMeasureNameInConfig(self):183 test = True184 try:185 temp = self._link_prediction_feature_extractor._measure_names186 self._link_prediction_feature_extractor._measure_names = ['hi', 'common_neighbors']187 self._link_prediction_feature_extractor.execute()188 except:189 test = False190 self.assertTrue(test)191 self._link_prediction_feature_extractor._measure_names = temp192 self._db.session.close()193 # Tests that error isn't thrown when there isn't any function with the same name as aggregation_functions in the config194 # This test should print Error to the console and log195 def testIncorrectAggregationFunctionInConfig(self):196 test = True197 try:198 temp = self._link_prediction_feature_extractor._aggregation_functions_names199 self._link_prediction_feature_extractor._aggregation_functions_names = ['lol']200 self._link_prediction_feature_extractor.execute()201 except:202 test = False203 self.assertTrue(test)204 self._link_prediction_feature_extractor._aggregation_functions_names = temp205 self._db.session.close()206 def _create_authors(self):207 authors = []208 author1 = Author()209 author1.name = u'1'210 author1.author_guid = u'g_1'211 author1.author_screen_name = u'TestUser1'212 author1.domain = self._domain213 author1.author_osn_id = 1214 authors.append(author1)215 author2 = Author()216 author2.name = u'2'217 author2.author_guid = u'g_2'218 author2.author_screen_name = u'TestUser2'219 author2.author_type = self._bad_actor_type220 author2.domain = self._domain221 author2.author_osn_id = 2222 authors.append(author2)223 author3 = Author()224 author3.name = u'3'225 author3.author_guid = u'g_3'226 author3.author_screen_name = u'TestUser3'227 author3.author_type = self._bad_actor_type228 author3.domain = self._domain229 author3.author_osn_id = 3230 authors.append(author3)231 author4 = Author()232 author4.name = u'4'233 author4.author_guid = u'g_4'234 author4.author_screen_name = u'TestUser4'235 author4.author_type = self._bad_actor_type236 author4.domain = self._domain237 author4.author_osn_id = 4238 authors.append(author4)239 author5 = Author()240 author5.name = u'5'241 author5.author_guid = u'g_5'242 author5.author_screen_name = u'TestUser5'243 author5.domain = self._domain244 author5.author_osn_id = 5245 authors.append(author5)246 author6 = Author()247 author6.name = u'6'248 author6.author_guid = u'g_6'249 author6.author_screen_name = u'TestUser6'250 author6.author_type = self._good_actor_type251 author6.domain = self._domain252 author6.author_osn_id = 6253 authors.append(author6)254 author7 = Author()255 author7.name = u'7'256 author7.author_guid = u'g_7'257 author7.author_screen_name = u'TestUser7'258 author7.author_type = self._good_actor_type259 author7.domain = self._domain260 author7.author_osn_id = 7261 authors.append(author7)262 author8 = Author()263 author8.name = u'8'264 author8.author_guid = u'g_8'265 author8.author_screen_name = u'TestUser8'266 author8.author_type = self._good_actor_type267 author8.domain = self._domain268 author8.author_osn_id = 8269 authors.append(author8)270 self._db.add_authors(authors)271 def _create_connections(self):272 author_connections = []273 author_connection_1_2 = AuthorConnection()274 author_connection_1_2.source_author_guid = u'g_1'275 author_connection_1_2.destination_author_guid = u'g_2'276 author_connection_1_2.connection_type = self._graph_type277 author_connection_1_2.weight = 1.0278 author_connection_1_2.insertion_date = datetime.datetime.now()279 author_connections.append(author_connection_1_2)280 author_connection_1_3 = AuthorConnection()281 author_connection_1_3.source_author_guid = u'g_1'282 author_connection_1_3.destination_author_guid = u'g_3'283 author_connection_1_3.connection_type = self._graph_type284 author_connection_1_3.weight = 1.0285 author_connection_1_3.insertion_date = datetime.datetime.now()286 author_connections.append(author_connection_1_3)287 author_connection_1_4 = AuthorConnection()288 author_connection_1_4.source_author_guid = u'g_1'289 author_connection_1_4.destination_author_guid = u'g_4'290 author_connection_1_4.connection_type = self._graph_type291 author_connection_1_4.weight = 1.0292 author_connection_1_4.insertion_date = datetime.datetime.now()293 author_connections.append(author_connection_1_4)294 author_connection_2_4 = AuthorConnection()295 author_connection_2_4.source_author_guid = u'g_2'296 author_connection_2_4.destination_author_guid = u'g_4'297 author_connection_2_4.connection_type = self._graph_type298 author_connection_2_4.weight = 1.0299 author_connection_2_4.insertion_date = datetime.datetime.now()300 author_connections.append(author_connection_2_4)301 author_connection_3_4 = AuthorConnection()302 author_connection_3_4.source_author_guid = u'g_3'303 author_connection_3_4.destination_author_guid = u'g_4'304 author_connection_3_4.connection_type = self._graph_type305 author_connection_3_4.weight = 1.0306 author_connection_3_4.insertion_date = datetime.datetime.now()307 author_connections.append(author_connection_3_4)308 author_connection_4_5 = AuthorConnection()309 author_connection_4_5.source_author_guid = u'g_4'310 author_connection_4_5.destination_author_guid = u'g_5'311 author_connection_4_5.connection_type = self._graph_type312 author_connection_4_5.weight = 1.0313 author_connection_4_5.insertion_date = datetime.datetime.now()314 author_connections.append(author_connection_4_5)315 author_connection_5_6 = AuthorConnection()316 author_connection_5_6.source_author_guid = u'g_5'317 author_connection_5_6.destination_author_guid = u'g_6'318 author_connection_5_6.connection_type = self._graph_type319 author_connection_5_6.weight = 1.0320 author_connection_5_6.insertion_date = datetime.datetime.now()321 author_connections.append(author_connection_5_6)322 author_connection_5_7 = AuthorConnection()323 author_connection_5_7.source_author_guid = u'g_5'324 author_connection_5_7.destination_author_guid = u'g_7'325 author_connection_5_7.connection_type = self._graph_type326 author_connection_5_7.weight = 1.0327 author_connection_5_7.insertion_date = datetime.datetime.now()328 author_connections.append(author_connection_5_7)329 author_connection_5_8 = AuthorConnection()330 author_connection_5_8.source_author_guid = u'g_5'331 author_connection_5_8.destination_author_guid = u'g_8'332 author_connection_5_8.connection_type = self._graph_type333 author_connection_5_8.weight = 1.0334 author_connection_5_8.insertion_date = datetime.datetime.now()335 author_connections.append(author_connection_5_8)336 author_connection_6_7 = AuthorConnection()337 author_connection_6_7.source_author_guid = u'g_6'338 author_connection_6_7.destination_author_guid = u'g_7'339 author_connection_6_7.connection_type = self._graph_type340 author_connection_6_7.weight = 1.0341 author_connection_6_7.insertion_date = datetime.datetime.now()342 author_connections.append(author_connection_6_7)...
interface.py
Source:interface.py
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""Tests for the attribute container interface."""4from __future__ import unicode_literals5import unittest6from plaso.containers import interface7from tests import test_lib as shared_test_lib8class AttributeContainerIdentifierTest(shared_test_lib.BaseTestCase):9 """Tests for the attribute container identifier."""10 def testCopyToString(self):11 """Tests the CopyToString function."""12 identifier = interface.AttributeContainerIdentifier()13 expected_identifier_string = '{0:d}'.format(id(identifier))14 identifier_string = identifier.CopyToString()15 self.assertEqual(identifier_string, expected_identifier_string)16class AttributeContainerTest(shared_test_lib.BaseTestCase):17 """Tests for the attribute container interface."""18 def testCopyToDict(self):19 """Tests the CopyToDict function."""20 attribute_container = interface.AttributeContainer()21 attribute_container.attribute_name = 'attribute_name'22 attribute_container.attribute_value = 'attribute_value'23 expected_dict = {24 'attribute_name': 'attribute_name',25 'attribute_value': 'attribute_value'}26 test_dict = attribute_container.CopyToDict()27 self.assertEqual(test_dict, expected_dict)28 def testGetAttributeNames(self):29 """Tests the GetAttributeNames function."""30 attribute_container = interface.AttributeContainer()31 attribute_container.attribute_name = 'attribute_name'32 attribute_container.attribute_value = 'attribute_value'33 expected_attribute_names = ['attribute_name', 'attribute_value']34 attribute_names = sorted(attribute_container.GetAttributeNames())35 self.assertEqual(attribute_names, expected_attribute_names)36 def testGetAttributes(self):37 """Tests the GetAttributes function."""38 attribute_container = interface.AttributeContainer()39 attribute_container.attribute_name = 'attribute_name'40 attribute_container.attribute_value = 'attribute_value'41 expected_attributes = [42 ('attribute_name', 'attribute_name'),43 ('attribute_value', 'attribute_value')]44 attributes = sorted(attribute_container.GetAttributes())45 self.assertEqual(attributes, expected_attributes)46 def testGetAttributeValueHash(self):47 """Tests the GetAttributeValuesHash function."""48 attribute_container = interface.AttributeContainer()49 attribute_container.attribute_name = 'attribute_name'50 attribute_container.attribute_value = 'attribute_value'51 attribute_values_hash1 = attribute_container.GetAttributeValuesHash()52 attribute_container.attribute_value = 'changes'53 attribute_values_hash2 = attribute_container.GetAttributeValuesHash()54 self.assertNotEqual(attribute_values_hash1, attribute_values_hash2)55 def testGetAttributeValuesString(self):56 """Tests the GetAttributeValuesString function."""57 attribute_container = interface.AttributeContainer()58 attribute_container.attribute_name = 'attribute_name'59 attribute_container.attribute_value = 'attribute_value'60 attribute_values_string1 = attribute_container.GetAttributeValuesString()61 attribute_container.attribute_value = 'changes'62 attribute_values_string2 = attribute_container.GetAttributeValuesString()63 self.assertNotEqual(attribute_values_string1, attribute_values_string2)64 def testGetIdentifier(self):65 """Tests the GetIdentifier function."""66 attribute_container = interface.AttributeContainer()67 identifier = attribute_container.GetIdentifier()68 self.assertIsNotNone(identifier)69 def testGetSessionIdentifier(self):70 """Tests the GetSessionIdentifier function."""71 attribute_container = interface.AttributeContainer()72 session_identifier = attribute_container.GetSessionIdentifier()73 self.assertIsNone(session_identifier)74 def testSetIdentifier(self):75 """Tests the SetIdentifier function."""76 attribute_container = interface.AttributeContainer()77 attribute_container.SetIdentifier(None)78 def testSetSessionIdentifier(self):79 """Tests the SetSessionIdentifier function."""80 attribute_container = interface.AttributeContainer()81 attribute_container.SetSessionIdentifier(None)82if __name__ == '__main__':...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!