Пример #1
1
 def add_role(self, name=None, id=None):
     id = id or uuid.uuid4().hex
     name = name or uuid.uuid4().hex
     roles = self._user.setdefault("roles", [])
     roles.append({"name": name})
     self._metadata.setdefault("roles", []).append(id)
     return {"id": id, "name": name}
Пример #2
1
def set_user_cookie_id():
    """
    Sets the user id in the global object if nothing is there 
    before each request
    This function works together with set_user_cookie in the after requests
    """
    # new fresh user
    if not request.cookies.get(config.COOKIE_ADSABS2_NAME):
        if current_user.is_anonymous():
            g.user_cookie_id = unicode(uuid.uuid4())
        else:
            g.user_cookie_id = current_user.get_id()
    # the user has already visited the web site
    else:
        if current_user.is_anonymous():
            # if the cookie is a valid UUID it's ok
            curr_cookie = request.cookies.get(config.COOKIE_ADSABS2_NAME)
            try:
                uuid.UUID(curr_cookie)
                g.user_cookie_id = curr_cookie
            # otherwise the app generates a new one
            except ValueError:
                g.user_cookie_id = unicode(uuid.uuid4())
        else:
            g.user_cookie_id = current_user.get_id()
Пример #3
1
    def test_auth_ref_load_with_overridden_arguments(self):
        new_auth_url = "https://newkeystone.com/v3"

        user_id = uuid.uuid4().hex
        user_name = uuid.uuid4().hex
        project_id = uuid.uuid4().hex

        first = client_fixtures.project_scoped_token(user_id=user_id, user_name=user_name, project_id=project_id)
        second = client_fixtures.project_scoped_token(user_id=user_id, user_name=user_name, project_id=project_id)
        self.stub_auth(json=first)
        self.stub_auth(json=second, base_url=new_auth_url)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            c = client.Client(user_id=user_id, password="password", project_id=project_id, auth_url=self.TEST_URL)
        cache = json.dumps(c.auth_ref)
        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            new_client = client.Client(auth_ref=json.loads(cache), auth_url=new_auth_url)
        self.assertIsNotNone(new_client.auth_ref)
        self.assertFalse(new_client.auth_ref.domain_scoped)
        self.assertTrue(new_client.auth_ref.project_scoped)
        self.assertEqual(new_auth_url, new_client.auth_url)
        self.assertEqual(user_name, new_client.username)
        self.assertIsNone(new_client.password)
        self.assertEqual(new_client.management_url, "http://admin:35357/v3")
Пример #4
1
    def test_facebook_token(self, _get_external_data, get_new_token):
        self.app.test_request_context().push()
        _get_external_data.return_value = FACEBOOK_GRAPH_DATA
        from rockpack.mainsite.services.oauth.api import FacebookUser

        long_lived_fb_token = "fdsuioncf3w8ryl38yb7y4eius"
        get_new_token.return_value = FacebookUser("facebook", long_lived_fb_token, 3600)

        user = self._new_user()
        token = uuid.uuid4().hex
        eu = FacebookUser("facebook", token, 3600)
        eu._user_data = FACEBOOK_GRAPH_DATA.copy()
        ExternalToken.update_token(user, eu)
        self.session.commit()

        e = ExternalToken.query.filter_by(external_token=long_lived_fb_token).one()
        self.assertEquals("facebook", e.external_system)
        self.assertEquals(user.username, e.user_rel.username)

        # test we can overwrite token
        new_token = uuid.uuid4().hex
        eu = FacebookUser("facebook", new_token, 172800)
        eu._user_data = FACEBOOK_GRAPH_DATA.copy()
        ExternalToken.update_token(user, eu)
        self.session.commit()

        e = ExternalToken.query.filter_by(user=user.id)
        self.assertEquals(1, e.count(), "only one token should exist")
        e = e.one()
        self.assertEquals(new_token, e.external_token, "saved token should match new token")
Пример #5
1
    def __init__(self, options):
        self.guid = str(uuid.uuid4()).upper()
        self.test_guid = str(uuid.uuid4()).upper()
        self.target_guids = {}
        self.version = version
        self.prefix = options.prefix
        self.libdir = options.libdir
        self.bindir = options.bindir
        self.includedir = options.includedir
        self.datadir = options.datadir
        self.mandir = options.mandir
        self.localedir = options.localedir
        self.backend = options.backend
        self.buildtype = options.buildtype
        self.strip = options.strip
        self.use_pch = options.use_pch
        self.unity = options.unity
        self.coverage = options.coverage
        self.warning_level = options.warning_level
        self.werror = options.werror
        self.user_options = {}
        self.external_args = {}  # These are set from "the outside" with e.g. mesonconf
        self.external_link_args = {}
        if options.cross_file is not None:
            self.cross_file = os.path.join(os.getcwd(), options.cross_file)
        else:
            self.cross_file = None

        self.compilers = {}
        self.cross_compilers = {}
        self.deps = {}
        self.ext_progs = {}
        self.ext_libs = {}
        self.modules = {}
Пример #6
1
    def test_update_project_returns_extra(self):
        """This tests for backwards-compatibility with an essex/folsom bug.

        Non-indexed attributes were returned in an 'extra' attribute, instead
        of on the entity itself; for consistency and backwards compatibility,
        those attributes should be included twice.

        This behavior is specific to the SQL driver.

        """
        tenant_id = uuid.uuid4().hex
        arbitrary_key = uuid.uuid4().hex
        arbitrary_value = uuid.uuid4().hex
        tenant = {
            "id": tenant_id,
            "name": uuid.uuid4().hex,
            "domain_id": DEFAULT_DOMAIN_ID,
            arbitrary_key: arbitrary_value,
        }
        ref = self.identity_man.create_project({}, tenant_id, tenant)
        self.assertEqual(arbitrary_value, ref[arbitrary_key])
        self.assertIsNone(ref.get("extra"))

        tenant["name"] = uuid.uuid4().hex
        ref = self.identity_api.update_project(tenant_id, tenant)
        self.assertEqual(arbitrary_value, ref[arbitrary_key])
        self.assertEqual(arbitrary_value, ref["extra"][arbitrary_key])
Пример #7
0
    def test_positional_parameters_expect_fail(self):
        """Ensure CrudManager raises TypeError exceptions.

        After passing wrong number of positional arguments
        an exception should be raised.

        Operations to be tested:
            * create()
            * get()
            * list()
            * delete()
            * update()

        """
        POS_PARAM_1 = uuid.uuid4().hex
        POS_PARAM_2 = uuid.uuid4().hex
        POS_PARAM_3 = uuid.uuid4().hex

        PARAMETERS = {
            "create": (POS_PARAM_1, POS_PARAM_2),
            "get": (POS_PARAM_1, POS_PARAM_2),
            "list": (POS_PARAM_1, POS_PARAM_2),
            "update": (POS_PARAM_1, POS_PARAM_2, POS_PARAM_3),
            "delete": (POS_PARAM_1, POS_PARAM_2),
        }

        for f_name, args in PARAMETERS.items():
            self.assertRaises(TypeError, getattr(self.manager, f_name), *args)
    def create_port(self, body):
        p = body.get("port")
        ret = {
            "status": "ACTIVE",
            "id": str(uuid.uuid4()),
            "mac_address": p.get("mac_address", "fa:16:3e:b8:f5:fb"),
            "device_id": p.get("device_id", str(uuid.uuid4())),
            "admin_state_up": p.get("admin_state_up", True),
            "security_groups": p.get("security_groups", []),
            "network_id": p.get("network_id"),
        }

        network = self._fake_networks[p["network_id"]]
        if "port_security_enabled" in p:
            ret["port_security_enabled"] = p["port_security_enabled"]
        elif "port_security_enabled" in network:
            ret["port_security_enabled"] = network["port_security_enabled"]

        port_security = ret.get("port_security_enabled", True)
        # port_security must be True if security groups are present
        if not port_security and ret["security_groups"]:
            raise exception.SecurityGroupCannotBeApplied()

        if network["subnets"]:
            ret["fixed_ips"] = [{"subnet_id": network["subnets"][0], "ip_address": "10.0.0.1"}]
        if not ret["security_groups"] and (port_security is None or port_security is True):
            for security_group in self._fake_security_groups.values():
                if security_group["name"] == "default":
                    ret["security_groups"] = [security_group["id"]]
                    break
        self._fake_ports[ret["id"]] = ret
        return {"port": ret}
Пример #9
0
def _generate_unique_module_name():
    import uuid

    name = str(uuid.uuid4())
    while name in sys.modules:
        name = str(uuid.uuid4())
    return name
Пример #10
0
    def __init__(self, data=None):

        c = TaskConstants()
        now = int(time.time())

        self.__values__ = {
            # Уникальный идентификатор задания
            "task_id": unicode(uuid.uuid4()),
            "base_id": unicode(uuid.uuid4()),
            "record_id": u"0",
            "queue_id": u"",
            "group_id": 0L,
            # Владелец задания, тот чей счёт используется
            "customer": u"",
            # Уникальный идентификатор правила тарифа
            "rate_id": u"",
            # Уникальный идентификатор метрики
            "metric_id": u"",
            # (Дупликация) стоймость метрики в тарифе
            "rate": 0L,
            # Текущее состояние задания
            "state": c.STATE_ENABLED,
            # Значение ресурса задания. Это может быть время или штуки
            "value": 0L,
            # Тайминги задания
            "time_create": now,
            "time_destroy": 0,
            # (Опциональные) биллинговые данные, описывающие характер VALUE
            "target_user": u"",
            "target_uuid": u"",
            "target_descr": u"",
        }
Пример #11
0
def lurker(sprite, watching_id, direction, reciprocate=True, absolute_lurker_id=False):
    return {
        "id": "lurkroom_%s" % (watching_id if watching_id else uuid.uuid4().hex),
        "type": "lurkroom",
        "sprite": "void",
        "entrances": "",
        "dimension": {
            "data": ["###", "#lh", "#_#", "___"],
            "exits": "",
            "wrap_mode": "bounded",
            "legend": {
                "#": {"sprite": "stone"},
                "_": {"sprite": "cobble"},
                "l": {
                    "id": ("%s_lurker" % watching_id) if watching_id else uuid.uuid4().hex,
                    "absolute_id": absolute_lurker_id,
                    "type": "lurker",
                    "sprite": sprite,
                    "song": "ibi wowo ema tut wowo wo, ibi rorowo roro beh wo roro",
                    "tick_speed": 1.0 / 4,
                },
                "h": {
                    "sprite": "glove",
                    "song": "tut ro bo%s" % direction,
                    "stitches": {"up": ("%s//%s" % (watching_id, "r" if reciprocate else "")) if watching_id else ""},
                    "tick_speed": 1.0 / 4,
                },
            },
        },
    }
Пример #12
0
def update(id, params, ts=0):
    """Recreate task"""

    with database.DBConnect(primarykey=id, autocommit=False) as db:

        ot = db.find_one("tasks", {"base_id": id, "record_id": "0"})
        if not ot:
            return

        nt = Task(ot)
        nt.set(params)
        nt.queue_id = str(uuid.uuid4())
        nt.task_id = str(uuid.uuid4())
        nt.time_create = ts or int(time.time())

        db.update(
            "tasks",
            {"base_id": id, "record_id": "0"},
            {"base_id": id, "record_id": str(uuid.uuid4()), "time_destroy": ts or int(time.time())},
        )

        db.insert("tasks", nt.values)
        db.insert("queue", {"id": nt.queue_id, "time_check": ts or int(time.time())})

        db.commit()
    def test_set_and_get(self):
        kvs = [(str(uuid.uuid4()), str(uuid.uuid4())) for i in range(0, 100)]
        for k, v in kvs:
            self.client.set(k, 0, 0, v)

        for k, v in kvs:
            self.client.get(k)
def main(client, advertiser_company_id):
    # Initialize appropriate service.
    activity_group_service = client.GetService("ActivityGroupService", version="v201505")

    # Create a short-term activity group.
    short_term_activity_group = {
        "name": "Short-term activity group #%s" % uuid.uuid4(),
        "companyIds": [advertiser_company_id],
        "clicksLookback": "1",
        "impressionsLookback": "1",
    }

    # Create a long-term activity group.
    long_term_activity_group = {
        "name": "Long-term activity group #%s" % uuid.uuid4(),
        "companyIds": [advertiser_company_id],
        "clicksLookback": "30",
        "impressionsLookback": "30",
    }

    # Create the activity groups on the server.
    activity_groups = activity_group_service.createActivityGroups([short_term_activity_group, long_term_activity_group])

    # Display results.
    for activity_group in activity_groups:
        print("Activity group with ID '%s' and name '%s' was created." % (activity_group["id"], activity_group["name"]))
Пример #15
0
    def test_delete_endpiont_port_failures(self, GivenException):
        fake_docker_network_id = hashlib.sha256(str(random.getrandbits(256))).hexdigest()
        fake_docker_endpoint_id = hashlib.sha256(str(random.getrandbits(256))).hexdigest()
        fake_neutron_network_id = str(uuid.uuid4())
        fake_neutron_subnet_v4_id = str(uuid.uuid4())
        fake_neutron_subnet_v6_id = str(uuid.uuid4())
        fake_neutron_port_id = str(uuid.uuid4())

        self._mock_out_network(fake_neutron_network_id, fake_docker_network_id)
        self.mox.StubOutWithMock(app.neutron, "list_ports")
        fake_ports = self._get_fake_ports(
            fake_docker_endpoint_id,
            fake_neutron_network_id,
            fake_neutron_port_id,
            fake_neutron_subnet_v4_id,
            fake_neutron_subnet_v6_id,
        )
        app.neutron.list_ports(network_id=fake_neutron_network_id).AndReturn(fake_ports)
        self._delete_port_with_exception(fake_neutron_port_id, GivenException)

        response = self._invoke_delete_request(fake_docker_network_id, fake_docker_endpoint_id)

        self.assertEqual(GivenException.status_code, response.status_code)
        decoded_json = jsonutils.loads(response.data)
        self.assertIn("Err", decoded_json)
        self.assertEqual({"Err": GivenException.message}, decoded_json)
Пример #16
0
    def test_can_manage_repositories(self):
        user = str(uuid.uuid4())
        user2 = str(uuid.uuid4())
        repo = str(uuid.uuid4())
        repo2 = str(uuid.uuid4())

        yield self.gandalf.user_new(user, {})
        yield self.gandalf.user_new(user2, {})

        created = yield self.gandalf.repository_new(repo, [user])
        expect(created).to_be_true()

        response = yield self.gandalf.repository_get(repo)
        expect(response).to_include("git_url")
        expect(response).to_include("ssh_url")
        expect(response).to_include("name")
        expect(response).to_include("public")

        renamed = yield self.gandalf.repository_update(repo, name=repo2)
        expect(renamed).to_be_true()

        granted = yield self.gandalf.repository_grant([user2], [repo2])
        expect(granted).to_be_true()

        # TODO: gandalf server needs to accept delete without body
        # response = yield self.gandalf.repository_revoke([user2], [repo2])
        # expect(response.code).to_equal(200)

        removed = yield self.gandalf.repository_delete(repo2)
        expect(removed).to_be_true()

        yield self.gandalf.user_delete(user)
        yield self.gandalf.user_delete(user2)
Пример #17
0
    def _create_subnet_with_exception(self, neutron_network_id, docker_endpoint_id, ex):
        fake_neutron_subnet_v4_id = str(uuid.uuid4())
        fake_neutron_subnet_v6_id = str(uuid.uuid4())

        self.mox.StubOutWithMock(app.neutron, "create_subnet")
        fake_subnet_request = {
            "subnets": [
                {
                    "name": "-".join([docker_endpoint_id, "192.168.1.0"]),
                    "network_id": neutron_network_id,
                    "ip_version": 4,
                    "cidr": "192.168.1.0/24",
                },
                {
                    "name": "-".join([docker_endpoint_id, "fe80::"]),
                    "network_id": neutron_network_id,
                    "ip_version": 6,
                    "cidr": "fe80::/64",
                },
            ]
        }
        fake_subnets = self._get_fake_subnets(
            docker_endpoint_id, neutron_network_id, fake_neutron_subnet_v4_id, fake_neutron_subnet_v6_id
        )

        if ex:
            app.neutron.create_subnet(fake_subnet_request).AndRaise(ex)
        else:
            app.neutron.create_subnet(fake_subnet_request).AndReturn(fake_subnets)
        self.mox.ReplayAll()

        return (fake_neutron_subnet_v4_id, fake_neutron_subnet_v6_id)
Пример #18
0
    def test_dup_domain(self):
        openstack_driver = FakeExtensionManager.get_extension_objects("vnc_cfg_api.resync")[0]
        orig_ks_domains_list = openstack_driver._ks_domains_list
        orig_ks_domain_get = openstack_driver._ks_domain_get
        try:
            openstack_driver._ks_domains_list = openstack_driver._ksv3_domains_list
            openstack_driver._ks_domain_get = openstack_driver._ksv3_domain_get
            logger.info('Creating first domain in "keystone"')
            dom_id = str(uuid.uuid4())
            dom_name = self.id()
            test_case.get_keystone_client().domains.add_domain(dom_id, dom_name)
            dom_obj = self._vnc_lib.domain_read(id=dom_id)
            self.assertThat(dom_obj.name, Equals(dom_name))

            logger.info('Creating second domain with same name diff id in "keystone"')
            new_dom_id = str(uuid.uuid4())
            test_case.get_keystone_client().domains.add_domain(new_dom_id, dom_name)
            new_dom_obj = self._vnc_lib.domain_read(id=new_dom_id)
            self.assertThat(new_dom_obj.name, Not(Equals(dom_name)))
            self.assertThat(new_dom_obj.name, Contains(dom_name))

            self._vnc_lib.domain_delete(id=dom_id)
            self._vnc_lib.domain_delete(id=new_dom_id)
        finally:
            openstack_driver._ks_domains_list = orig_ks_domains_list
            openstack_driver._ks_domain_get = orig_ks_domain_get
Пример #19
0
    def setUp(self):
        # Basic setup and mock/fake structures for testing only
        super(TestDatastoreBase, self).setUp()
        util.init_db()
        self.rand_id = str(uuid.uuid4())
        self.ds_name = "my-test-datastore" + self.rand_id
        self.ds_version = "my-test-version" + self.rand_id
        self.capability_name = "root_on_create" + self.rand_id
        self.capability_desc = "Enables root on create"
        self.capability_enabled = True
        self.datastore_version_id = str(uuid.uuid4())
        self.flavor_id = 1

        datastore_models.update_datastore(self.ds_name, False)
        self.datastore = Datastore.load(self.ds_name)

        datastore_models.update_datastore_version(self.ds_name, self.ds_version, "mysql", "", "", True)
        DatastoreVersionMetadata.add_datastore_version_flavor_association(
            self.ds_name, self.ds_version, [self.flavor_id]
        )

        self.datastore_version = DatastoreVersion.load(self.datastore, self.ds_version)
        self.test_id = self.datastore_version.id

        self.cap1 = Capability.create(self.capability_name, self.capability_desc, True)
        self.cap2 = Capability.create("require_volume" + self.rand_id, "Require external volume", True)
        self.cap3 = Capability.create("test_capability" + self.rand_id, "Test capability", False)
Пример #20
0
    def create_request_token(
        self, consumer_id, project_id, token_duration, request_token_id=None, request_token_secret=None
    ):
        if request_token_id is None:
            request_token_id = uuid.uuid4().hex
        if request_token_secret is None:
            request_token_secret = uuid.uuid4().hex
        expiry_date = None
        if token_duration:
            now = timeutils.utcnow()
            future = now + datetime.timedelta(seconds=token_duration)
            expiry_date = utils.isotime(future, subsecond=True)

        ref = {}
        ref["id"] = request_token_id
        ref["request_secret"] = request_token_secret
        ref["verifier"] = None
        ref["authorizing_user_id"] = None
        ref["requested_project_id"] = project_id
        ref["role_ids"] = None
        ref["consumer_id"] = consumer_id
        ref["expires_at"] = expiry_date
        session = sql.get_session()
        with session.begin():
            token_ref = RequestToken.from_dict(ref)
            session.add(token_ref)
        return token_ref.to_dict()
    def setUp(self):
        super(CertificatesViewsTests, self).setUp()
        self.client = Client()
        self.course = CourseFactory.create(org="testorg", number="run1", display_name="refundable course")
        self.course_id = self.course.location.course_key
        self.user = UserFactory.create(email="joe_user@edx.org", username="joeuser", password="foo")
        self.user.profile.name = "Joe User"
        self.user.profile.save()
        self.client.login(username=self.user.username, password="foo")
        self.request = RequestFactory().request()

        self.cert = GeneratedCertificate.objects.create(
            user=self.user,
            course_id=self.course_id,
            verify_uuid=uuid4(),
            download_uuid=uuid4(),
            download_url="http://www.example.com/certificates/download",
            grade="0.95",
            key="the_key",
            distinction=True,
            status="generated",
            mode="honor",
            name=self.user.profile.name,
        )
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course_id)
        CertificateHtmlViewConfigurationFactory.create()
        LinkedInAddToProfileConfigurationFactory.create()
Пример #22
0
    def create_access_token(self, request_token_id, token_duration, access_token_id=None, access_token_secret=None):
        if access_token_id is None:
            access_token_id = uuid.uuid4().hex
        if access_token_secret is None:
            access_token_secret = uuid.uuid4().hex
        session = sql.get_session()
        with session.begin():
            req_token_ref = self._get_request_token(session, request_token_id)
            token_dict = req_token_ref.to_dict()

            expiry_date = None
            if token_duration:
                now = timeutils.utcnow()
                future = now + datetime.timedelta(seconds=token_duration)
                expiry_date = utils.isotime(future, subsecond=True)

            # add Access Token
            ref = {}
            ref["id"] = access_token_id
            ref["access_secret"] = access_token_secret
            ref["authorizing_user_id"] = token_dict["authorizing_user_id"]
            ref["project_id"] = token_dict["requested_project_id"]
            ref["role_ids"] = token_dict["role_ids"]
            ref["consumer_id"] = token_dict["consumer_id"]
            ref["expires_at"] = expiry_date
            token_ref = AccessToken.from_dict(ref)
            session.add(token_ref)

            # remove request token, it's been used
            session.delete(req_token_ref)

        return token_ref.to_dict()
Пример #23
0
    def tst_dump_formats(self):
        from uuid import uuid4
        from os.path import join
        import os

        os.environ["DIALS_REGRESSION"] = self.path

        # Get all the filenames
        filename1 = join(self.path, "experiment_test_data", "experiment_1.json")

        # Read all the experiment lists in
        elist1 = ExperimentListFactory.from_json_file(filename1)

        # Create the experiment list dumper
        dump = ExperimentListDumper(elist1)

        # Dump as JSON file and reload
        filename = "temp%s.json" % uuid4().hex
        dump.as_json(filename)
        elist2 = ExperimentListFactory.from_json_file(filename)
        self.check(elist1, elist2)

        # Dump as split JSON file and reload
        filename = "temp%s.json" % uuid4().hex
        dump.as_json(filename, split=True)
        elist2 = ExperimentListFactory.from_json_file(filename)
        self.check(elist1, elist2)

        # Dump as pickle and reload
        filename = "temp%s.pickle" % uuid4().hex
        dump.as_pickle(filename)
        elist2 = ExperimentListFactory.from_pickle_file(filename)
        self.check(elist1, elist2)
Пример #24
0
    def test_auth(self):
        username = uuid.uuid4().hex
        password = uuid.uuid4().hex

        digest_auth = "%s:%s" % (username, password)
        acl = self._makeAuth(username, password, all=True)

        self.client.add_auth("digest", digest_auth)
        self.client.default_acl = (acl,)

        try:
            self.client.create("/1")
            self.client.create("/1/2")
            self.client.ensure_path("/1/2/3")

            eve = self._get_client()
            eve.start()

            self.assertRaises(NoAuthError, eve.get, "/1/2")

            # try again with the wrong auth token
            eve.add_auth("digest", "badbad:bad")

            self.assertRaises(NoAuthError, eve.get, "/1/2")
        finally:
            # Ensure we remove the ACL protected nodes
            self.client.delete("/1", recursive=True)
            eve.stop()
            eve.close()
Пример #25
0
    def test_multiple_delivery_with_multiple_ack(self):
        data = str(uuid.uuid4())
        data2 = str(uuid.uuid4())
        client = yield self.quick_register(use_webpush=True)
        yield client.disconnect()
        ok_(client.channels)
        yield client.send_notification(data=data)
        yield client.send_notification(data=data2)
        yield client.connect()
        yield client.hello()
        result = yield client.get_notification()
        ok_(result != {})
        ok_(result["data"] in map(urlsafe_b64encode, [data, data2]))
        result2 = yield client.get_notification()
        ok_(result2 != {})
        ok_(result2["data"] in map(urlsafe_b64encode, [data, data2]))
        yield client.ack(result2["channelID"], result2["version"])
        yield client.ack(result["channelID"], result["version"])

        yield client.disconnect()
        yield client.connect()
        yield client.hello()
        result = yield client.get_notification()
        eq_(result, None)
        yield self.shut_down(client)
Пример #26
0
 def new_ref(self, **kwargs):
     kwargs = super(CredentialTests, self).new_ref(**kwargs)
     kwargs.setdefault("data", uuid.uuid4().hex)
     kwargs.setdefault("project_id", uuid.uuid4().hex)
     kwargs.setdefault("type", uuid.uuid4().hex)
     kwargs.setdefault("user_id", uuid.uuid4().hex)
     return kwargs
Пример #27
0
    def createCharacteristicValueList(self, value_attributes):

        value = value_attributes[0]
        try:
            typeValue = value_attributes.Term_Accession_Number
        except AttributeError:
            typeValue = ""

        try:
            unitValue = value_attributes.Unit
        except AttributeError:
            unitValue = ""

        if unitValue:
            characteristicValue = dict(
                [
                    ("@id", "https://repo.metadatacenter.org/UUID" + str(uuid4())),
                    ("@type", "https://repo.metadatacenter.org/model/CharacteristicValue"),
                    ("type", dict([("_value", "")])),
                    ("unit", dict([("_value", unitValue), ("@type", typeValue)])),
                    ("value", dict([("_value", value)])),
                ]
            )
        else:
            characteristicValue = dict(
                [
                    ("@id", "https://repo.metadatacenter.org/UUID" + str(uuid4())),
                    ("@type", "https://repo.metadatacenter.org/model/CharacteristicValue"),
                    ("type", dict([("_value", typeValue)])),
                    ("unit", dict([("_value", unitValue)])),
                    ("value", dict([("_value", value)])),
                ]
            )

        return characteristicValue
Пример #28
0
    def test_create_access_token_expires_at(self):
        verifier = uuid.uuid4().hex
        consumer_key = uuid.uuid4().hex
        consumer_secret = uuid.uuid4().hex
        request_key = uuid.uuid4().hex
        request_secret = uuid.uuid4().hex

        t = self._new_oauth_token_with_expires_at()
        access_key, access_secret, expires_at, resp_ref = t

        headers = {"Content-Type": "application/x-www-form-urlencoded"}
        self.stub_url("POST", [self.path_prefix, "access_token"], status_code=201, text=resp_ref, headers=headers)

        # Assert that the manager creates an access token object
        access_token = self.manager.create(consumer_key, consumer_secret, request_key, request_secret, verifier)
        self.assertIsInstance(access_token, self.model)
        self.assertEqual(access_key, access_token.key)
        self.assertEqual(access_secret, access_token.secret)
        self.assertEqual(expires_at, access_token.expires)

        req_headers = self.requests_mock.last_request.headers
        oauth_client = oauth1.Client(
            consumer_key,
            client_secret=consumer_secret,
            resource_owner_key=request_key,
            resource_owner_secret=request_secret,
            signature_method=oauth1.SIGNATURE_HMAC,
            verifier=verifier,
        )

        self._validate_oauth_headers(req_headers["Authorization"], oauth_client)
Пример #29
0
    def create_stack(self, stack_name="test_stack2", params={}):
        temp = template_format.parse(test_template_waitcondition)
        template = parser.Template(temp)
        parameters = parser.Parameters(stack_name, template, params)
        ctx = context.get_admin_context()
        ctx.tenant_id = "test_tenant"
        stack = parser.Stack(ctx, stack_name, template, parameters, disable_rollback=True)
        # Stub out the UUID for this test, so we can get an expected signature
        self.m.StubOutWithMock(uuid, "uuid4")
        uuid.uuid4().AndReturn("STACKABCD1234")
        self.m.ReplayAll()
        stack.store()

        self.m.StubOutWithMock(scheduler.TaskRunner, "_sleep")
        scheduler.TaskRunner._sleep(mox.IsA(int)).AndReturn(None)

        # Stub waitcondition status so all goes CREATE_COMPLETE
        self.m.StubOutWithMock(wc.WaitConditionHandle, "get_status")
        wc.WaitConditionHandle.get_status().AndReturn(["SUCCESS"])

        # Stub keystone() with fake client
        self.m.StubOutWithMock(wc.WaitConditionHandle, "keystone")
        wc.WaitConditionHandle.keystone().MultipleTimes().AndReturn(self.fc)

        id = identifier.ResourceIdentifier("test_tenant", stack.name, stack.id, "", "WaitHandle")
        self.m.StubOutWithMock(wc.WaitConditionHandle, "identifier")
        wc.WaitConditionHandle.identifier().MultipleTimes().AndReturn(id)

        self.m.ReplayAll()
        stack.create()

        return stack
Пример #30
0
    def handle(self):
        salt = uuid4().hex
        input = self.request.input
        input.password = tech_account_password(uuid4().hex, salt)

        with closing(self.odb.session()) as session:
            cluster = session.query(Cluster).filter_by(id=input.cluster_id).first()

            # Let's see if we already have an account of that name before committing
            # any stuff into the database.
            existing_one = (
                session.query(TechnicalAccount)
                .filter(Cluster.id == input.cluster_id)
                .filter(TechnicalAccount.name == input.name)
                .first()
            )

            if existing_one:
                raise Exception("Technical account [{0}] already exists on this cluster".format(input.name))

            try:
                tech_account = TechnicalAccount(
                    None, input.name, input.is_active, input.password, salt, cluster=cluster
                )
                session.add(tech_account)
                session.commit()

            except Exception, e:
                msg = "Could not create a technical account, e:[{e}]".format(e=format_exc(e))
                self.logger.error(msg)
                session.rollback()

                raise
            else: